texmex44 texmex44 - 3 months ago 9
React JSX Question

ReactJS + Redux + Reduc-thunk Can't dispatch promise

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 ...

Answer

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.