Home > database >  Why is my setState not updating the state or triggering re-render?
Why is my setState not updating the state or triggering re-render?

Time:03-02

const handleFormSubmit = (event) => {
    event.preventDefault()
    let match = persons.filter(person => person.name === newName)
    if (!(match.length > 0 && window.confirm(`${newName} is already added to phonebook, replace the old number with a new one?`))) {
      let newPerson = {name: newName, number: newNumber, id: persons[persons.length - 1].id   1}
      ContactServices
        .create(newPerson) //this is a function linked to API to update the phonebook
        .then(response => {
          setPersons(persons.concat(response))
          setFilterPersons(persons)
          setNewName('')
          setNewNumber('')
          //the four setState above does not work but setMessage works
          setMessage(`new number ${newPerson.name} is added`)
          setTimeout(() => {
            setMessage(null)
          }, 5000)
        })
    }
//...rest of the code

I'm having problems figuring out why only some of my setStates don't work. setMessage works but not setPersons or setNewName. I tried passing in a function instead a new object into setState, and console.log within the callback function. It worked so it seems that the function is executed but the new state is just not saved? I cannot use useEffect in a callback function here either.

CodePudding user response:

change this condition to something meaningful for javascript this condition always returns false so your code inside ** if ** never works

window.confirm(`${newName} is already added to phonebook, replace the old number with a new one?`)){

CodePudding user response:

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it runs before the state has actually finished updating.

Which is why we have useEffect, a built-in React hook that activates a callback when one of it's dependencies have changed.

Example:

useEffect(() => {
   // Should show updated state -
   console.log(state);
}, [state])

The callback will run only after the state has finished changing and a render has occurred.

Note: "state" in the example is interchangeable with whatever state piece your dealing with in your case, be it persons / newName / newNumber etc..

  • Related