Search code examples
react-nativeasyncstorage

Why is AsyncStorage getAllKeys not returning null? Have multiple views, want to render based on if data found, deleted all keys


I have a boolean called isDataReady stored in the state. If I find keys via AsyncStorage, I set it true and display a list of data. If nothing is found then I want to render a different view. My data is displaying fine but with everything deletef, I can't get my intro screen to display. Its because AsyncStorage is never null despite their being no keys. What am I doing wrong?

Code (view related code removed for clarity)

 constructor() {
    super();
    this.state={
      meals: [],
      isDataReady: false,
    }
  }

  componentDidMount() {
    this.getAllMeals();
  }

  getAllMeals = async () => {    
    try {
        const data = [];
        let keys = await AsyncStorage.getAllKeys();
        // await AsyncStorage.multiRemove(keys);
        if (keys !== null) {
          for (let inKey of keys) {
            let obj = await AsyncStorage.getItem(inKey);
            obj = JSON.parse(obj);
            obj["key"] = inKey;
            data.push(obj);
        }
        this.setState({
          meals: data,
          isDataReady: true
        })
      } else {
        this.setState({
          isDataReady: false
        })   
      }
      } catch (error) {
        console.log("Error saving all meals. Error: " + error)
      }
    }

 render() {
  if (this.state.isDataReady === true) {
      return (
        <View style={styles.container}>
            </View>         
    );
  } else if (this.state.isDataReady === false) {
      return (
        <ScrollView>
        <View style={styles.container}>
      </View>
    </ScrollView>
    );
   }
 }
}

Solution

  • I change the if statement to if (keys.length !== 0), always returns array so its never null.