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

128
Vistas
how to use onChange on array of objects to add data in ReactJS

I am new in ReactJS world, I want to update my useState hook which contains array of objects, but it is now updating the data according to my requirement please help me in this.

ContactForm.js

function ContactForm() {
  const [user, setUser] = useState([]);

  const submitForm = () => {
    console.log(user);
  };

  return (
    <div>
      <input
        type="text"
        placeholder="name"
        onChange={(e) =>
          setUser((state) => [...state, { user_name: e.target.value }])
        }
        value={user.user_name}
      />
      <input
        type="text"
        placeholder="mobile"
        onChange={(e) =>
          setUser([...user, [...user, { mobile_number: e.target.value }]])
        }
        value={user.mobile_number}
      />
      <button onClick={submitForm}>Submit</button>
    </div>
  );
}

I am expecting something like

[{
    user_name:"abc",
    mobile_number:"123"
}]

should be store in my state, but I am getting some different output like below

0: {user_name: "a"}
1: {user_name: "as"}
2: {user_name: "asd"}
3: (4) [{…}, {…}, {…}, {…}]
4: (5) [{…}, {…}, {…}, Array(4), {…}]
5: (6) [{…}, {…}, {…}, Array(4), Array(5), {…}]

please help me out from this issue, and please tell me how objects in an array in useState worked Thanks in advance

(updated stack) I tried so many ways, that's why you may feel what I have written in code, especially in the

<input/>

tag

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

0

From your code, I'm guessing user is an object instead of an array. You are initializing the user as an array even though it should be an object (assuming from the use of user word here, i.e singular). I made the following changes:-

  1. Initialize user as an object.
  2. Use spread operator and add new property user_name or mobile_number as needed to update the state.

The below code should work

function ContactForm() {
  const [user, setUser] = useState({});

  const submitForm = () => {
    console.log(user);
  };

  return (
    <div>
      <input
        type="text"
        placeholder="name"
        onChange={(e) =>
          setUser({...user, user_name: e.target.value });
        }
        value={user.user_name}
      />
      <input
        type="text"
        placeholder="mobile"
        onChange={(e) =>
          setUser({...user, mobile_number: e.target.value })
        }
        value={user.mobile_number}
      />
      <button onClick={submitForm}>Submit</button>
    </div>
  );
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think you need to change your setState on the mobile input. Right now you're spreading the user as an array when you want it to be an object. When you do [...user] inside of the parent array, you create a new array instead of an object. Also, you need to make sure to edit the last element of the array. So:

setUser([...user, {...user[user.length], mobile_number: e.target.value }])

The parentheses get the last element of that array, not sure if that's what you're looking for. Pretty sure you need some way to identify which object in the array you want to use when editing the mobile number.

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