Reputation: 1406
I'm new to hooks
and async/await
. I'm trying to handle errors in an Axios call and I'm unsure of how to use then/catch
or try/catch
to handle errors with my API call.
In class based React I would handle errors like this:
componentDidMount() {
axios.get('url')
.then((res) => {
// handle response here
})
.catch((err) => {
//handle error here
})
};
How can I handle Axios error handling when using useEffect
and async/await
? I've seen examples using try/catch
but I can't get it to work in my code.
How can I add error handling to the following API call :
useEffect(() => {
const fetchData = async () => {
setLoading(true);
const data = await axios.get(`https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=Miami&state_code=FL&limit=100&offset=0`, headers);
const properties = data.data.properties;
console.log(properties);
/// Iterates through data and grabs all the data for house listings
const listings = properties.map((listing, index) => {
const arr = [];
arr.push(
listing.listing_id,
listing.address.line,
listing.address.city,
listing.address.county,
listing.address.neighborhood_name,
listing.address.state,
listing.year_built,
listing.address.lat,
listing.address.lon);
arr.push(listing.photos.map((photo) => {
return photo.href;
}));
return arr;
});
// House listing data is put into houseData
//getHouseData(listings);
setListings(listings);
setLoading(false);
}
fetchData();
}, [])
Upvotes: 0
Views: 4386
Reputation: 593
Here's the thing about axios. It returns promises, not the value it gets. You need to use that to handle errors. For that you need the then()
and catch()
method. Example:
useEffect(() => {
const fetchData = async () => {
setLoading(true);
await axios.get(`https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=Miami&state_code=FL&limit=100&offset=0`, headers).then((response)=>{
/* DO STUFF WHEN THE CALLS SUCCEEDS */
setLoading(false);
}).catch((e)=>{
/* HANDLE THE ERROR (e) */
});
}
fetchData();
}, [])
Basically, you tell the promise: If the call succeeds, run the function in then
, with the response as a parameter. If it fails, run the function in catch
, with the exception as a parameter. Then, you launch fetchData(). You need to handle your data that you received inside the then
block, because the promise won't directly return it. And if there's an issue, it'll go in the catch
block, and you handle your error there (maybe set an error message in the state and show it?).
This is a big part of asynchronous programming, and it's still a bit fuzzy for me, but this is a good start to handle your errors more adequatly.
Upvotes: 1