skip to Main Content

I’m building a mobile game using react native and I’m trying to retrieve the best value storage on it to display on the screen. The problem is that it seems that react native is rendering the screen before it retrieves the value and then it doesn’t re-render when the value is updated using setBest(), so no value is displayed.
Here is the code:


  const navigation = useNavigation()
  const [result, setResult] = useState('')
  const [best, setBest] = useState('')

  
  
  useEffect(() => {
    const Storage = async (key,value) => {
     await AsyncStorage.setItem(key,value)
    }
    const Retrieve = async (key) => {
      const value = await AsyncStorage.getItem(key)
      setBest(()=>value)
   
    }

    Retrieve('1').catch(console.error)
    setResult(route.params.paramKey)

    if(route.params.paramKey>best){
      var aux = result.toString()
       Storage('1',aux)
      console.log(best)
}
  }, [])
  


  return (
    <View style={styles.container}>
      <View style={styles.textView}>
        <Text style={styles.tituloText}>Melhor pontuação</Text>
        <Text style={styles.tituloText}>{best}</Text>
        <Text style={styles.tituloText}>Sua pontuação</Text>
        <Text style={styles.resultText}>{result}</Text>

        <View style={styles.viewBtn}>

          <TouchableOpacity style={styles.viewBack} onPress={() => navigation.navigate('Modo1')}>
            <Icon style={styles.iconBack} name="backward" />
          </TouchableOpacity>
          <TouchableOpacity style={styles.viewHome} onPress={() => navigation.dispatch(StackActions.popToTop)}>
            <Icon style={styles.iconBack} name="home" />
          </TouchableOpacity>
        </View>
      </View>

    </View>
  );
}

Thanks for the help guys! I’ve been struggling with this for days and any help will be appreciated!

2

Answers


  1. This is how you retrieve the value..

     useEffect(() => {
    
    
            AsyncStorage.getItem('key').then(value => {
              if (value != null) {
                 console.log(value);
                setBest(value);
              }
            });
          }, []);
    

    also don’t forget to add the import statement..

    To set the value you must use

      AsyncStorage.setItem('key', value);
    
    Login or Signup to reply.
  2. You can use Async Functions inside of ~useEffect()` like this:

      useEffect(() => {
       (async () => {
        async function getData() {
          try {
            const value = await AsyncStorage.getItem('myKey');
            if (value !== null) {
              setData(value);
            }
          } catch (error) {
            console.log(error);
          }
        }
        getData();
        })();
      }, []);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search