Sometimes we want to share to our users what’s going on with his network requests, because as we all know, unfortunately those the network requests can fail, and when they do, handling and displaying them in an automated and reusable way without not repeating ourselves rewriting try/catch blocks all over and then somehow handling those errors and displaying them in the UI.
I will assume that you already have basic knowledge of Redux, ReduxToolkit and React.
Lets start creating a simple create-react-app with a reducer that will set the reusable modals whenever the network requests
First, we'll create actions using the createAsyncThunk method, whether they are actually async or not. You can still use them to dispatch data to the reducers as if the were in the reducers object of the slice .
The actions would look like this:
And the slice/reducer:
Great, so we can now dispatch open and close a modal with an id and any content that we want. But that doesn’t do a lot at the moment.
Now comes the magic. Let’s add a wrapper that we will call asyncThunkHandleError that will act as a high order component for all our thunks and will catch any error.
Here's the js version to make it more clear
Next, we’ll create two thunks, one to get a positive response and one to force an error.
Now let’s add a button in the component that will trigger these two requests. Our component — I did this project with create-react-app— will look like this:
If we console.log the store modals we’ll see that a new modal object is added at every new network error, that means that if we perform a set of several requests at once we’ll have one modal element, per failed request. Cool huh?
Now we should somehow display this information to the user. Let’s add a simple modal css-only modal.
And finally, once we have this modal, we have to map every modal by id. This we’ll have one modal per error. If N requests failed, then N modals will be open and the user will be able to see one modal per failed request.
Resulting into this:
To evidentiate the multi-modal feature, I’ve added the option to dispatch more errors inside the modal component. If you click the error button N times you’ll get N more modals, one displayed over another, so you’ll be able to get one error per failed request without missing any errors.
Every ok click will close that specific modal.
And that was it. I hope that this article will make your error handling easier in your next projects..
If you want to see the sample code you can find it here and run it by yourself.
First posted in Medium