0

I have this reducer:

export const reducer = ( state, { type, payload } ) => {

      switch ( type ) {
        case 'SET_TOURS_IN_CART':
          return { ...state, toursInCart: payload };
        default:
          return state;
      }
    };

I want to add data to this reducer using SET_TOURS_IN_CART dispatch.

the payload contains this data: {id: '3', name: 'Best of Salzburg & Vienna in 8 Days Tour'}

I want the toursInCart to contain an array of objects, so that each time I add a new payload the array will add the new object to the existing data.

this is the provider:

import React, { useReducer, createContext } from 'react'
import { reducer } from './cart-context-reducer'

export const CartContext = createContext();

export default function CartContextProvider( props ) {
  const initialState = {
      toursInCart: []
    },
    [ data, dispatch ] = useReducer( reducer, initialState );

  return (
    <CartContext.Provider value={ { data, dispatch } }>
      { props.children }
    </CartContext.Provider>
  );
}

What am I doing wrong?

DavSev
  • 1,005
  • 4
  • 22
  • 47

1 Answers1

2

You return an object, not an array: return { ...state, toursInCart: payload }; (the toursInCart: payload part)

If you want to add the payload to the array toursInCart, try:

return {...state, toursInCart: [...state.toursInCart, payload]}

Or any variant

Maneal
  • 159
  • 4