I am having a consistent problem when passing additional parameters to a thunk in redux using react. I am using applyMiddleware(thunkMiddleware)
in the redux store.
I have a version of the code that works fine with axios.get for retrieving all records in the DB. This works great:
export async function fetchCollection(dispatch, getState) {
return await axios
.get(apiAddress + "/collections")
.then(response => {
dispatch({
type: 'collectionLoaded',
payload: response.data,
})
})
}
However when I try to modify this function so I can eventually pass in a variable and then return a thunk, I get nothing. The below is essentially copy and paste from the redux website, but does not work. I am running the function on page load to populate the state. This does not ping my backend server and the dispatch
does not seem to run (the state is never updated in redux dev tools).
export function fetchCollection() {
console.log("api: ", apiAddress + "/collections")
return async function fetchCollectionThunk(dispatch, getState) {
await axios
.get(apiAddress + "/collections")
.then(response => {
dispatch({
type: 'collectionLoaded',
payload: response.data,
})
})
}
}
My plan with the second function is to pass in the user ID so that I can request just the relevant data back from the API. The console.log
I threw in does run, but nothing else. If I put a console.log
in the .then
function, it does not run.
Left out catch/error handling for simplicity, however the first code block runs without.
Not sure if I'm missing something or maybe I'm crazy. I had this issue once before with axios & redux and wasn't able to figure out the cause. Any help is greatly appreciated!
EDIT:
In response to a few questions:
The action is being dispatched on the initial load. For development, I am using it to populate the state upfront. Eventually, there will be some more layers of complexity involved, but need to get this working first. Here is where the action is being dispatched:
Index.js
store.dispatch(fetchCollection)
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
then
you don't needasync/await
. Also, how are you dispatching that thunk action? – apokryfosfetchCollection
function, can you please share the component code along with how it's connected to redux and all – Gulam Hussaindispatch
object, i.e.const myAsyncAction = (arg1, arg2,...) => dispatch => { .... }
. – Drew Reese