1

Sometime back Dan tweeted

"I cringe when I see

`.then(() => dispatch(...)).catch(...)` 

in React projects. If a component throws during dispatch, you’ll get into catch."

And says the solution is so simple. Just don’t chain catch() after then() that renders UI. Instead pass error handler as second arg to then().

Can someone explain why this is the case.

In my case I am making an ajax call, so I assume I will get inside then for anything that is 200 as a server response and inside catch for anything that is not 200, i.e. error from server. Am I missing something here?

1 Answer 1

3

So what Dan means is that in a Async request, you would expect the success call to result in .then() being called, and since you are dispatching an action in .then() which in turn will update the redux store and thus the UI, so if there is any error in the UI update process, .catch() will also be called and whereas you would expect it to only be called when the server returns an error

the solution is to handle it like

.then(
function (){
    //handle success
    dispatch({...})
},
function () {
    //handle reject() and Error for Async request

})
Sign up to request clarification or add additional context in comments.

4 Comments

So is it like there should not be any then catch and instead always try to use the approach above, because in most of the cases after successful response from an API call, we will endup setting something in state via dispatch which will in turn render UI. Also for the cases which dont disptach inside then, is this solution feasible?
It sure is, but should definitely be preferred when you update the UI form the .then() callback
and how can I code a case where I have an API call and on its success only I want to call another API call and on its success another API call, based on the solution mentioned above? I would like to handle errrors on each calls.
I am not sure about this case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.