Reputation: 1015
I have axios post method to check username
and password when they available I want to set a state as true
but always get the state as false
.
My code is:
const [validated, setValidated] = useState(false);
const login = () => {
Axios.post('http://124.43.17.60:4000/loginnew', {
username: email,
password: password
}).then((response) => {
// let data = response.data
console.log("my web response all", response)
console.log("my web response", response.data[0])
try {
if (response.data[0].role) {
let role = response.data[0].role
setValidated(true)
console.log(validated)
if (role == "admin") {
history.push('/admin')
} else {
history.push('/member')
}
}
} catch (err) {
alert.error("wrong credentials");
}
});
}
Can anyone tell me what um doing wrong and please help me to solve this problem
Upvotes: 1
Views: 67
Reputation: 3244
In React, modifying the state is an asynchronous action. Meaning that this piece of code won't give your expected results:
setValidated(true)
console.log(validated) // Won't be updated to true
If you want to achieve something specifically on true
, you have 2 options
useEffect(() => { if (validated) { ...do something... } }, [validated])
setValidated((oldValidated) => {
const newValidated = !oldValidated;
console.log(newValidated) // true if oldValidated was false
// do something with newValidated === true
return newValidated; // Make sure to return the new value, otherwise state won't update at all.
})
Upvotes: 2
Reputation: 1267
You cannot view the "updated" state inside you login
function as setValidated
is an asynchronous process, which mean the code will not wait for the data to get back and still use the old value. Read this post for more explanation
If you want to view the "updated" value of validated
you need to create a useEffect
like so
useEffect(() => {
console.log(validated)
})
Upvotes: 1
Reputation: 6336
useEffect(() => {
Axios.post('http://124.43.17.60:4000/loginnew', {
username: email,
password: password
}).then((response) => {
// let data = response.data
console.log("my web response all", response)
console.log("my web response", response.data[0])
try {
if (response.data[0].role) {
let role = response.data[0].role
setValidated(true)
console.log(validated)
if (role == "admin") {
history.push('/admin')
} else {
history.push('/member')
}
}
} catch (err) {
alert.error("wrong credentials");
}
});
}, []);
Upvotes: 0