简体   繁体   中英

State not set in useEffect

I have a function to get data from local storage and set that local storage value to state but value doesn't set the state

this is my code,

 const [mobileNum, setMobilenum] = useState();

 useEffect(() => {
        getDatalocal();
    }, []);

async function getDatalocal() { // get data from local
        try {
            let mobileNumRes = await AsyncStorage.getItem('@number_Token')
            setMobilenum(mobileNumRes) // set mobile number for state
            console.log("mobile num ======================================>>>", mobileNum)

           
        } catch (error) {
            console.log("error in get mobile no", error)
        }
    }

I'm calling this function in useEffect, Can anyone tell what I am doing wrong and please help me to solve this

setMobilenum is the asynchronous method, so you can't get the updated value of mobileNum right after setMobilenum . You should get it in the another useEffect with adding a dependency mobileNum .

const [mobileNum, setMobilenum] = useState();

useEffect(() => {
    getDatalocal();
}, []);

async function getDatalocal() { // get data from local
    try {
        let mobileNumRes = await AsyncStorage.getItem('@number_Token')
        setMobilenum(mobileNumRes)
    } catch (error) {
        console.log("error in get mobile no", error)
    }
}

useEffect(() => {
    console.log("mobile num ==============>>>", mobileNum)
}, [mobileNum]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM