Reputation: 149
In my redux action, I have one action will be called by another two actions, code is below:
export const addParticipantFromPopupRequest = (participant, project_id, currentStep) => async (dispatch) => {
const result = await addParticipant(participant)
dispatch({ type: PARTICIPANT_ADD, payload: result })
dispatch(updateProjectStep(project_id, currentStep))
}
export const handleFinalStep = (projectId, currentStep) => async (dispatch) => {
dispatch(updateProjectStep(projectId, currentStep))
}
const updateProjectStep = (projectId, currentStep) => async (dispatch, getState) => {
dispatch({ type: MODAL_STATUS_CHANGE, payload: { projectId, currentStep } })
dispatch({ type: PROJECT_PROCESS_LIST_UPDATE, payload: { project_id: projectId, currentStep } })
const { projectsProcessListsReducer } = getState()
localStorage.setItem("projectsProcessLists", JSON.stringify(projectsProcessListsReducer))
}
If I dont' use dispatch when call updateProjectStep, the addParticipantFromPopupRequest and handleFinalStep cannot run correct.
My question is can I call dispatch actions in this way and is it correct? Why I need the "dispatch" when I call updateProjectStep in another actions rather than call function name directly?
Upvotes: 1
Views: 257
Reputation: 1749
My question is can I call dispatch actions in this way and is it correct?
Yes. You should always call with the dispatch
.
Why I need the "dispatch" when I call updateProjectStep in another actions rather than call function name directly?
If you call updateProjectStep
directly without dispatch
, it will become a normal js function call and your store
won't be aware of it. Dispatch is the only way to trigger a state change in store
.
In
redux
thestore
is single source of truth, thedispatch
you are using is actually comes fromstore
(store.dispatch
).
If you call a function normally then it won't be aware by the
store
. That action won't pass through themiddlewares
(thunk/saga) thatstore
is aware of and won't do thestore
update viareducers
.
If
store
is not updated, your components won't receive any updates. Eventually your UI won't re-render.
You can find more about dispatch here.
Upvotes: 1