Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
Adding a key to Object with React Reducer?

hoping this is a easy question but I can't seem to figure it out.

I'm attempting to append a key to a object that is held in state. This key and value pair don't exist prior which I think is whats giving me the problem. Anyways here's what I have so far:

const Reducer = (state, action) => {
    
  switch (action.type) {
    case "SET_STUDENT_TAGS":
      const userID = action.payload.id;

      let studentIndex = state.originalStudentList.students.findIndex(obj => obj.id === action.payload.id);

      return {
      

        ...state,
            originalStudentList: {
                ...state.originalStudentList,
                students: {
                    [studentIndex]: {
                            tags: "test"
                    }
                }
            }
      };
    

Now the issue i'm running into is that I can run findIndex once but any attempt after just crashes my app saying its not a function. Simiarly the set state logic in the reducer there doesn't work either as it can't find "tags". So I guess i'm at a loss of how to do this. Here's how the data that is getting fed in looks:

{
  "students": [
    {
      
      "id": "1",
      
    },
    {
      "id": "2",
      
    }
  ]
}

here's the function from the input box:

const addTag = (event, student) => {
    if (event.key === "Enter") {
      if (event.target.value != "") {

        dispatch({
          type: "SET_STUDENT_TAGS",
          payload: {
            id: student.id,
            value: event.target.value,
          },
        });

        event.target.value = "";
      } else {
        return;
      }
    }
  };

what I'd like to achieve:

{
  "students": [
    {
      
      "id": "1",
      "tags": ["cat", "dog"]
    },
    {
      "id": "2",
      "tags": ["cat", "parrot"]
    }
  ]
}

So i'm at a lost as to how to do this correctly. Appreciate any help!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're on the right track, but that syntax replaces the array with a regular object, which is why findIndex fails after the first time. For more info, see this answer.

And then to add a property to the specific student, you just replace it with an object spreading the original and adding the tags:

const Reducer = (state, action) => {
    
  switch (action.type) {
    case "SET_STUDENT_TAGS":
      const userID = action.payload.id;

      let studentIndex = state.originalStudentList.students.findIndex(obj => obj.id === action.payload.id);
      let student = state.originalStudentList.students[studentIndex];

      return {
      

        ...state,
            originalStudentList: {
                ...state.originalStudentList,
                students: [
                    state.originalStudentList.students.slice(0, studentIndex),
                    {
                        ...student,
                      tags: action.payload.tags
                    },
                    state.originalStudentList.students.slice(studentIndex+1)
                ]
            }
      };
    
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda