1

I have a problem, a friend of mine and I have decided that we will create a site where school children can come and learn programming, solve problems, and take part in programming contests. The site we are doing in NextJS, and using Material UI, TailwindCSS. Sanity IO and MongoDB are the backend. I haven't published it yet, site link: https://brackets.vercel.app/ So far, everything is going well, but I'm stuck in one place. The problem is, there will be a complete problem on the right side of the problem-solving page and a code compiler on the right side where the user can solve the problem sitting on our site without using a separate editor, just like Leetcode, edabit, and some other online judge. Our Problem Solving Page: (https://brackets.vercel.app/problemset/two-sum) We can't bring any code compiler to NextJS in any way. Even if you can code here but, you can't run. We found a video on YouTube on how to build a compiler on MERN Stack but we are not working here despite coding exactly like him.

As far as I understand I solved the tiny errors by going to Google and Stackoverflow but couldn't in the end, note that he used Mac, we used Windows, all my known developers are from programming hero, 2 days in a row. I have held live meetings on request and I have not found any solution several times. Then I got another blog where he copied to React, we also got to React, the problem is that whenever I want to bring it to NextJs, I get two errors, "Can't set property localStorage of # which has only a getter" Resolved but, running on local server, whenever I reload, it gives "loaclStorage is not defined" error,

Got another solution, but the same situation, I went to deploy Vercel is giving error, I have attached all the tutorial links and screenshots sir. I tried my best, talked to many, but no one could do anything about it. So I annoyed you at the end without giving up. How can I do this help me a, please? I don't think we can do without your cooperation.

I've followed this tutorial = https://www.youtube.com/watch?v=RZ66yGyEKFg (not working after 24 min on video)

I've try this blog - https://medium.com/dsckiit/make-your-own-online-compiler-in-react-%EF%B8%8F-b06bc29dd202 (its working on react but when I convert it to nextJs it gives me error)

Code:

import React, { Component } from "react";

import "./Compiler.css";
export default class Compiler extends Component {
  constructor(props) {
    super(props);
    this.state = {
      input: localStorage.getItem('input')||``,
      output: ``,
      language_id:localStorage.getItem('language_Id')|| 2,
      user_input: ``,
    };
  }
  input = (event) => {
 
    event.preventDefault();
  
    this.setState({ input: event.target.value });
    localStorage.setItem('input', event.target.value)
 
  };
  userInput = (event) => {
    event.preventDefault();
    this.setState({ user_input: event.target.value });
  };
  language = (event) => {
   
    event.preventDefault();
   
    this.setState({ language_id: event.target.value });
    localStorage.setItem('language_Id',event.target.value)
   
  };

  submit = async (e) => {
    e.preventDefault();

    let outputText = document.getElementById("output");
    outputText.innerHTML = "";
    outputText.innerHTML += "Creating Submission ...\n";
    const response = await fetch(
      "https://judge0-ce.p.rapidapi.com/submissions",
      {
        method: "POST",
        headers: {
          "x-rapidapi-host": "judge0-ce.p.rapidapi.com",
          "x-rapidapi-key": "*****************",
          "content-type": "application/json",
          accept: "application/json",
        },
        body: JSON.stringify({
          source_code: this.state.input,
          stdin: this.state.user_input,
          language_id: this.state.language_id,
        }),
      }
    );
    outputText.innerHTML += "Submission Created ...\n";
    const jsonResponse = await response.json();

    let jsonGetSolution = {
      status: { description: "Queue" },
      stderr: null,
      compile_output: null,
    };

    while (
      jsonGetSolution.status.description !== "Accepted" &&
      jsonGetSolution.stderr == null &&
      jsonGetSolution.compile_output == null
    ) {
      outputText.innerHTML = `Creating Submission ... \nSubmission Created ...\nChecking Submission Status\nstatus : ${jsonGetSolution.status.description}`;
      if (jsonResponse.token) {
        let url = `https://judge0-ce.p.rapidapi.com/submissions/${jsonResponse.token}?base64_encoded=true`;

        const getSolution = await fetch(url, {
          method: "GET",
          headers: {
            "x-rapidapi-host": "judge0-ce.p.rapidapi.com",
            "x-rapidapi-key": "******************",
            "content-type": "application/json",
          },
        });

        jsonGetSolution = await getSolution.json();
      }
    }
    if (jsonGetSolution.stdout) {
      const output = atob(jsonGetSolution.stdout);

      outputText.innerHTML = "";

      outputText.innerHTML += `Results :\n${output}\nExecution Time : ${jsonGetSolution.time} Secs\nMemory used : ${jsonGetSolution.memory} bytes`;
    } else if (jsonGetSolution.stderr) {
      const error = atob(jsonGetSolution.stderr);

      outputText.innerHTML = "";

      outputText.innerHTML += `\n Error :${error}`;
    } else {
      const compilation_error = atob(jsonGetSolution.compile_output);

      outputText.innerHTML = "";

      outputText.innerHTML += `\n Error :${compilation_error}`;
    }
  };
  render() {
 
    return (
      <>
        <div className="row container-fluid">
          <div className="col-6 ml-4 ">
            <label htmlFor="solution ">
              <span className="badge badge-info heading mt-2 ">
                <i className="fas fa-code fa-fw fa-lg"></i> Code Here
              </span>
            </label>
            <textarea
              required
              name="solution"
              id="source"
              onChange={this.input}
              className=" source"
              value={this.state.input}
            ></textarea>

            <button
              type="submit"
              className="btn btn-danger ml-2 mr-2 "
              onClick={this.submit}
            >
              <i className="fas fa-cog fa-fw"></i> Run
            </button>

            <label htmlFor="tags" className="mr-1">
              <b className="heading">Language:</b>
            </label>
            <select
              value={this.state.language_id}
              onChange={this.language}
              id="tags"
              className="form-control form-inline mb-2 language"
            >
              <option value="54">C++</option>
              <option value="50">C</option>
              <option value="62">Java</option>
              <option value="71">Python</option>
            </select>
          </div>
          <div className="col-5">
            <div>
              <span className="badge badge-info heading my-2 ">
                <i className="fas fa-exclamation fa-fw fa-md"></i> Output
              </span>
              <textarea id="output"></textarea>
            </div>
          </div>
        </div>

        <div className="mt-2 ml-5">
          <span className="badge badge-primary heading my-2 ">
            <i className="fas fa-user fa-fw fa-md"></i> User Input
          </span>
          <br />
          <textarea id="input" onChange={this.userInput}></textarea>
        </div>
      </>
    );
  }
}

This is not working on NextJS, giving error localstorage is not defined

h0r53
  • 3,034
  • 2
  • 16
  • 25
  • Welcome to StackOverflow. The convention here is that we don't write your project for you but we can help with actual problems you have in code you have written. Try adding a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to your post to better enable people to help you with your problem. – David Jones Oct 04 '21 at 20:48
  • Thanks. Should I edit my post and put the code here? – Farhan Ahmed Oct 04 '21 at 20:58
  • Yes, please edit the post to include some code. That would definitely be a step in the right direction. – David Jones Oct 04 '21 at 21:00
  • I've edited with my code, this code is not working on nextJS. – Farhan Ahmed Oct 04 '21 at 21:23
  • I've edited your question to remove what looked like a valid `x-rapidapi-key`. You should consider purging this key and acquiring a new one if it was indeed a sensitive key. Another word of advice, if you are creating a site where users submit code and you compile and run that code in your backend, you should be VERY careful what code you allow others to run on your system. For starters, I'd execute the code in a restricted, containerized, environment to mitigate potential harm. – h0r53 Oct 04 '21 at 21:30
  • Sorry about that, I must take a new one. Thanks a lot – Farhan Ahmed Oct 04 '21 at 21:32
  • Does this help answer your question: [In reactjs and nextjs constructor getting Reference Error: localstorage is not defined](https://stackoverflow.com/questions/59540321/in-reactjs-and-nextjs-constructor-getting-reference-error-localstorage-is-not-d)? Try moving the `localStorage` logic to `componentDidMount` instead. – juliomalves Oct 05 '21 at 08:40

0 Answers0