Search code examples
javascriptreactjsreact-reduxredux-toolkit

I am facing problem in sending array and fetching array through payload in redux toolkit


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


Solution

  • Issue

    When you pass an onClick handler as such onClick={abfunction} then the onClick event object is what is passed to the callback. The problem is that the onClick event object, named product in abfunction is passed as the action payload, and since there the event object hasn't any payload property it will be undefined.

    function abfunction(product) { // onClick event object
      dispatch(addpica(product))   // click event object pass to action
    }
    
    ...
    
    <button onClick={abfunction}>ADD TO CART</button>
    
    addpica: (state, action) => {
      state.push(action.payload); // click event has no payload property!!
    }
    

    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:

      function abfunction(product) {
        dispatch(addpica(product));
      }
      
      ...
      
      <button onClick={() => abfunction(product)}>ADD TO CART</button>
      
    • Don't consume the click event object and pass a product object reference to action:

      function abfunction() {
        dispatch(addpica(product));
      }
      
      ...
      
      <button onClick={abfunction}>ADD TO CART</button>