handsome
handsome

Reputation: 2412

how to update array element with useState

hello I have a family object with children and I want to update the children´s name

const [family, setFamily] = useState({lastName: "Doe", children:[{name: "Mary"]}, {name: "Jane"]})

then i do

family.children.map((c, i) => <input name="name" key={i} onChange={(e) => updateChildren(e)} />)

const updateChildren = (event) => {
    let value = event.target.value;

    setFamily((prevState) => {
        return {
            ...prevState,
            children: //I think here´s the problem not sure how to target the children,
        };
    });
};

thank you!

Upvotes: 0

Views: 82

Answers (2)

German
German

Reputation: 1166

It should gonna be like this

 const updateChildren = ({ target }) => {
    setFamily(({ lastName, children }) => {
      children = [...children, { name: target.value }];
      return { lastName, children }; // updates the children
    });
  };

check codesandbox for demo.

https://codesandbox.io/s/nervous-snyder-s4cyn?file=/src/App.js

Upvotes: 0

Predrag Davidovic
Predrag Davidovic

Reputation: 1566

Add to updateChildren function index property to know which one you want to update:

family.children.map((c, i) => <input name="name" key={i} onChange={(e,i) =>.   
updateChildren(e, i)} />)

const updateChildren = (event, index) => {

let myFamily = Object.assign({}, family);
const currentChild = myFamily[children[index]];
currentChild.name = event.target.value;

setFamily((prevState) => ({
        ...prevState,
        ...myFamily: 
    });
});

};

Upvotes: 1

Related Questions