Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to coordinate server error messages between Flux and React?

I've been learning React and Flux over the past few months, and one thing I've not yet dealt with is displaying error messages to users. Specifically, error messages that occur as a result of an ajax http request within a flux action creator method.

A simple example is user sign in - if the sign in ajax request fails due to a bad password, the server responds with the failure. At that moment, within my flux action creator method, my only option is to dispatch an action containing the error information, right?

I can dispatch the error information and keep that error in a store. I'm not sure what the best way to tie certain errors to certain components is, though. Lets say my react component tree is rendering multiple error-aware components, but an error occurs during server-side user auth attempt and needs to be displayed on that sign in form.

Is there good pattern or convention for storing errors and knowing which component they're for? Is there a programmatic way of determining this, instead of passing in some identifier to every action creator function that identifies the component the action creator is called it, etc?

like image 248
Ryan Avatar asked Aug 05 '15 03:08

Ryan


People also ask

Can you use try catch in React?

The Classic 'Try and Catch' Method in React To be more realistic and close to the React world as possible, let's see an example of how you'd use this in your app: const fetchData = async () => { try { return await fetch("https://some-url-that-might-fail.com"); } catch (error) { console.

How to handle error in React application?

Error handling with Error Boundaries — For class components. Error boundaries are the most straightforward and effective way to handle errors that occur within your React components. You can create an error boundary component by including the life cycle method componentDidCatch(error, info) if you use class component.

What do you call a React component that catch JavaScript errors anywhere in the child component tree?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.


1 Answers

Your idea of keeping error info in a store is fine (probably an ErrorStore). But the store doesn't need to know the component interested in a particular error. Instead, the ErrorStore needs to emit a CHANGE event. When emitting that event, you can add an additional argument, namely the error type (which the store presumably gets from the action creator).

Now, any component can listen to the ErrorStore and check the error type (which it will get as an argument). Components can then know what kind of error was generated and decide whether they are interested in that or not.

like image 72
Hal Helms Avatar answered Sep 30 '22 19:09

Hal Helms