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