0

In the console I'm getting two outputs , one with empty array and another one with the updated array . I only need the updated array after the component did mount function.. How can I eliminate the first one...

class App extends Component {
  state={
    categories:[]
  };

  componentDidMount() { 
    axios.get(`https://s3.ap-south-1.amazonaws.com/scapic-others/json/models.json`)
      .then(response => {
             this.setState({categories:response.data.categories });
         })
    };

  render() {
    return (  
        <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" /></header>
          <h1 className="shake-opacity shake-freeze">3D models</h1>
         {console.log(this.state.categories)}
        </header>
        <footer className="pv4 ph3 ph5-m ph6-l red">
            <small className="f6 db tc">© 2018 <b className="ttu">Scapic Inc</b>., All Rights Reserved</small>
            <div className="tc mt3">
               {`Made by Renjith`}
            </div>
        </footer>
      </div>
    );
  }
}

export default App;
hannad rehman
  • 4,133
  • 3
  • 33
  • 55
ReNinja
  • 543
  • 2
  • 10
  • 27

1 Answers1

2

The reason that you get two console outputs is because componentDidMount is executed after render which triggers an API call that returns the response asynchronously. Once the response is available, you call setState that triggers another render and hence the second output.

Considering the behaviour that you need, you need to have a loading state, which is shown till the data is not available

class App extends Component {
  state={
    categories:[],
    isLoading: true
  };

  componentDidMount() { 
    axios.get(`https://s3.ap-south-1.amazonaws.com/scapic-others/json/models.json`)
      .then(response => 
        {this.setState({categories:response.data.categories, isLoading: false });
         })
    };


  render() {
    if (isLoading) {
        return <div>Loading...</div>
    }
    return (  
        <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" /></header>
          <h1 className="shake-opacity shake-freeze">3D models</h1>
         {console.log(this.state.categories)}





  <footer className="pv4 ph3 ph5-m ph6-l red">
            <small className="f6 db tc">© 2018 <b className="ttu">Scapic Inc</b>., All Rights Reserved</small>
            <div className="tc mt3">
               {`Made by Renjith`}
            </div>
        </footer>


      </div>



    );
  }
}

export default App;
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400