Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application vs. local state in redux

In many Redux examples, SOME_ASYNC_ACTION_ERROR or SOME_ASYNC_PENDING are actions that are dispatched to manipulate the global state. I can't think of a scenario where it would make sense for a component to be initially rendered with a global error / loading / pending state. When a component is destroyed and remounted, that async error would need to be "cleared", making it seem like manipulating the component's local state is a better choice.

Considering this, what's the best practice for dealing with loading / error / pending states in Redux:

  • Should a component default to an initial state locally but still subscribe to the global application state for loading / errors?
  • OR Should the application state for error / loading be reset after leaving a component?
  • OR Should these transitory states just be managed locally?
like image 725
Whoa Avatar asked Jan 27 '16 17:01

Whoa


1 Answers

From my understanding, the best practice in Redux is to always store application in the global store, but then have your individual components subscribe to only the relevant information from that store, using connect(mapStateToProps)(Component). So rather than having a global application loading property, your individual components would subscribe to the relevant flag, such as users.loading

See http://rackt.org/redux/docs/basics/UsageWithReact.html for more

EDIT: To further answer your question, each Action should clean up after itself, by dispatching another action. So you might have REQUEST_USER which adds a loading flag and resets an error state, followed by RECEIVE_USER, which removes the loading flag, or FAILED_TO_RECIEVE_USER, which removes the loading flag, buts adds an error state. This pattern is described pretty thoroughly here: https://github.com/agraboso/redux-api-middleware#redux-standard-api-calling-actions

like image 155
Aaron Avatar answered Nov 13 '22 13:11

Aaron