Akhi21
Akhi21

Reputation: 229

How to store object in state from Input Field?

I am trying to fetch both the input value save it in the state but it does take only last the Input field value.

When in useEffect console.log(state) the object only stores and displays the last values lname I am not able to get why its not storing fname.

I want to store both the the value as object from input field.

const handleChange = idx => e => {
    const { name, value } = e.target;
    const rows = [...state.rows];
    rows[idx] = {
      ...rows[idx]
      [name]: value
    };
    setState({
      rows
    });
  };

Upvotes: 1

Views: 306

Answers (2)

Dennis Vash
Dennis Vash

Reputation: 53874

The problem is with handleChange, you overriding the changed state:

const handleChange = (idx) => (e) => {
  const { name, value } = e.target;
  const rows = [...state.rows];
  // Add ...rows[idx] to keep the values updated from other names
  rows[idx] = { ...rows[idx], [name]: value };
  setState({ rows });
};

Edit gallant-elgamal-5bq21

Upvotes: 2

Hagai Harari
Hagai Harari

Reputation: 2877

you need to use ...rows[idx] in your handleChange

const handleChange = idx => e => {
    const { name, value } = e.target;
    const rows = [...state.rows];
    rows[idx] = { ...rows[idx], [name]: value }; //here
    setState({
      rows
    });
  };

Upvotes: 2

Related Questions