In React with Redux, when there are some user operations, e.g., in facebook, user adds some comments, I will call dispatch()
to send the add action to redux store, but when should I call back end API to save these data to database? do I need to do it together with dispatch()
?
thanks
One solution would be to transfer your API logic into a thunk using a middleware package such redux-thunk (or similar).
Using thunks allows you to treat special kinds of
actions
as functions which means you can extend a plain action with specific action-related logic. The example you give of needing to serialize your state is an excellent use-case for redux-thunk.You should note that, unlike reducers, thunks explicitly support fetching state and dispatching subsequent actions via the
getState
anddispatch
functions.Below is an ES6 example of how such a multi-purpose thunk might look.
To demo the
getState()
method the new item will only be saved via the api only if the redux stateshouldSave
value is truthy.I would also use the
async/await
syntax to make sure the the api call succeeds before dispatching the local redux action.Thunk Example - adding a new item