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

278
Vistas
React: How to save previous states in a object with dynamic properties?

I'm trying to store some information every time that a change occurs on the value of a input element.

const [inputs, setInputs] = useState({})

const addInput = (name, value, type) => {
    setInputs(() => {
      inputs[name] = {
        "value": value,
        "type": type
      }
      return inputs
    })
  }

...

  const handleInput = (event) => {
    addInput(props.name, event.target.value, event.target.type)
    ...
  }

I've got an empty object callled inputs, and if the user types inside an input like this:

<input name="username" value={onChange} type="text">

the inputs object should have now a property called username:

{
  username: {
    type: "text",
    value: : "text-from-the-user",
  }
}

but my problem is: When I add two inputs or more inside this inputs object, a override occurs in all the properties that isn't having a change.

For example: If I have two objects inside the inputs...:

{
  username: {
    type: "text",
    value: : "John",
  },
  email: {
    type: "email",
    value: : undefined,
  },
}

...and I add some text in the email input, the inputs object loses the data from the username object:

{
  username: {
    type: undefined,
    value: : undefined,
  },
  email: {
    type: "email",
    value: : "Jhon123@yahoo.com",
  },
}

So I'm trying to implement the ...prev inside this setInput, but I'm having trouble with this, because inside this setInput I say that I want to create new objects if they don't exist:

...
      inputs[name] = {
        "value": value,
        "type": type
      }
...
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should do it like this:

setInputs((ps) => ({
    ...ps,
    [name]: {
        "value": value,
        "type": type
    }
}))

When you set state:

  • you must update state in immutable way
  • and useState overwrites new value over the old one (doesn't merge like it was in class components)
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