Search code examples
reactjsreact-reduxredux-thunk

What is the point of the dispatch parameter in a function?


New to react and redux thunk, just wondering what is the reason of having the dispatch parameter

return (dispatch: Dispatch, getState: () => ReduxState):

In the isTest() method??? My understanding is dispatch is only used to dispatch an action to update a state, but my method below doesn't need to and is not dispatching an action.

My grid is not updating properly if I remove the dispatch parameter from the method.

Container file:
getTest: ():any => {
      return {
        disabledFields: dispatch(isTest("Abc"))
          ? [grid.title]
          : [grid.name]
      };
    }

Action file:
export const isTest = (
  str: String
) => {
  return (
    dispatch: Dispatch<ReduxState>,
    getState: () => ReduxState
  ): boolean => {
    return getState().id === 5;
  };
};

Solution

  • From the documentation...

    Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.

    So the point of the dispatch parameters is so that you can run a function or another action before you return an object to your reducer. An example of this would be if you hit an API with an action you can then dispatch another function that may parse the response and then dispatch an action that would return the parsed response to your reducers. Or it might not dispatch the final action because API response was bad.