Search code examples
reactjsreduxreact-reduxredux-thunk

How to solve redux error Use custom middleware for async actions?


export const register = (user) => async (dispatch) => {
    try {
        const { res } = await api.register(user)
        dispatch({ type: REGISTER, payload: res });
    } catch (err) {
        console.log(err)
    }
}

export default (user = [], action) => {
    switch (action.type) {
        case REGISTER:
            return [...user, action.payload];
        default:
            return user;
    }
}

When I dispatch I get "Uncaught Error: Actions must be plain objects. Use custom middleware for async actions". Can anyone tell me what is wrong here?


Solution

  • From the description and the code snippet given, this is my conclusion on this issue.

    Redux library by default does not have support for async actions. The library achieves this by means of middlewares. The two most popular middlewares for async action are redux thunk and redux saga.

    I have not used redux saga much. But using redux thunk the problem can be solved as follows.

    1 Install redux thunk library.

    npm install redux-thunk

    2 Add redux thunk to the store

    Which would look something like this

    const store = createStore(
      rootReducer,
      applyMiddleware(thunk)
    );
    

    Here you can replace the root reducer with the name of your reducer that is used in the source.

    Now while you dispatch the function from the code the dispatch used in the async function will be added by the middleware.

    For more detailed explanation please refer the official redux thunk documentation.