0

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.

4
  • What is wrong with the above code? What are you expecting? Commented Apr 22, 2022 at 5:54
  • How do I add an array to it? something like team = []. I don't know how to append this in redux. Commented Apr 22, 2022 at 6:17
  • Do you want to add value to the team? Commented Apr 22, 2022 at 6:19
  • Yes, to the teams array Commented Apr 22, 2022 at 12:40

2 Answers 2

2

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;
  }
};
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.