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;
}
};