Home > OS >  Redux error when submitting a form: Actions must be plain objects. Instead, the actual type was: �
Redux error when submitting a form: Actions must be plain objects. Instead, the actual type was: �

Time:11-21

I'm trying to submit a form using Redux, however, getting an error message in the console: Uncaught Error: Actions must be plain objects. Instead, the actual type was: 'Promise'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions.

I am already using thunk as my middleware when creating the store. Here's the code:

const store = createStore(reducers, compose(applyMiddleware(thunk)))

create post action:

export const createPosts = (post) => async (dispatch)=>{
  try {
    const {data} = await api.createPost(post)

    dispatch({type:'CREATE', payload:data})
  } catch (error) {
        console.log(error.message);

  }
}

CodePudding user response:

return the api call and do the dispatch after

export const createPosts = (post) => (dispatch)=>{
  try {
   return api.createPost(post).then(data => {
     dispatch({type:'CREATE', payload:data}) 
   })

  } catch (error) {
        console.log(error.message);

  }
}

CodePudding user response:

As the error suggests, you cannot have an async function as an action, even with thunk.

Thunk allows you to return an async response, not call an async action. So the proper way to do this would be:

export const createPost = post => (dispatch, getState) => {
  api.createPost(post)
    .then(data => dispatch({ type: "CREATE", payload: data}))
    .catch(e => console.log(e))
}

Assuming that the declaration of createPost is an async function or it returns a call to an async function.

  • Related