Error Handling

pravin_gaire_023f91e4e5a2

Pravin Gaire

Posted on August 28, 2024

Error Handling

useEffect(() => {
async function fetchPlaces() {
setIsFetching(true);
try {
const places = await
fetchAvailablePlaces();

navigator.geolocation.getCurrentPosition((position)=> {
const sortedPlaces = sortPlacesByDistance(
places,
position.coords.latitude,
position.coords.longitude
);
setAvailablePlaces(sortedPlaces);
setIsFetching(false);
})

} catch(error) {
setError({
message:
error.message || 'Could not fetch places, please try again later'});
}
setIsFetching(false);
}
fetchPlaces();

}, [])

if(error) {
return(

);
}

** Separate file for fetching and getting data **

export async function fetchAvailablePlaces(){
const response = await
fetch('http://localhost:3000/places');
const resData = await response.json();

  if(!response.ok) {
    throw new Error('Failed to fetch places');
  }

 return  resData.places;
Enter fullscreen mode Exit fullscreen mode

}

I would like to know how is this approach to handle error while building react app.

💖 💪 🙅 🚩
pravin_gaire_023f91e4e5a2
Pravin Gaire

Posted on August 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related