0
votes

I am trying to pull json data after storing it in AsyncStorage on an android emulator. I can pull the data inside an async function, but I can't store it in a variable to be used elsewhere in my code

The following code will pull the data, but I cannot call variable value any where else in my code:

async function getValue(){
  try {
    const value = await AsyncStorage.getItem('redditInsights')
    console.log(value)
    return value

  }
  catch (error) {
    console.log(error)
  }
}

If I define a variable like so: const insights = getValue() outside the above function, it seems to try an define insights before the getValue() function is finished retrieving the data and so returns it as an empty object

Your help is greatly appreciated!!

1
are you returning the value? return value to the place where getValue was called? Or, if you want, instead of a return, create a global variable and assing its value = to value - Calvin Nunes
Tried that, sorry let me fix the code above. When I define a variable like so: ` const insights = getValue()` it seems to try an define insights before the getValue() function is finished retrieving the data and so returns it as an empty object - Adam
Is it possible to define a global variable inside the async function? How do you do that? - Adam
try with global.myGlobalVar = value, then I think you can use this variable anywhere since it is global... - Calvin Nunes
Are you awaiting the async function getValue? const insights = await getValue(); - jvgaeta

1 Answers

0
votes

Try this way

const getValue = async () => {
  let value = '';
  try {
   value = await AsyncStorage.getItem('redditInsights')
  } catch (error) {
    // Error retrieving data
    console.log(error.message);
  }
  return value;
}