Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am not able to render 2 components based on result of 2 fetch call using Promise.allSettled() if one of them throws error

I am sending two fetch calls in a Promise.allSettled() and rendering components based on the result a component with data if it is fulfilled and an error component if rejected. The problem is when one of them throws error an error component for that is rendered but the component with data for other call is not rendering? Why is this happening?

code:

 const sendRequest=useCallback(async (url)=>{
        setIsLoading([true,true]);
        setError([null,null]);

        let response;

        try{
            response=await Promise.allSettled( [fetch(url[0]),fetch(url[1])]);

            
            if(!response[0].value.ok){
                throw new Error('Something went wrong');
            }

            const data1=await response[0].value.json();

            if(!response[1].value.ok){
                throw new Error('Something went wrong');
            }

            const data2=await response[1].value.json();

            setItems([[data1.results],[data2.results]]);
        }
        catch(err){
            if(!response[0].value.ok) {setError([err.message || 'Something went wrong',error[1]])};
            if(!response[1].value.ok){setError([error[0],err.message || 'Something went wrong'])};
        }
        setIsLoading([false,false]);
    },[])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

this is because the setItems([[data1.results],[data2.results]]); method is not getting called, if any of your request if giving error you are executing throw new Error('Something went wrong') which will make the code execution to catch block & your setItems([[data1.results],[data2.results]]); method will not get executed. Please have a look at below code that will solve your problem.

        let error = false;
        if(!response[0].value.ok){
            error =true;
        }else{
          const data1=await response[0].value.json();
        }
        if(!response[1].value.ok){
           error =true;
        }else{
         const data2=await response[1].value.json();
        }
        setItems([[data1.results],[data2.results]]);
        if(error){
         throw new Error('Something went wrong')
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading