Reputation: 53
I have this message when i try to dispatch a promise with redux and i d'ont see what i wrong
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
1) Here my createStore
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import RootReducer from '../reducers/root.reducer'
export default function configureStore(preloadedState) {
const store = createStore(
RootReducer,
preloadedState,
compose(
applyMiddleware(thunk), createLogger()
)
)
return store
}
2) In my component i dispatch my action like this
dispatch(myAction(myParam))
3) Here is myAction code
export function myAction(dispatch, myParam){
return fetchList(myParam)
.then(response => response.json())
.then(json => {
console.log(json)
})
.catch(err => {
if (err)
throw err
})
}
But if i call my action like this, it's work :
myAction(dispatch, myParam)
I think there is redux-thunk problem but why ...
Upvotes: 1
Views: 355
Reputation: 1593
Thunk allows an action creator to return a function instead of plain-object, so you use it like
export function myAction(myParam) {
return dispatch => {
console.log("IN ACTION");
fetchList(myParam)
.then(response => response.json())
.then(json => {
dispatch({
type: FETCH_LIST_SUCCESS,
list: json
});
})
.catch(err => {
if (err)
throw err;
});
};
}
You were returning a Promise object, that was the part of the problem.
Upvotes: 0
Reputation: 6078
With redux-thunk
you have to return a function from you action creator.
dispatch
would be passed to this function as a first parameter so you can call it anywhere inside the function to dispatch
different actions.
export function myAction(myParam) {
return dispatch => {
fetchList(myParam)
.then(response => response.json())
.then(json => {
dispatch({
type: FETCH_LIST_SUCCESS,
list: json
});
})
.catch(err => {
if (err)
throw err;
});
};
}
Read the docs more carefully.
Upvotes: 3