LoF10
LoF10

Reputation: 2127

How to properly fetch data from async storage in react native?

I am attempting to load and retrieve local data through asynchronous storage. I've laid out the current set up on a page, but am unable to retrieve data. Data is definitely saved as I receive a notification about it once I click store data. But when I proceed to call data it returns a null value. What am I doing something wrong here?

const STORAGE_KEY = '@save_enableauto'

    state={
        enableAuto:false
    }

    _storeData = async enableAuto => {
        try {
          let x = toString(enableAuto);
          await AsyncStorage.setItem(STORAGE_KEY, x)
          alert('Data successfully saved!')
          //this.setState({ enableAuto: x })
        } catch (e) {
            console.log(e)
          alert('Failed to save name.')
        }
      }

    _retrieveData = async () => {
        console.log('trying to call data')
        try {
          const enableAuto = await AsyncStorage.getItem('STORAGE_KEY');
          console.log(enableAuto)
          if (enableAuto !== null) {
            // We have data!!
            console.log(enableAuto);
          }
        } catch (error) {
            alert('failed to load previous settings.')
          // Error retrieving data
        }
    };

   ...

   <Button title={'Store Data'} onPress={() => this._storeData(this.state.enableAuto)}/>
                        <Button title={'call Data'} onPress={() => this._retrieveData()}/>
                    </View>    
                        <View>
                            <CheckBox
                                value={this.state.enableAuto}
                                onValueChange={() => this.setState({ checked: !this.state.enableAuto })}
                            />

Upvotes: 1

Views: 1395

Answers (1)

Gaurav Roy
Gaurav Roy

Reputation: 12210

The error above is while you are storing, you are setting :

await AsyncStorage.setItem(STORAGE_KEY, x)

and here STORAGE_KEY refers to value @save_enableauto

But while you are retrieving data

const enableAuto = await AsyncStorage.getItem('STORAGE_KEY');

you are giving 'STORAGE_KEY' as string , so that means its refering 'STORAGE_KEY' and it doesnt have any stored value. Try this

const enableAuto = await AsyncStorage.getItem(STORAGE_KEY);

Hope it helps. feel free for doubts

Upvotes: 1

Related Questions