Pedro H Correia
Pedro H Correia

Reputation: 1

useState doesn't change when needed

The user must enter a name and hospital in the form, then their name and hospital will appear in a side menu. But I can't make it happen, useState returns an empty state so it's not working

export function Home() {
 
  const [nome, setNome] = useState("")
  const [hospital, setHospital] = useState("")
  const [describe, setDescribe] = useState("")
  const [patient, setNewPatient] = useState({})

  
  
  function handleCreateNewPatient(event){
    event.preventDefault()
    
    setNewPatient({
      id: nome.length,
      nome: nome,
      hospital: hospital,
      describe: describe
    })

    Users.push(patient)
    
  }

the code with UI material of the form

<form onSubmit={handleCreateNewPatient} >
             <div>
               <TextField
                 value={nome}
                 onChange={event=>setNome(event.target.value)}
               />
               <TextField
                 value={hospital}
                 onChange={event=>setHospital(event.target.value)}
               />
             </div>
             <div>
               <TextareaAutosize
               value={describe} 
               onChange={event=>setDescribe(event.target.value)}
            />
             </div>
             <Button type="submit">Confirmar</Button>
           </form>

Upvotes: 0

Views: 48

Answers (2)

hackhan
hackhan

Reputation: 522

State updates are not synchronous in React. You can do something like this:

function handleCreateNewPatient(event){
    event.preventDefault();

    const patient = {
      id: nome.length,
      nome: nome,
      hospital: hospital,
      describe: describe
    };

    setNewPatient(patient)
    Users.push(patient)
  }

or write an effect as mentioned in the other answer.

Upvotes: 0

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

The issue is here:

setNewPatient({
      id: nome.length,
      nome: nome,
      hospital: hospital,
      describe: describe
    })

    Users.push(patient)

setState() is asynchronous. React does not guarantee that the state changes are applied immediately. Think of setState() as a request rather than an immediate command to update the component.

To get the updated value you have to use useEffect like:

useEffect(() => {
    if( patient.hasOwnProperty('id') )  // Checking if patient is set or not
    {
        Users.push(patient)
    }
}, [patient]);  // Here `patient` is the dependency so this effect will run every time when `patient` change.

Such type of logic will help you.

Upvotes: 1

Related Questions