For example, a user needs to create a resource. Clicking the "create" button will call an action to send data to the API. If the resource is successfully created, dispatch a "Success" action. Otherwise, dispatch a "Failure" action.
How can a component respond to a success or a failure in Flux? Should I be setting a success/failure flag in the store that is read by the component? Should I be emitting separate events from the store with their own listeners on the component for success/failure?
More specifically, say I want to route to the created resource on "Success". If I want to open a specific dialog on "Failure"? How would I do that from the component?
I'm just trying to figure out best practices.
Thanks!
How exactly you do this depends on which Flux implementation you use. However, the way to handle it is more or less the same:
In general, in any Flux implementation you'll be able to connect your store to component props, such that whenever your store is updated, any components which are connected to the store will get the updated store values. So if you want to handle any kind of change to the store, what you want to do is connect your component to the store and use the component update methods in order to have your component detect changes to the store.
For instance, if you want to respond to a success/failure in an API call, what you would do would have the following in your store:
{
...
runningApiRequest: //boolean value
apiRequestResult: //whatever your API returns
...
}
You would then use whatever Flux library you are using to make your component which call the actual API request action receive apiRequestSucceeded
and apiRequestResult
as props. In your component, you could then implement the following:
componentDidUpdate(prevProps, prevState) {
if (!prevProps.runningApiRequest && this.props.runningApiRequest) {
// request started
this.showLoadingIndicator()
}
if (prevProps.runningApiRequest && !this.props.runningApiRequest) {
// request finished, handle success or failure
this.handleRequestResult(this.props.apiRequestResult)
}
}
Of course, this is not the only way to do this, but handling changes to a Flux store will always come down to the same fundamental building blocks: hooking props to the store and handling changes to props in lifecycle methods.