'React reducer - data.map is not a function or how to add values to case in a reducer

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maneal