3

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

Piyush Jiwane
  • 179
  • 3
  • 13
  • 3
    `[...user, [...user,` you are adding your previous values as an array instead of just spreading the previous values into the array itself, you should have it like you have the previous one – Patrick Evans Aug 22 '21 at 22:08
  • hi @PatrickEvans , I tried with a single [...user also, but still I was getting same issue – Piyush Jiwane Aug 22 '21 at 22:12
  • Though, it's unclear why you're even using an array here. – Emile Bergeron Aug 22 '21 at 22:15
  • hi @EmileBergeron , i want to store data in objects of array format so i can apply .map() on it – Piyush Jiwane Aug 22 '21 at 22:17
  • 1
    Are you meaning to just have a single user or multiple users? If single your state should be an object instead of an array. If you want multiple users you need to make the single user object first and use some other method to add it to your array – Patrick Evans Aug 22 '21 at 22:21

2 Answers2

6

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>
  );
}
Utkarsh Dixit
  • 4,267
  • 3
  • 15
  • 38
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.