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

123
Vistas
I am trying to add elements to object using usestate in React?

I am trying to add a new fields in the useState hook

// prevstate  
let [currentdata, setcurrentdata] = useState({
   id:'',
   name:''
  })

I try to add new fields in the object like that

   setcurrentdata(currentdata => ({
            ...currentdata,
            q: quantity,
          }))

but it did not add new fields

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

0

The code snippet below may be one possible solution to achieve the desired objective.

NOTE: I personally dislike the idea of using useState in conjunction with such objects & prefer multiple simpler useState on each variable instead.

Code Snippet

const {useState} = React;

const MyFunction = () => {
  const [badStateObj, setBadStateObj] = useState({
    id: '',
    name: ''
  });
  const clickHandler = (propName) => setBadStateObj(prev => ({
    ...prev,
    [propName]: prev[propName] || ''
  }));
  const updateHandler = (propName, propVal) => setBadStateObj(prev => ({
    ...prev,
    [propName]: propVal
  }));
  
  return (
    <div>
      {Object.entries(badStateObj).map(([k,v]) => (
        <div>
          Key: {k} &emsp; Value: {v} &emsp; &emsp;
          <button
            onClick={() => updateHandler(k, prompt(
              `Enter new value for ${k}`
            ))}
          >
            Update {k}
          </button>
        </div>
      ))}
      <button
        onClick={() => clickHandler(prompt('Enter prop name'))}
      >
        Add new prop
      </button>
    </div>
  );
};

ReactDOM.render(
  <div>
    <h4>Demo showing the useState that I personally dislike</h4>
    <MyFunction />
  </div>,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

Explanation

  • The badStateObj is initialized with only id and name props
  • When user clicks the Add new prop button, a new prop may be added
  • Separate buttons exist to update the value of each individual prop
  • clickHandler adds the new prop entered by user with '' value.
  • updateHandler accepts propName and propVal as parameters and updates the appropriate props within the badStateObj.
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