Nathan Bergeron
Nathan Bergeron

Reputation: 105

How to prevent showing the same error multiple times with Redux?

I'm relatively new to React and Redux, but I have a basic understanding of how the actions+store+reducers work to enable one way dataflow.

One issue that I've run into as I write my actual app is how to display alerts for errors exactly once per unique error.

The solution that I've come up with works quite well, but I feel like it shouldn't be required, or that with my inexperience I might be missing something.

Essentially it boils down to this:

/* In the reducer: */
const initialState = {
    someStateData: 'wow state',
    error: undefined,
    errorId: 0,
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case SUCCESS:
            return {
                ...state,
                someStateData: action.data,
                error: undefined,
            }
        case ERROR:
            return {
                ...state,
                error: action.error,
                errorId: state.errorId + 1,
            }
        default:
            return state
    }
}

/* In the view component: */
class SomeComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            lastErrorId: 0,
        }
    }

    processHandlers() {
        if (this.props.error &&
            this.props.lastErrorId !== this.state.lastErrorId) {
            this.props.onFailure?.(this.props.error)
            this.setState({
                ...this.state,
                lastErrorId: this.props.lastErrorId,
            })
        }
    }

    componentDidMount() {
        this.processHandlers()
    }

    componentDidUpdate(prevProps, prevState) {
        this.processHandlers()
    }
}

const mapStateToProps = state => {
    return {
        error: state.error,
        lastErrorId: state.errorId,
    }
}

export default (connect(mapStateToProps)(SomeComponent))

This works great - is there another, better way? More idiomatic with Redux?

Upvotes: 0

Views: 184

Answers (1)

user998548
user998548

Reputation: 175

Add it to your logic or architecture...once the error occurs, save it, that could be another slice of your store that keeps track errors and other current issues. That is the point of state management, what is happening in your application right now...

Upvotes: 1

Related Questions