Possible Unhandled Promise Rejection Error

0

I have a problem calling a 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, whenever I put headers , it gives the following error

  

Possible Unhandled Promise Rejection

And when I do, it works again, remembering that 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})
    }
    
asked by anonymous 11.03.2018 / 00:39

1 answer

0

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

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

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