react-async-hook
react-async-hook copied to clipboard
Fix unhandled promise rejection propagation
In executeAsyncOperation the promise rejection scenario is not properly handled. It captures the error, saves it in state, but then it propagates further and causes exceptions in the codebase. I suggest to change the implementation to this
return promise
.then((result) => {
if (shouldHandlePromise(promise)) {
AsyncState.setResult(result);
}
normalizedOptions.onSuccess(result, {
isCurrent: () => CurrentPromise.is(promise),
});
})
.catch((error) => {
if (shouldHandlePromise(promise)) {
AsyncState.setError(error);
}
normalizedOptions.onError(error, {
isCurrent: () => CurrentPromise.is(promise),
});
});
instead of
promise.then(() => {}, () => {});
I have the same probleme. I have to try cath my requests even if I use onError to handle error
const resultRef = useRef();
const { result } = useAsync(async( $params, $condition ){
if($condition){
return await yourPromiseFunction($params).then((response)=>{
//handle your response
if( response is error ){
const error: Error = {
name: "Error Occurred",
message: "Error",
stack: "no stack"
console.error(error.name, res.ResultMessage);
throw error;
}
}
})
}
},
[params, condition],
{
setLoading: (state) => ({
...state
result: resultRef.current ?? state.result,
loading: true
}),
setResult: (result, asyncState) => ({
...asyncState,
result:
result === undefined ? resultRef .current : result,
loading: false
}),
onSuccess: ( result , { isCurrent })=>{
if (isCurrent()) {
resultRef.current = result ?? resultRef.current;
//do the rest
}
},
onError:()=>{}
}
)