1

I have a function that, when initialized, takes a previously set state and uses it to make an api call with axios:

 _onRefresh = () => {
    this.setState({ refreshing: true }, () => {
      axios.get(this.state.currentPath)
        .then(res=>{
          console.log(res.data)
          this.props.loadCards(res.data) 
        })
        this.setState({refreshing: false})
    });
  }

I can see that the promise is never completed, and that a response is not given.

However, on the first use after the page loads, the function works correctly; it's only on subsequent usage that it does not work.

When the get request does not work, I've taken the path that's been stored in state, made a request in postman, and received a valid result.

Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
schoenbl
  • 663
  • 2
  • 14
  • 29

3 Answers3

1

you should cancel the refreshing in the finally block

get(...)
.then(...)
.catch(...)
.finally(() => this.setState({refreshing: false}))
cucaracho
  • 174
  • 6
0

Does this fix the issue?

_onRefresh = () => {
this.setState({ refreshing: true }, () => {
  axios.get(this.state.currentPath)
    .then(res=>{
      console.log(res.data)
      this.props.loadCards(res.data)
      this.setState({refreshing: false}) // moved this line into the then block
    })    
});

}

oemera
  • 3,223
  • 1
  • 19
  • 33
0

Try this

_onRefresh =async () => {
    this.setState({ refreshing: true }, () => {
   await axios.get(this.state.currentPath) //you might need to handle promises to get this working.
        .then(res=>{
          console.log(res.data)
          this.props.loadCards(res.data) 
        })
        this.setState({refreshing: false})
    });
  }
Rishav Kumar
  • 4,979
  • 1
  • 17
  • 32