Iggy
Iggy

Reputation: 5251

How to delay componentDidMount API fetching in React?

I am GETting data using Axios and wanted to make loading animation longer (for personal reason).

  componentDidMount(){
    var that = this;
    axios.get('api.something.io.json', {
        params: data
      })
      .then(function (response) {
        console.log(response);
        that.setState({
          axiosResponse: response.data,
          isLoading: false
        })
      })
      .catch(function (error) {
        console.log(error);
      });
  };
  ...
  render() {
    if(this.state.isLoading){
      return <div>Waiting...</div>
    }

    return (
      <div className="App">
        <h1>{this.state.axiosResponse.awesomeTitle}</h1>
      </div>
    );

Right now Waiting... shows up for a split second before main component renders. I would like to extend the "Waiting..." to last a little longer, about 2-3 seconds. I tried using setTimeout on componentDidMount but it didn't seem to work.

componentDidMount(){
  setTimeout(this.setState({isLoading: 1}), 3000);
  //do axios call here
}

I have also tried to stub the setTimeout inside .then call:

  componentDidMount(){
    var that = this;
    axios.get('https://api.rss2json.com/v1/api.json', {
        params: data
      })
      .then(function (response) {
        console.log(response);
        setTimeout(
          that.setState({
            axiosResponse: response.data,
            isLoading: false
          })
          , 3000);

      })
  ...

None worked. How can extend the isLoading by 3 seconds?

Upvotes: 3

Views: 6873

Answers (1)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93203

setTimeout accepts function as first argument:

    setTimeout(function() {
      that.setState({
        axiosResponse: response.data,
        isLoading: false
      })
     }, 3000); 

and not :

     setTimeout(
          that.setState({
            axiosResponse: response.data,
            isLoading: false
          }), 3000); 

Upvotes: 6

Related Questions