Possible Unhandled Promise Rejection Error

Asked

Viewed 8,393 times

0

I’m having a problem calling one API, and this problem only happens in a certain situation, an example:

// Situação que funciona perfeitamente

    const response = await axios.get('https://localhost:8080/api/appcompras/catalogues?scheme_url=company&page=${this.state.page}`)
    const catalogues = await response.data

    this.setState({
        result: [...this.state.result, ...catalogues.response.data],
        page: page + 1,
        loading: false,
    })

// Situação que não funciona
const options = {
            headers: {
                Authorization: 'Bearer ' + this.state.token
            }
        }

        const response = await axios.get(`https://localhost:8080/api/appcompras/catalogues?scheme_url=namine&page=${this.state.page}`, options)
        const catalogues = await response.data

        this.setState({
            result: [...this.state.result, ...catalogues.response.data],
            page: page + 1,
            loading: false,
        }) 

So the question is, every time I headers, he gives the following error

Possible Unhandled Promise Rejection

And when I take it off, it comes back to working naturally, remembering that the this.state.token is called to be populated in componentWillMount.

async componentWillMount(){
        const dados = JSON.parse(await AsyncStorage.getItem('@MySuperStore:dados')) 
        console.log(dados.token)
        this.setState({token: dados.token})
    }

1 answer

0

Most likely the API is returning an error (HTTP), and Axios generates an exception (which is not being handled) in this case.

When using async/await, the ideal is to do the asynchronous operations in a try-catch:

try {
  const response = await axios.get('...')
} catch (error) {
  // Tratar o erro adequadamente
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.