Ruchira Swarnapriya
Ruchira Swarnapriya

Reputation: 1015

Set State inside axios post method

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

Answers (3)

Antonio Erdeljac
Antonio Erdeljac

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

1. useEffect


useEffect(() => { if (validated) { ...do something... } }, [validated])

2. setState callback

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

kunquan
kunquan

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

Or Assayag
Or Assayag

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

Related Questions