0

I am trying to fetch a big json file when the webpage has been loaded and then update react state with that data.

Currently, I have this code

get(url) {
 return new Promise((resolve, reject) => {
   const req = new XMLHttpRequest();
   req.open('GET', url);
   req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
   req.onerror = (e) => reject(Error(`Network Error: ${e}`));
   req.send();
 });

}

componentDidMount(){
  this.get('https://x.com/data/tool.json').then((response) =>{
    this.setState({"sections" : response});
    console.log(this.state);
  }).catch((err) =>{
    console.log(err);
  });
}

The code sets sections to a sting as shown in the screenshot instead of the actual json object.

react setstate problem

How can I initialize state with the fetched json.

3
  • Did you try JSON.parse the string ? Commented Jul 18, 2017 at 9:35
  • You need to use JSON.parse to parse the string. Commented Jul 18, 2017 at 9:39
  • I have tried that many tmes. Also tried JSON.stringify first to ensure everything go right bu no luck. Commented Jul 18, 2017 at 9:51

1 Answer 1

3

Firstly I would recommend using the fetch library instead of Promises and XMLHttpRequest. If you need to support IE 11 and below, you can use a polyfill

Sticking with your code though, at no point do you appear to use JSON.parse on your response, to turn the JSON string you get back into a JavaScript object.

this.setState({"sections" : JSON.parse(response)});

This would be much easier and cleaner with fetch though I feel,

componentDidMount(){
  fetch('https://abx.com/data/tool.json').then(response =>{
    if (!response.ok) throw Error('Response not ok')

    return response.json(); // This is built in JSON.parse wrapped as a Promise
  }).then(json => {
    this.setState({"sections" : json});
  }).catch(err =>{
    console.log(err);
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this works. I have reinstalled babel-loader after which your code worked perfectly. I don't know why yarn installed binaries don't work as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.