Moon
Moon

Reputation: 149

Redux action dispatch

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

Answers (1)

Prathap Reddy
Prathap Reddy

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 the store is single source of truth, the dispatch you are using is actually comes from store (store.dispatch).

If you call a function normally then it won't be aware by the store. That action won't pass through the middlewares (thunk/saga) that store is aware of and won't do the store update via reducers.

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

Related Questions