Home > Net >  Why is my page not updating with the addition of an element to my array when using React
Why is my page not updating with the addition of an element to my array when using React

Time:04-10

I am working on a basic react app where I use a form to submit a person's name then it will show up on the screen. After inputting the name, the array does properly get updated, but nothing changes on the screen. This is what I am using to show the person's name. In this case, I have useState on persons so I thought it should update. I am still quite new to React so any help is appreciated. Thanks in advance

{persons.map(person =>
    <div key={person}>{person.name}</div>
}

Edit:

const [persons, setPersons] = useState([
     { name: 'Arto Hellas' }
]) 
const [newName, setNewName] = useState('')

const addPerson = (event) => {
     event.preventDefault()
     setPersons(persons.concat(newName))
     setNewName('')
}

CodePudding user response:

const [persons, setPersons] = useState([
     { name: 'Arto Hellas' }
]) 
const [newName, setNewName] = useState('')

const addPerson = (event) => {
     event.preventDefault()
     setPersons([...persons,{name:newName}])
     setNewName('')
}

CodePudding user response:

Unfortunately, React doesn't think that you've changed the state when you use these kinds of array functions. It's generally recommended to use a callback in your setState call like:

const addPerson = (e) => {
    e.preventDefault();
    setPersons((prevPersons) => [...prevPersons, { name: newName }]);
    setNewName('');
}
  • Related