Reputation: 205
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);
}
}
PS: submit form works after page is refreshed
Adding the requested code as per in the comments:
createPost controller:
export const createPost = async (req, res) => {
const { title, message, selectedFile, creator, tags } = req.body;
const newPostMessage = new PostMessage({
title,
message,
selectedFile,
creator,
tags,
});
try {
await newPostMessage.save();
res.status(201).json(newPostMessage);
} catch (error) {
res.status(409).json({ message: error.message });
}
};
reducer index.js
import posts from "./posts";
export default combineReducers({
posts,
})
post reducers:
switch (action.type) {
case 'UPDATE':
return posts.map((post)=>post._id === action.payload._id ? action.payload : post)
case "FETCH_ALL":
return action.payload;
case "CREATE":
return [...posts, action.payload];
default:
return posts;
}
};
Upvotes: 0
Views: 83
Reputation: 127
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.
Upvotes: 0