Search code examples
javascriptreactjsreact-nativeasyncstorage

React native-How to return item from AsyncStorage to use outside of async function?


I'm trying to use an item from AsyncStorage, stored as a variable created in an async function, however, when it is returned, it returns as undefined.

import React from 'react';
import {View,Text,TouchableOpacity,StyleSheet}from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
function App(){
  async function save() {
    let info = ['space']
    AsyncStorage.setItem('key', JSON.stringify(info))
  }
  async function show1() {
    try {
      let show = await AsyncStorage.getItem('key');
      show = JSON.parse(show)
      console.log('item:', show)
      return show;
    } catch (error) {
      console.log(error)
    }
  }
  const read=(show)=> {
    console.log(show)
  }
  show1();

The function read is called by a button and logs 'undefined' instead of ['space'].In the async function it correctly logs show as ['space'], but doesn't seem to return it. Is it possible to use an aysnc item outside of an async function or am i missing something.


Solution

  • By defining

    const read=(show)=> { console.log(show) }

    you are declaring a function that takes a parameter, that will be referred as show in the scope of that function.

    What you should be doing is:

    const read = show1();
    console.log(read);`
    

    or

    const read = () => {
     console.log(show1());
    }
    read();
    

    What you should remember is that when you declare a variable in a function, it is not accessible outside the scope of this function.

    So if you do:

    function myAssign() {
    let a = 10;
    console.log(a) // 10
    }
    console.log(a) // undefined