0

I have a problem with setState. I want to check if the username has been taken before.

this is my useState:

const [checkUserExist, setCheckUserExist] = useState(false)

This is my function which I check the username

const checkUserIfExist = async (username) => {
    const result = await axios.get(
      `http://localhost:3000/users?username=${username}`
    );

    if (result.data.length > 0) {
      setCheckUserExist(true);
    } else {
      setCheckUserExist(false);
    }

    console.log(result.data.length); // I check how much data is coming
  };

This is my add function with axios to json-server

const addUser = (username, password) => {

    checkUserIfExist(username);

    if (checkUserExist) {
      alert("You should change your username");
    } else {
      console.log("Successful");
    }

    
  };

But unfortunately this is working a bit late. When I click Login button first time, it shows like this :

login button clicking first time

login button clicking second time

It doesn't work when I click login button first time. It works after first clicking. How can I solve this problem ?

I am expecting that when I click login button, it must throw an alert but it throw an alert after first clicking

  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Emile Bergeron Jul 13 '23 at 15:30
  • 1
    @EmileBergeron thanks for answering ! this will helps me. Thanks a lot :) – YunusEmre55 Jul 14 '23 at 18:06

0 Answers0