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

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

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

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 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