0

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;
4
  • Put checkCache in a useEffect. stackoverflow.com/questions/53819864/… Commented Jun 22, 2021 at 23:11
  • You would want to make the arrow function async, const displayImage = async () => {...} if you want the inner function call to use await. Commented Jun 22, 2021 at 23:13
  • 1
    Does this answer your question? How to async await in react render function? Commented Jun 22, 2021 at 23:13
  • Thanks everyone using useEffect solved my issue. Thank you for sending me in the right direction. Commented Jun 24, 2021 at 5:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.