Search code examples
reactjsreduxreact-redux

How do I store an array of objects that have arrays as value in Redux?


How do I store an array of objects that have arrays as value in Redux where the value is an array of items and key is a string like the name. I have to store something like:

[{
    name: 'ron',
    team: ['josh','brian'],
  },
{
   name: 'marie',
  team: ['ann', 'kevin']

    }
]

This is the code I have with just the name:

import {v4 as uuid} from 'uuid';
const initalState = [
  {
    id: uuid(),
    name: ''
  }
];


const trainerReducer = (state = initalState, action) => {
  const {type, payload} = action;

  switch (type) {
    case 'CREATE_TRAINER':
      console.log('payload', payload);
      return [...state, {id: uuid(), name: payload.name}];
   

    default:
      return state;
  }
};

export default trainerReducer;

Also, any documentation on how to add,update, delete this in redux would be appreciated.


Solution

  • You pass the team when you create a trainer.

    const trainerReducer = (state = initalState, action) => {
      const { type, payload } = action;
    
      switch (type) {
        case "CREATE_TRAINER":
          console.log("payload", payload);
          return [
            ...state,
            { id: uuid(), name: payload.name, team: payload.team ?? [] },
          ];
    
        case "ADD_TEAM":
          return state.map((trainer) =>
            trainer.id === payload.id ? { ...trainer, ...payload.team } : trainer
          );
    
        default:
          return state;
      }
    };