Search code examples
javascriptreactjsreact-nativeasyncstorage

get value from async function in useState


I'm using async storage to retrieve my data but how do I use it with useState()?

Example:

async function getdata(){
let d= await AsyncStorage.getItem('Name');
return d;
}

export default function App() {
 const [name, setName] = useState(() => getdata());
 return (<View>...</View>)
}

but this doesn't work since getdata() is async, so how do I solve this problem?

Edit:

I forgot to mention I tried the useEffect() Hook like this:

async function getdata(){
let d= await AsyncStorage.getItem('Name');
console.log('retrieved Data!');
return d;
}

const [name, setName] = useState(()=>0);
  useEffect(() => {
    getData().then(setName);
    console.log('moving on...');
  }, []);

but the order of execution was:

'Moving on...'
'retrieved Data!'

where as it should have been the other way around


Solution

  • You'll initialize your state to some empty value. Maybe an empty string, maybe a null. If you like, you can have your component render something different during this time, such as a loading indicator. Then once the data loads, you can set state to render again.

    export default function App() {
      const [name, setName] = useState(null);
      useEffect(() => {
        getData().then(value => setName(value));
      }, []);
    
      if (name === null) {
        return <Text>Loading...</Text>
      } else {
        return (<View>...</View>)
      }
    }