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

169
Vistas
How to update/add new data to react functional component object?

I am trying to create a function that updates an object in react functional component. What i was trying to do is:

const [content, setContent] = useState({});
const applyContent = (num: number, key: string, val: string) => {
  if (content[num] === undefined) {
    content[num] = {};
  }
  content[num][key] = val;
  setNewContent(newInput);
};

But I keep getting an error stating that content doesnt have a num attribute, In vanilla JS it would work, what am i missing to make it work with react functional component?

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

0

The setter for your component state has been incorrectly spelled. Have a look at the code below.

import React, { useState } from 'react';
import './style.css';

export default function App() {
  const [content, setContent] = useState({});

  const applyContent = (num, key, val) => {
    //gets the appropriate inputs
    let updatedContent = content;
    let value = {};
    value[key] = val;

    updatedContent[num] = value; //this inserts a new object if not present ot updates the existing one.

    setContent({ ...updatedContent });
  };

  return (
    <div>
      <h1>Click buttons to change content</h1>
      <p>{JSON.stringify(content)}</p>
      <button onClick={(e) => applyContent(0, 'a', 'b')}>Add</button>
      <button onClick={(e) => applyContent(1, 'c', 'd')}>Add</button>
      <button onClick={(e) => applyContent(0, 'e', 'f')}>Add</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

content is a read only value. You must not directly mutate this. Use it only to show data or to copy this data to another helper value.

setContent is a function that sets content.

There are two ways to set data

setContent(value) <-- set directly 
setContent(prevState => {
    return {
        ...prevState,
        ...value
    }
})

In second example, you will use the previous value, copy it, and then override it with new value. This is useful if you are only updating a part of an object or array.

If you you are working with a deeply nested object, shallow copy might not be enough and you might need to deepcopy your content value first. If not, then use the prevState example to only update the part of that content

const [content, setContent] = useState({});

const applyContent = (num:number,key:string,val:string) => {
const newContent = {...content} // Shallow copy content
    if (content[num] === undefined) {
      //content[num] = {}; <-- you cant directly change content. content is a readOnly value
    newContent[num] = {}
    
    }
    newContent[num][key] = val;
    //setNewContent(newInput);
      setContent(newContent) // <-- use "setContent" to change "content" value
  }

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