How to clear error message coming from redux actions

I have an API that can return an error. In simplified form, the component looks like this. The question is when the error occurs, what are 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);

      

+3


source to share


2 answers


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

Personally, I've always used the first method, letting you take the form submission as an example. When the user submits the form, you fire up form-submit/request

and can show the loading message. If the form is submitted correctly, you shoot form-submit

, and if an error occurs, you shoot form-submit/error

by setting the error in the gearbox. Then in form-submit/request

you clear the error, so the user gets feedback if an error occurs, but if the form is submitted again, the error will be cleared. If you don't want to do anything when the form is submitted, which is odd, you can clear the startup errorform-submit

... The downside to this approach is that if, for example, you want to clear an error when some form field is changed, you will have to add another action and make an undefined error for that action.



Now, if you hit the close button on the error component, you can reuse the React React component, but for every API call you will have to have an action action/dismiss-error

and set the error to undefined on the reducer for each one, this can get very tedious quickly.

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

+1


source


Quote from docs:

The store stores the entire state tree of your application. The only way to change the state inside it is to send an action to it.



What is it. If you are storing something in redux state, then to change its value you need to dispatch an action.

+1


source







All Articles