javascriptreactjsobjectredux

React redux update a list of objects nested objects


Im trying to create this structure in my redux store, havea feature to add a user,struggling to update the structure to add cars to a user , im passing object think i need to do a map on state but its not working correctly

// main object im trying to build

const inventory = [
  {
    id: 1,
    name: "Paul",
    cars: [
      {
        model: "Ford",
        year: "1995",
      },
      {
        model: "BMW",
        year: "2010",
      },
    ],
  },
  {
    id: 2,
    name: "Simon",
    cars: [
      {
        model: "Vauxhall",
        year: "2022",
      },
      {
        model: "VW",
        year: "2001",
      },
    ],
  },
];


 // object that gets sent to the store

 const addUser = (content) => (
    
    {
        type: 'ADD_USER',
        payload: {
            id : 1,
            name : 'George',
            cars : []
        
        }
    }
)

const carOptions = (content) => (
    {
        type : "ADD_CAR",
        payload : {
            model: "Porsche", 
            year: "2009" 
        }
    }
)

This is my reducer main issue appears in ADD_CAR  

const carReducer = ( state = [], action) => {
    
    switch(action.type) {
        case 'ADD_USER':
            return [...state,action.payload]
       case 'ADD_CAR':
        return state.map((item) =>
        item.id === 1
          ? { ...item, cars: item.cars.concat([ ...state, action.payload ]) }
          : item
      );
        default:
            return state;
            
    }
}


Solution

  • I think you should specify to which user you want to add car to. Your ADD_CAR payload can look like this:

    { userId, carOptions: { model: "Porsche", year: "2009" } }
    

    In reducer you will first find the user by userId and then add car to this user, smth like this:

    return state.map((user) =>
        user.id === action.payload.userId
          ? { ...user, cars: [...user.cars, action.payload.carOptions] }
          : user
      );