Let's say I have this code below:
switch (action.type) {
case "GET_LIST":
// update state
break;
case "GET_LIST_SUCCESS":
// update state
break;
case "GET_LIST_ERROR":
// update state
break;
default:
return state;
}
Before this, I've already set-up some action creators (with a thunk middleware for async requests). So the flow would be either GET_LIST > GET_LIST_SUCCESS
OR GET_LIST > GET_LIST_ERROR
.
Now in my React component, I want to do something depending on which action type was dispatched in the end (either success or error).
Is it a good practice to use the action type themselves or should I just use the store state for my condition? In this example, my store would have an error
property, which I can use to detect whether there's an error or not.
So it's either (using action type):
if (actiontype === "GET_LIST_SUCCESS") {
// do something
}
OR (using the store state)
if (this.props.list.length > 0) {
// do something
}
Which is a better practice and why?
Just my opinion, but one advantage of using Redux over storing data in component state is that you separate the concern of how to handle data updating from view layer (React) to Redux; React component should only know if the data has been changed, not how it is changed. This de-couples the data layer and view layer in frontend, and helpful when you need to execute a chain of actions to update state (e.g. fetching from API).
If you want to expose current Redux action type to React component, you have to log the action somewhere in your app, since I don't think Redux exposes current action to view layer. In addition, this also reveal too much info of how Redux handles data flow.
Common practice is saving fetching state in boolean, and error log, e.g.
isFetching
andfetchListError
, update those values along the fetching process, and pass those value to view layer for display.