Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear error message coming from redux actions

Tags:

reactjs

redux

I have an API, which may return an error. In the simplistic form, the component reads as below. The question is, when an error occurs, what is the steps to dismiss/clear the error message?

class LoginError extends Component {
    render() {
        return (
            {
                this.props.error != null ?
                    <h2>this.props.error</h2> :
                    undefined
            }
        )
    }
}

const mapStateToProps = (state) => {
    return {
        error: state.error
    };
}


export default connect(mapStateToProps, null)(LoginError);
like image 776
nomadus Avatar asked Aug 05 '17 04:08

nomadus


2 Answers

There is no straight forward way to do this, you basically have two options: set the error to undefined in the reducer when another action fires, or provide a close button on the error itself using a reusable error component, that dispatches an action that will set the error to undefined in the reducer.

Personally i've always used the first method, lets take the submit of a form as an example. When the user submits the form you fire form-submit/request and maybe show a loading message. If the form is sent correctly you fire form-submit and if an error happens you fire form-submit/error, setting the error in the reducer. Then in form-submit/request you clear the error, so the user gets feedback if an error happens but if the form is submitted again the error is cleared. If you don't want to do anything when the form is submitted, which is odd, you can clear the error when form-submit is fired. The downside of this approach is that if for example you want to clear the error when any field of the form is changed, you'll have to add another action and make the error undefined for that action as well.

Now if you put a close button in the error component you can reuse the error React component, but you'll have to have a action/dismiss-error action for every API call and set the error to undefined on the reducer for each one of them, this can get very tedious quickly.

The best approach for me is to use the first method, but choosing carefully how much errors you display for each page or section. This way each page can have its error section that will be displayed for any API call that is associated with the page and you only need an error action for each page, not for every API call.

like image 191
Marco Scabbiolo Avatar answered Nov 09 '22 23:11

Marco Scabbiolo


Quote from docs:

A store holds the whole state tree of your application. The only way to change the state inside it is to dispatch an action on it.

That's it. If you keep something in redux state then to change it's value you have to dispatch an action.

like image 23
Tomasz Mularczyk Avatar answered Nov 09 '22 23:11

Tomasz Mularczyk