Reputation: 1494
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?
Upvotes: 4
Views: 1328
Reputation: 13682
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())
Upvotes: 2
Reputation: 632
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);
Upvotes: 2