Home > Web Front-end > JS Tutorial > body text

Error Handling

王林
Release: 2024-08-29 12:32:09
Original
383 people have browsed it

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;
Copy after login

}

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

The above is the detailed content of Error Handling. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!