1
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?

2
  • How are you creating the store? Commented Mar 22, 2021 at 8:41
  • I fixed the issue just import error Commented Mar 22, 2021 at 13:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

import user from './user' export default combineReducers({ user })
const store = createStore(reducers, compose(applyMiddleware(thunk)))
I have used thunk. But still getting the error
Is the issue resolved @ShahariarRahmanSajib?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.