简体   繁体   中英

Dispatch not sending the action to the reducer

I have a react redux app and I am having an issue with dispatching the action to the reducer. This is what I have in my actions.js

import GetDataFromAPIs from "../utils/api-data";
export const UPDATE_DATA = 'UPDATE_DATA';

export const updateData = async => {
    const newData = await GetDataFromAPIs();

    return{
        type: UPDATE_DATA, 
        payload: newData
    };
};

and this is how I am calling updateData from index.js:

const menuStore = createStore(MyReducer, composeWithDevTools(applyMiddleware(thunk)));
menuStore.dispatch(applyMiddleware(thunk)(updateData));

I can step through the actions.js but I don't see menuStore.dispatch sending the action to the reducer. What am I missing?

When using thunk middleware you need to pass the 'thunk' to the dispatch function.
First, the thunk need some modification. As the docs say here

A thunk is a function that wraps an expression to delay its evaluation

Therefore need to change the thunk as below.

export const updateData = async (dispatch)=> {
   const newData = await GetDataFromAPIs();

   dispatch({
      type: UPDATE_DATA, 
      payload: newData
    });
};

Now pass this thunk to the store.dispatch() function.

menuStore.dispatch(updateData);
  • If using thunk, then your action needs to return a function. The funtion will take dispatch as an argument which will be used to dispatch actions based on api response.
  • While calling dispatch you need not use middleware.
  • Also the action needs to be called in the dispatch menuStore.dispatch(updateData()) not just passing reference
export const updateData = inputData => async dispatch => {
    const newData = await GetDataFromAPIs();
    dispatch({
        type: UPDATE_DATA,
        payload: newData
    })
};

Usage

menuStore.dispatch(updateData())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM