-1

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. And 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,
                data: 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

Thank You...

1 Answer 1

1

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:

  • a function body
  • a label named type
  • and a reference to data

instead 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.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.