Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
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]);
    },[])
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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')
        }
about 4 years ago · Juan Pablo Isaza Denunciar

0

I improved the code above which was posted by @abhishek sahu. It is best to work with clause guards when checking for errors. Errors should not be used as flags in the flow. When an error happens it should immediately be thrown, not wait till the end of the code/function. Some other error could happen in between and you will not know if you use flags as errors.

const hanndleCallsAsync = async () =>{
    if(!response[0].value.ok)
        throw new Error('Something wrong went with reponse0');
    if(!response[1].value.ok){
           throw new Error('Something wrong went with reponse1');

    const data1=await response[0].value.json();        
    const data2=await response[1].value.json();
    setItems([[data1.results],[data2.results]]);
    ....

}

Now, your code is much shorter and easier to read and figure out where the error occurred.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda