Home > Enterprise >  React useState and setState not updating immediately
React useState and setState not updating immediately

Time:11-24

When I press a key and try to display it on console, the previous value will be it's current value based on the console

import {useState } from "react";

const [username,setUsername] = useState("");

const onChangeUsername = (event) => {
    setUsername(event.target.value);
    console.log(username)
    Axios.post(hostServer "user/guestCheck", {
        username:username
    }).then((response) => {
        console.log(response);
    });
}

<input required type="text" name="username" placeholder="Username" autoComplete="off"
onChange={onChangeUsername} ></input>

How can I get the real current value using this code?

CodePudding user response:

You could use the event.target.value but the usual approach is it use a useEffect that depends on the value of username

(and as an additional improvement you could use useCallback for the change handler to avoid creating a new one on each keystroke)

import {useState, useCallback, useEffect} from "react";

const [username, setUsername] = useState("");


const onChangeUsername = useCallback((event) => {
  setUsername(event.target.value);
}, [])

useEffect(() => {
  console.log(username);
  
  Axios.post(hostServer   "user/guestCheck", {
    username: username
  }).then((response) => {
    console.log(response);
  });
}, [username]);

Keep in mind thought that this code will create a new request for each keystroke, which might be a bit aggressive/taxing for the backend. Perhaps you should debounce it a little.

CodePudding user response:

Method1: Try posting the data to server from event.target.value

import {useState } from "react";

const [username,setUsername] = useState("");

const onChangeUsername = (event) => {
    setUsername(event.target.value);
    console.log(username)
    Axios.post(hostServer "user/guestCheck", {
        username:event.target.value
    }).then((response) => {
        console.log(response);
    });
}

<input required type="text" name="username" placeholder="Username" autoComplete="off" onChange = { onChangeUsername } > </input>
    

Method2: Use useEffect hook that will post the data once the username is updated and component is re-rendered.

import {useState } from "react";

const [username,setUsername] = useState("");

useEffect(() => {
    Axios.post(hostServer "user/guestCheck", {
        username:event.target.value
    }).then((response) => {
        console.log(response);
    });
}, [username])
const onChangeUsername = (event) => {
    setUsername(event.target.value);
    console.log(username);
}


<input required type="text" name="username" placeholder="Username"`enter code here`autoComplete="off" onChange = { onChangeUsername } > </input>

CodePudding user response:

You can simply use the effect() hook that will render according to your data change.

Here a demo https://codesandbox.io/s/fervent-satoshi-xxyxf?file=/src/App.js

CodePudding user response:

useState and setState work asynchronous. So it's not update state immediately. There are two way to solve your problem.

  1. You can pass the value directly without saving in a state

    import {useState } from "react";
    const [username,setUsername] = useState("");
    const onChangeUsername = (event) => {
    setUsername(event.target.value);
    let userName =event.target.value; 
    console.log(username)
    Axios.post(hostServer "user/guestCheck", {
      username:userName
    }).then((response) => {
     console.log(response);
    });
    }
    <input required type="text" name="username" placeholder="Username" 
    autoComplete="off"
    onChange={onChangeUsername} ></input>
    
  2. You can use in useEffect and pass username

    import {useState, useEffect } from "react";
    
    const [username,setUsername] = useState("");
    
    const onChangeUsername = (event) => {
    setUsername(event.target.value);
    console.log(username)
    }
    
     useEffect(() => {
       funcToCallApi()
        }, [username]);
    
       funcToCallApi() {
         console.log(username)
    
         Axios.post(hostServer "user/guestCheck", {
         username:username
         }).then((response) => {
         console.log(response);
         });
        }
    
  • Related