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]);
},[])
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')
}
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.