Home > Blockchain >  React doesn't display without conditional rendering from api
React doesn't display without conditional rendering from api

Time:12-15

Why does the component not render/display anything when I fetch data from an api? This code below just gives me a blank page

 render(){
    return (
      <div>
        <p>{this.state.character[0]}</p>
      </div>
    )
  }

But when I do some conditional rendering it displays the data.

 render(){
    return (
      <div>
        {<p>{this.state.character? this.state.character[0] : null}</p>}
      </div>
    )
  }

CodePudding user response:

Data from API takes time to load, so the first code doesn't have any data as the request from the API is not completed. you cannot access the index of something that has nothing in it. So the condition basically is making it safe to display.

CodePudding user response:

How are you fetching the data? in componentDidMount() hopefully. componentDidMount() runs AFTER render() meaning, when the component first loads/mounts, there is no data. The data gets received then added to state AFTER the component is mounted

  • Related