Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda