I am stuck on this problem trying to dispatch a state update to the store.
This is my productSlice.js
import { createSlice } from "@reduxjs/toolkit"
const initialState = [];
export const productSlice = createSlice({
name: 'product',
initialState,
reducers: {
addpica: (state, action) => {
state.push(action.payload);
}
}
})
export const { addpica } = productSlice.actions;
export default productSlice.reducer;
I have added a dispatch in singleproduct.jsx
function abfunction(product) {
dispatch(addpica(product))
}
...
<button onClick={abfunction}>ADD TO CART</button>
The problem is I have an array with name "product" and I want to send that array as payload with dispatch. I am stuck in this problem for 2 days. I want to send and receive that "product" array.
When sending that dispatch, it’s saying: "state.push
is not a function".
2
Answers
It seems like the issue you’re facing is due to the incorrect initialization of the initialState. The initialState should be an object, not an array, because Redux slices typically manage state as an object to handle multiple properties.
Try this, I think this helps you
Issue
When you pass an
onClick
handler as suchonClick={abfunction}
then theonClick
event object is what is passed to the callback. The problem is that theonClick
event object, namedproduct
inabfunction
is passed as the action payload, and since there the event object hasn’t anypayload
property it will be undefined.Solution Suggestion
Update the UI code to pass the appropriate
addpica
payload value.Examples:
Use an anonymous callback function to pass a product object refernece:
Don’t consume the click event object and pass a product object reference to action: