0

my form only writes the previous value

let [userStateLog, userSetStateLogin]:any = useState({login: ''})

function changeLogin(event:any){
      userSetStateLogin({[event.target.name]:event.target.value})
}

<input placeholder="Login" name="login" onChange={changeLogin} className="login"/>

when writing a value through onchange, only the previous value is written to the state parameter

1 onchange event => event.targe.value = 1 => myState = ' '

2 onchange event => event.target.value = 12 => myState = '1'

3 onchange event => event.target.value = 123 => myState = '12'

I don't understand why myState is one step behind

How to fix it? When sending to another component and returning a checked value. Lagging can be observed in 2 - 3 steps. How do I fix this?

all code :

export default function Auth ():JSX.Element {
   let [userStateLog, userSetStateLogin]:any = useState({login: ''})
   function changeLogin(event:any){
      let login:any = document.querySelector('.login')
      userSetStateLogin({[event.target.name]:event.target.value})
      console.log(userStateLog)
   }
   return(<>
   <input placeholder="Login" name="login" onChange={changeLogin} className="login"/>
   </>)
}

enter image description here

thanks to all! it helped me a lot!

HLEB HLEB
  • 128
  • 8
  • 1
    where is your value prop on your input? can you share the full component please – İlker Jul 10 '21 at 08:20
  • 1
    Where are you performing your `console.log()`? The `userSetStateLogin()` won't change `userStateLog` immediately once it is called. – Nick Parsons Jul 10 '21 at 08:23
  • console.log() - I use immediately after calling – HLEB HLEB Jul 10 '21 at 08:26
  • 1
    @HLEBHLEB yeah, that's your issue then. `userSetStateLogin()` will eventually cause your component to re-render with the new/updated `userStateLog` value. You can see so by moving your log before you `return` your JSX from your component to log upon each render. – Nick Parsons Jul 10 '21 at 08:31
  • how then to make it update immediately? – HLEB HLEB Jul 10 '21 at 08:31
  • 1
    React state updates are asynchronously processed. Log the updated state in an `useEffect` with appropriate dependency. – Drew Reese Jul 10 '21 at 08:32
  • i used useEffect. But the problems kept repeating – HLEB HLEB Jul 10 '21 at 08:33
  • If issue persists can you try creating *running* codesandbox that reproduces the issue for us to inspect and live debug? – Drew Reese Jul 10 '21 at 08:41

0 Answers0