I like the idea of restricting UI State to the components.
Kyle Douglas DeTella
21

Great question.

In our use case, we have a small module that wraps requests for handling errors. So, we fire an action, that action makes a request, if it’s successful then update the store with the information, otherwise, the module will catch the failure and send a global error message. But that’s just our use case.

If you need to render specific error messages in your component or reset the store, there are quite a few ways you can do this. Here’s a couple examples:

— —

If your want to reset your info and get rid of the spinner, wrap the function in a try/catch. Something like this:

async submitForm() {
this.setState({isLoading: true});
try {
await this.props.submitUserInformation();
this.setState({isLoading: false});
} catch (error) {
this.props.resetUserInformation();
this.setState({isLoading: false});
}
}

Not really that fantastic though, right?

— —

Another direction: I would say that error messages are core data and reside in the Store. So, say your reducer has a field like errors, you could then check if the errors has data. If it does, set isLoading to false, and render the errors how you’d like. Maybe in a lifecycle method:

componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({isLoading: false});
}
}

componentWillReceiveProps typically doesn’t get called again after this.setState, so you don’t have to worry about this causing an infinite loop setting isLoading to false over and over, and thus causing render to be called over and over.

I like this direction more than the first example because we are able to make UI decisions off of core data we also use to render information for the user. I.E. “Email cannot be blank.”

— —

These are just a couple examples that came to the top of my head. If you don’t like how this is done and want to put UI data in the Store to solve these issues, by all means go for it. Whatever you and your team are most comfortable with is always the right direction. I don’t feel like I run into this situation too often and like keeping UI data in component state for the reasons I expressed in the article.

Thanks for reading and your thoughtful feedback.

Like what you read? Give Nick Cantelmi a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.