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
>Solution :
To solve this problem, you can make use of the useEffect hook to watch for changes in the checkUserExist state. Here’s an updated version of your code that addresses the issue:
const addUser = async (username, password) => {
await checkUserIfExist(username);
if (checkUserExist) {
alert("You should change your username");
} else {
console.log("Successful");
}
};
const checkUserIfExist = async (username) => {
const result = await axios.get(
`http://localhost:3000/users?username=${username}`
);
setCheckUserExist(result.data.length > 0);
};
useEffect(() => {
checkUserIfExist(username); // Make an initial check when the component mounts
}, []); // Empty dependency array ensures the effect only runs once
With these changes, the checkUserIfExist function will be executed before the if (checkUserExist) check, ensuring that the state is updated before the condition is evaluated.