Home > Net >  how to update react state to add an element in array, which is nested array?
how to update react state to add an element in array, which is nested array?

Time:06-20

  const [persons, setPersons] = useState([
    { name: "", age: "", phoneNumbers: [''] },
  ]);

if we need to add a new person, we can use following syntax...

  const addPersonFields = () => {
    let person = {
      name: "",
      age: "",
      phoneNumbers: [""],
    };
    setPersons([...persons, person]);
  };

But how to add new phone number for the person at index "i" and make that reflect in react state?

CodePudding user response:

Assuming you know the index of the person you want to update, you could do something like:

const addPersonPhoneNumber = (index, newNumber) => {
    const newState = [persons];
    newState[index].phoneNumbers.push(newNumber);
    setPersons([...newState]);
}

CodePudding user response:

Another way, we can add the phone number of a person at index i by using setPersons directly

    const addPhoneNumber = (index, phoneNumber) => {
        setPersons((prevPersons) => {
            prevPersons[index].phoneNumbers.push(phoneNumber);
            return [...prevPersons];
        });
    }

CodePudding user response:

You would have to find the person at first. The solution below suggests you already have the person object you want to add a phone number to.

  const addPhoneNumber = (newNumber) => {
    let index = persons.map((e) => e).indexOf(person);
    persons[index].phoneNumbers.push(newNumber);
    setPersons([...persons]);
  };
  • Related