Using React Native Await/Async in main function

So I am using async functions and await to retrieve data from the async storage cache and depending on whether it is in the cache or not I would like to change the text on the screen based on whether it is in the cache or not. The problem I'm running into however is ReactNative doesn't let me declare my main function to use async which causes me to get the data from checkCache() too early. The cache has already has data from a different screen stored for the key 'test_code'.

How can I make CodeTest() an async function in order to use the await method in front of checkCache() so that I can display the correct text?

import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  SafeAreaView,
  TouchableOpacity,
} from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";

async function checkCache() {
  var isCodeCached = false;
  try {
    result = await AsyncStorage.getItem('test_code');
    if (result != null) {
      console.log("result is valid");
      console.log(result);
      isCodeCached = true;
    } else {
      console.log("result is not valid");
    }
  } catch (e) {
    console.log("Retrieval failed!");
  }

  return isCodeCached;
}

function CodeTest() { 
  const displayImage = () => {
    var x = 1;
    var isCodeCached = checkCache();
    if (isCodeCached === true) {
      return (
        <SafeAreaView>
          <Text style={styles.text}> Hello world</Text>
        </SafeAreaView>
      );
    } else {
      return (
        <SafeAreaView>
          <Text style={styles.text}> Hello universe</Text>
        </SafeAreaView>
      );
    }
  };

  return CodeTest();
}

export default CodeTest;


Read more here: https://stackoverflow.com/questions/68091610/using-react-native-await-async-in-main-function

Content Attribution

This content was originally published by LegoBrick at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: