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);
menuStore.dispatch(updateData())
not just passing referenceexport 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.