Home > Software engineering >  Possible Unhandled promise Rejection (id: 0) JSON Parse value in try catch block
Possible Unhandled promise Rejection (id: 0) JSON Parse value in try catch block

Time:09-29

I am calling APIs using Yelp but warning shoes me Possible Unhandled promise Rejection (id: 0) again and again please help hear is code

const [resturantData, setResturantData] = React.useState(localResturant);


    const getResturantFromYelp = () => {
        const yelpurl = 'https://www.yelp.com/developers/documentation/v3/business_search?term=resturants&location=SanDiego';

    const apiOptions = {
        headers:{
            Authorization: `Bearer ${YELP_API_KEY}`,
        },
    };
    try {
        return  fetch(yelpurl, apiOptions)
        .then((res) => res.json())
        .then((json) =>  setResturantData(JSON.stringify(json.businesses)))
    } catch (error) {
        console.log(error)
    }
        
    };
    useEffect(() => {
       getResturantFromYelp();
    }, []);

the rendering code map here

export default function ResturantItems({resturant_Data}) {
  return (
    <TouchableOpacity activeOpacity={1} style={{marginBottom:15}}>{
        
        resturant_Data.map((resturant, index)=> (

     <View key={index} style={{
        backgroundColor: '#fff',
        padding: 7,
        marginTop: 7
    }}>
        <ResturantImage image={resturant.image_url} />
        <ResturantInfo  name={resturant.name} rating={resturant.rating} />
    </View>
))

CodePudding user response:

If promise has error or any then callback has error use catch block to handle error

As @caTS mentioned remove JSON.stringfy the reponse, unless you need the data in string format.

 fetch(yelpurl, apiOptions)
        .then((res) => res.json())
        .then((json) =>  setResturantData(json.businesses))
        .catch((error) => {
               console.log(error); // if error in promise this catch block will be executed
               // return empty response or throw error to execute try catch block
        });

CodePudding user response:

can you try this one async and await keywords and remove return keyword

    const getResturantFromYelp = async () => {
...
...
...
        await fetch(yelpurl, apiOptions)
        .then((res) => res.json())
        .then((json) =>  setResturantData(JSON.stringify(json.businesses)))
    } catch (error) {
...
...
...
  • Related