Ad

Didn't Get Correct Return Of AsyncStorage.getItem()

- 1 answer

I've try to get value from key in AsyncStorage with sync function and try to print on console.log() command the value is correct on my expectation, but when i make an if with ternary it getting error like this.

Uncaught Error: Invariant Violation: Invariant Violation: Objects are not valid as a React child (found: object with keys{_40,_65,_55,_72)

Here part code of navigator react-native

Guest:{
screen:MainScreen,
navigationOptions: ({navigation}) => ({
    headerLeft:
          (async () => {
              const login = await AsyncStorage.getItem("isLogin");
              (login == null) ?
              <Text></Text>
              :
              <Icon
                style={{ paddingLeft: 10, color: '#ffffff', }}
                onPress={() => navigation.openDrawer()}
                name="menu"
                size={30}
              />
          })

       ,
    headerTransparent:true,
 })

}

Ad

Answer

Your headerLeft function returns Promise, as it is async

But headerLeft had to return React.Element i guess.

So better to remove async there and create separate component

import React, { useEffect, useState } from 'react';

const getLogin = async(setLogin) => {
  const login = await AsyncStorage.getItem('isLogin');
  setLogin(login);
}

export const HeaderLeft = ({navigation}) => {
  const [login, setLogin] = useState(null);
  useEffect(() => {
    getLogin(setLogin);
  }, []);
  return (login == null)
    ? <Text/>
    : <Icon
        style={{ paddingLeft: 10, color: '#ffffff', }}
        onPress={() => navigation.openDrawer()}
        name="menu"
        size={30}
      />
}

and use like

...
headerLeft: <HeaderLeft navigation={navigation}/>
....
Ad
source: stackoverflow.com
Ad