This is a common error shown when we mess up the action. But in this case, I am trying to dispatch an action with data in its parameter. Action is receiving the data but the reducer is not able to fetch that. I am using the useDispatch hook in this case. Are there any other ways to send data that I might not know, or should I use the connect() function cause useDispatch has some bugs! I am using node v16.15.1 and npm v8.12.2
I have shortened the code for a better understanding
Component
const data = {...}
dispatch(sendData(data)); // the dispatch function will call onClick of a button
Action
export const sendData(data) => {
type:ADD_DATA, //ADD_DATA is a constant imported for using as type
data
}
Reducer
const dataReducer = (state = [], action) => {
switch(action.type) {
case ADD_DATA:
return {
...state,
action.data
}
default:
return state;
}
}
combined it with combineReducers() function
store created using configureStore()
the app is wrapped on <Provider store={store}></Provider>
Another Component
const data = useSelector(state=> state.dataReducer);
console.log(data);
In console.log empty state is displayed when rendered the component. But won't update onClick and gives the uncaught error Actions must be plain objects
Stuck with the problem for a long time, and need some helping hand
Thank You...
Your sendData action creator is wrong:
export const sendData(data) => {
type:ADD_DATA, //ADD_DATA is a constant imported for using as type
data
}
This isn't actually returning anything. Because you have a => and a {, it's a function body, not an object. So, this is actually:
typedatainstead of an object like {type, data}
You could put parentheses around the curly braces to make it an implicitly returned object instead: => ({type, data}).
However, the better answer here is to switch to using our official Redux Toolkit package to write your Redux logic. Redux Toolkit is the the right way to use Redux today, and RTK's createSlice API will automatically generate action creators for you.