Reputation: 364
I am currently building a React app which does a lot of server communication. If a server error occurs, I want to display the error to the user in a general way, e.g. an overlay with the error message.
In my reducers, I return something like this:
{
type: "LIST_POSTS_ERROR",
loading: false,
error: {
msg: "An error occurred"
}
}
Obviously, my container components are redux aware. In the render()
function, I could check, if the current state has a property error
and if so, I would render the error message. Oddly, in every container component, I would have to check the current state and might have duplicated code in every container component.
What am I looking for is a more general approach. Something that knows about all the states and displays the error message automatically if the current state contains an error. Think of it like an interceptor for errors. Of course, this component would not belong to a route, so I am wondering if this is even possible?
How do you do error handling in your React app? I would love to know your approach!
Upvotes: 1
Views: 1348
Reputation: 8124
I am trying something similar for my App. So fire a dispatch on catch or >=400 response to set a string(your api response) in state and connect this value to your component.
Next, after maybe 4-5 seconds fire a dispatch to clear that value, so your message would go away. This you can implement in your login screens or your post API calls.
Hope it helps !!!
Upvotes: 0
Reputation: 19133
In my app, I've a action called handleError
which will trigger a toast
component in my app.
You can dispatch
this action at the time of error. Like, you can dispatch
it in the .catch()
of the Promise
.
Upvotes: 1