Javascript Axios How to return status 404 from function

Viewed 254

I had a problem how to return axios status from function. I have found the solution but I feel there is a better option. I have tried many ways but only this one works. Is this solution correct? or I should find another?

export const getPerson = async (patient) => {
  try {
    const res = await axios.post('/api/user',patient)
    return res.data
  } catch (err) {
    return err.response.status
  }
};

onSubmit = async () =>{
        await getPerson({id:this.state.id})
        .then(data => {
            if(data === 404){
                this.setState({errorStatus:data})
            }
            console.log(data)
        })
    }

Also Can someone explain to me why in this example then and catch execute simultaneously.

onSubmit = async () =>{
        await getPerson({id:this.state.id})
        .then(data => {
            console.log(data)
        })
        .catch( err => console.log(err)
    }

2 Answers

A better approach in my opinion would be to have the same object structure returned in both cases. The difference would be in what the object contains.

export const getPerson = async (patient) => {
   try {
     const res = await axios.post('/api/user',patient)
     return {data: res.data, status: 200}
   } catch (err) {
     return {data: {}, status: err.status}
   }
};

With this, you can just check the error status if you want to determine if data is valid or not based on the response status, with checking the status.

if (data.status === 200) {
   console.log(data)
}
else {
   this.setState({errorStatus: data.status})
}

For your question, i suppose that the post request throws an error, so it starts with the .then() function and then the post request throws an error, which is caught by .error()

Why not just let the error flow to the calling function if you want to handle the error there?

export const getPerson = patient => axios.post('/api/user', patient)

onSubmit = async () => {
  try {
    const res = await getPerson({ id: this.state.id })
    console.log(res);
  }
  catch (err) {
    this.setState({ errorStatus: err.response.status })
  }
}
Related