Jie
Jie

Reputation: 317

async function error in redux action with redux-thunk installed

I have the redux-thunk installed and I think I configured it as documentation. But still get the error: Actions must be plain objects. Use custom middleware for async actions.

action:

import fetch from 'isomorphic-fetch'

export { get_all_posts } from '../utils/http_functions'

export function fetchAllPosts(){
    return{
        type: 'FETCH_ALL_POSTS'
    }
}

export function receivedAllPosts(posts){
    return{
        type: 'RECEIVED_ALL_POSTS', 
        posts: posts
    }
}

export function getAllPosts(){
    return (dispatch) => {
        dispatch(fetchAllPosts())
        return fetch('/api/posts')
            .then(response => response.json())
            .then(json => {
                dispatch(receivedAllPosts(json))
            })
            .catch(error => {

            })
    }
}

store:

import { createStore, applyMiddleware } from 'redux'
import rootReducer from '../reducers/index'
import thunk from 'redux-thunk'

const debugware = [];
if (process.env.NODE_ENV !== 'production') {
    const createLogger = require('redux-logger');
    debugware.push(createLogger({
        collapsed: true
    }));
}

export default function configureStore(initialState = {}){
    const store = createStore(
        rootReducer, 
        initialState, 
        window.devToolsExtension && window.devToolsExtension(), 
        applyMiddleware(thunk, ...debugware)
    )

    if (module.hot){
        module.hot.accept('../reducers', () => {
            const nextRootReducer = require('../reducers/index').default
            store.replaceReducer(nextRootReducer)
        })
    }

    return store
}

reducer:

export function posts(state = {}, action){
    switch(action.type){
        case 'RECEIVED_ALL_POSTS':
            return Object.assign({}, state, {
                'posts': action.posts
            })

        default:
            return state
    }
}

in server.js, I am using proxy server to route the '/api/' request to my backend service:

app.all(/^\/api\/(.*)/, function api(req, res){
    proxy.web(req, res, {
        target: 'http://localhost:5000'
    })
})

Upvotes: 1

Views: 287

Answers (1)

Joy
Joy

Reputation: 9550

Because in your code:

const store = createStore(
    rootReducer, 
    initialState, 
    window.devToolsExtension && window.devToolsExtension(), 
    applyMiddleware(thunk, ...debugware)
)

The function applyMiddleware(thunk, ...debugware) is actually not applied. In the document of createStore: http://redux.js.org/docs/api/createStore.html

createStore(reducer, [preloadedState], [enhancer])

Your applyMiddleware should be input as the third argument.

Note: Your solution in the comment is another approach to apply the middleware.

Upvotes: 1

Related Questions