简体   繁体   中英

React-native AsyncStorage Issue

In the code snippet you see, I am trying to reach the data that I have determined through asyncStorage in the getToken and `` functions, but when I open the page with these codes from the emulator, the data is empty for the first time, and then when I do ctrl+s from the editor, the data is full. What is the reason for this problem?

App.js Page

    getToken: async () => {
      const token =  AsyncStorage.getItem('userToken');
      return token;
    },
    getMail: async () => {
      const mail =  AsyncStorage.getItem('userMail');
      return mail;
    },

OrderListScreen Page

        getToken().then((res) => {
            if(res){
            setToken(res);
            console.log(token)
            }else {
              setToken('');
            }
        });
        getMail().then((res) => {
            if(res){
            setMail(res);
            console.log(mail)
            }else {
              setMail('');
            }
        });

Apply await before using AsyncStorage.getItem :

getToken: async () => {
  const token = await AsyncStorage.getItem('userToken');
  return token;
},
getMail: async () => {
  const mail =  await AsyncStorage.getItem('userMail');
  return mail;
},

In the log you'll not get the updated state in next line of state setter.

getToken().then((res) => {
    if(res){
    setToken(res);
    console.log(token); //You'll never get this value here because state updates are asynchronous in React
    console.log("res : ", res);
    }else {
      setToken('');
    }
});
getMail().then((res) => {
    if(res){
    setMail(res);
    console.log(mail)//You'll never get this value here because state updates are asynchronous in React
    console.log("Email Res : ", res);
    }else {
      setMail('');
    }
});

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