Tom Brooke
Tom Brooke

Reputation: 171

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.

Upvotes: 0

Views: 3760

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 10071

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;
  }
};

Upvotes: 2

Hacı Celal Aygar
Hacı Celal Aygar

Reputation: 518

try this please : create var or const array.

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

    }
];

then send this array to related method over action.

    import {v4 as uuid} from 'uuid';
    const initalState = [
      {
        id: uuid(),
        name: ''
      }
    ];
    
    
    const trainerReducer = (state = initalState, action) => {
      const {type, payload} = action;
      const arrayData = payload.arrayData;

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

Upvotes: 0

Related Questions