"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Error Handling

Error Handling

Published on 2024-09-02
Browse:490

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;

}

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

Release Statement This article is reproduced at: https://dev.to/pravin_gaire_023f91e4e5a2/error-handling-3903?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3