abeikverdi abeikverdi - 6 months ago 64
React JSX Question

Best practice to handle errors in Redux and React

I have an asynchronous function in my redux actions and it returns an object like this in my reducer:

user: {},
fetching: false,
fetched, false,
error: null

So basically when I start calling the asynchronous function I update the redux state to
fetching: true
and if the result is successfully fulfilled then

So I map the redux state to props using connect in react-redux and I added this in my component's render function:

if(this.props.fetched) {
// Go to next page

And it automatically goes to the next page once the data is fetched.

However, I have a problem with my error handling. When error changes from null to error then how do I handle the error handling on my react component. What I have right now is:

if(this.props.error != null) {
// popup error

But now I end up in a situation that next time I call my action it already has this.props.error assigned to an error and its not null which results it displaying the popup even if there is no error.

Do I have to reset my error everytime it is displayed or is there any better practice of doing this whole thing?


You can use the redux-catch middleware to capture the errors for Redux reducers and middlewares.

You can use something like,

import reduxCatch from 'redux-catch';

function errorHandler(error, getState, lastAction, dispatch) {
    //dispatch action as you need.

const store = createStore(reducer, applyMiddleware(