Somename
Somename

Reputation: 3434

Unable to setItem in AsyncStorage

I'm unable to setItem with AsyncStorage. Following is my code. So I'm getting the name in state from a TextInput and then want to store it in AsyncStorage onPress of TouchableOpacity. I'm getting error:

enter image description here

import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity} from 'react-native';

class AsyncStorage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            name:''
        }
        //this.asyncSetName = this.asyncSetName.bind(this)   //tried this too.
   };

    asyncSetName(){
        let name = this.state.name
        AsyncStorage.setItem('name', name);
    }

    render(){
        <View>
            <TextInput
                placeholder='Set Name here'
                onChangeText={(name) => this.setState({name})}
                value={this.state.name}
                autoCorrect={false}
            ></TextInput>

            <TouchableOpacity
                onPress={this.asyncSetName.bind(this)}
            >
                <Text>SetName</Text>
            </TouchableOpacity>
        </View>
    }
}

What am I doing wrong? Please help.

Upvotes: 3

Views: 382

Answers (2)

Amr Labib
Amr Labib

Reputation: 4073

You need to import AsyncStorage from react-native

import { View, Text, StyleSheet, TextInput, TouchableOpacity , AsyncStorage} from 'react-native';

You will also need to keep the binding of asyncSetName function

uncomment this line

this.asyncSetName = this.asyncSetName.bind(this)

Also as spotted by @Chris you need to change your class name to be different from AsyncStorage

Upvotes: 4

Chris Geirman
Chris Geirman

Reputation: 9684

  1. As @Amir said, you need to import AsyncStorage from react-nativeas well as keep the binding as he suggests.
  2. You'll probably want to rename your class to something other than AsyncStorage too at this point
  3. Optionally, you might want to namespace your AsyncStorage key. It's common to put an @AppName in front of the key, so your final key would end up being @AppName${this.state.name}. But again, this is optional and merely convention.

Upvotes: 2

Related Questions