0

hey all so im using react-natives-community async storage and i can't for the life of me get the state to save and im not too sure why. the first console.log from the await variable returns the correct information, but when i set the state the second console.log returns null and im not sure what's going on

const [userEmail, setUserEmail] = useState<string | null>(null);

const getEmail = await AsyncStorage.getItem('email')
console.log(getEmail + 'first')
setUserEmail(getEmail);
console.log(userEmail + 'second')

I made this custom hook but still no luck

const useGetAsyncStorage = (AsyncStorageItem: string): string => {
  try {
    const [data, setData] = useState<string | null>(null);
    useEffect(() => {
      const fetchAsyncStorage = async () => {
        const AsyncStorageData = await AsyncStorage.getItem(AsyncStorageItem);
        console.log(AsyncStorageData)
        setData(AsyncStorageData);
      };
      fetchAsyncStorage();
    }, [AsyncStorageItem]);

    return data as string
  } catch (error) {
    return error
  }
};
keil
  • 395
  • 1
  • 3
  • 15
  • The thing is state updates are asynchronous. You will end up seeing the same result as in first . If you want to see the change , you should do console.log in useEffect() hook. – Harmandeep Singh Kalsi May 30 '20 at 19:14

1 Answers1

0

The thing is state updates are asynchronous. You will end up seeing the null for the email what it was initially . If you want to see the change , you should do console.log in useEffect() hook

Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
  • so how i would go about updating the state. becasue i don't see the same result in first the first is (johnDoe@gmail.com) and the second is (null) – keil May 30 '20 at 19:44
  • Actually it will not be the same as first , it should be previous state , which is null. I updated my answer – Harmandeep Singh Kalsi May 30 '20 at 19:50
  • so i made this custom hook and it's still not working `const useGetAsyncStorage = (AsyncStorageItem: string): string => { try { const [data, setData] = useState(null); useEffect(() => { const fetchAsyncStorage = async () => { const AsyncStorageData = await AsyncStorage.getItem(AsyncStorageItem); console.log(AsyncStorageData) setData(AsyncStorageData); }; fetchAsyncStorage(); }, [AsyncStorageItem]); return data as string } catch (error) { return error } };` – keil May 30 '20 at 19:53