Search code examples
javascriptreactjscomponentsundefinedsettimeout

How to delay return in React.js for load data from JSON


So far, I have tried several methods that I found on the internet, but none has worked. I tried setTimeout and setting isLoading like in code right now.

As for loading the data, I am sure that they appear correctly because after deleting loading the brand in the paragraph, the data is visible in the console (more precisely in the React 'Components' add-on)

This is what a JSON file looks like:

[
   {
    id: 0,
    brand: "Lorem0",
    model: "Lorem",
    dealer: "Lorem",
    main_image: "Lorem",
    sections: [
        {
            id: 0,
            section_type: "",
            section_title: "Lorem",
            section_text: "Lorem Lorem Lorem Lorem Lorem",
            image_left: "Lorem1.png",
            image_center: null,
            image_right: null
        }
      ]
   },
   {
    id: 1,
    brand: "Lorem0",
    model: "Lorem",
    dealer: "Lorem",
    main_image: "Lorem",
    sections: [
        {
            id: 0,
            section_type: "",
            section_title: "Lorem",
            section_text: "Lorem Lorem Lorem Lorem Lorem",
            image_left: "Lorem1.png",
            image_center: null,
            image_right: null
        }
      ]
   },    
]

And this is the code from App.js:

state = {
   isLoading: true,
}
carData = [];

componentDidMount() {
   fetch("/data.json")
     .then(response => response.json())
     .then(data => {
       this.setState({
         carData: data,
         isLoading: false
       })
     })
 }
 render() {
   return (
     <div className="App">
       {!this.state.isLoading && <p>{this.carData[1].brand}</p>}
     </div>
   );
 }

Maybe I am making a mistake that I cannot see but it seems to me that everything is fine but the error still shows up.

TypeError: Cannot read property 'brand' of undefined


Solution

  • You are storing data in state but you are not trying to load data from state.

    Try something like below:-

    state = {
       isLoading: true,
       carData: []  // initialize carData with blank array in state 
    }
    
    
    componentDidMount() {
       fetch("/data.json")
         .then(response => response.json())
         .then(data => {
           this.setState({
             carData: data,
             isLoading: false
           })
         })
     }
     render() {
       return (
         <div className="App">
           {!this.state.isLoading && <p>{this.state.carData[1].brand}</p>}   // use carData with this.state.carData
         </div>
       );
     }