Search code examples
reactjsreact-nativeasyncstorage

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.


Solution

  • 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