0

My problem is that I get a response from the BE but I'm unable to assign it to a variable in the FE. This is my code:

  componentDidMount = async () => {
    try {
      const response = await fetch('http://localhost:8080/classes/all', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if(response.ok){
      const classes = await response.json();
        console.log('classes' + classes);
        this.setState({
          classes,
          selectedClass : classes[0],
          selectedSubject : classes[0].subjects[0].name
        });
      }
    } catch (error) {
      this.setState({ error });
      alert(error.stack);
    }
  };

And the network returns an array of 4 classes, so no problem there... I'm wondering what it up with my code?

  • Do you get any error? – mpsq Dec 04 '20 at 12:57
  • Yeah - "SyntaxError: Unexpected end of input at App.componentDidMount (http://localhost:3000/static/js/main.chunk.js:171:40)". Which honestly tells me nothing :( – FireAndBlood Dec 04 '20 at 13:10
  • One error I can see is the call to `fetch`. `fetch` takes only 2 params. You need to merge the 2nd and 3rd params. See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch. You probably also want to check `response.ok` before trying to parse with `json()`. – mpsq Dec 04 '20 at 13:16
  • ok, I updated my code accordingly, but I'm still unable to assign it. It never gets to response.json() since the response.ok returns false :( – FireAndBlood Dec 04 '20 at 13:27
  • Partially it did. I removed it. Turns out I had to set CORS in the BE and now it works like a charm. Thanks :) – FireAndBlood Dec 04 '20 at 14:35

0 Answers0