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]);
},[])
CodePudding user response:
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')
}