Sharath Chandra
Sharath Chandra

Reputation: 704

Handle errors in react native and redux

I have a react native application using redux for state management. On every API request, I have actions dispatched which is handled by reducer. This is then forwarded to saga and back to reducer.

I am using snackbar to show any errors which might have happened.

e.g. In the login flow, one of the operations is to fetch the OTP for username.

The action types are:

The initial state for the reducer (LoginReducer) is

{
    hasError: false,
    error : {
       display_message : "",
       details : null
    }
    otherData : []
}

Now in case of GET_OTP_FOR_USER_FAILURE, the reducer will be updated to

{
    hasError: true,
    error : {
       display_message : "Invalid Username",
       details : null
    }
    otherData : []
}

In my view component, I conditionally render the snackbar based on the hasError flag

{this.props.hasError ? Snackbar.show({
                title: this.props.error.display_message,
                duration: Snackbar.LENGTH_LONG
            }) : null}

If I don't reset the hasError, then the snackbar keeps coming for every setState call (which happens on textinputchange).

The current approach I am using is, I have an action to RESET_ERROR. I call this action once the setState is called on the textbox on the component (in this case the username)

onUserNameTextChanged = (text) => {

    this.props.resetError(); //Reset the error

    this.setState({ //something });

}

The issue with this is that this.props.resetError(); will get called on every character update. Just to ensure that I don't call render multiple time, I am using shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState){
    if(this.props.hasError && (this.props.hasError === nextProps.hasError))
        return false;
    else
        return true;
}

I am not sure if there is simpler or cleaner approach to handle these scenarios. Any directions will be helpful.

Upvotes: 0

Views: 496

Answers (1)

Matt Aft
Matt Aft

Reputation: 8936

You can just conditionally call it if there's an error, that way you're not always invoking it:

onUserNameTextChanged = (text) => {
    if (this.props.hasError) {
        this.props.resetError(); //Reset the error
    }

    this.setState({ //something });

}

You can also tie it into the success action if you want that error to show until the API returns successfully.

Upvotes: 1

Related Questions