Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 206
Somename Avatar asked Mar 08 '23 12:03

Somename


1 Answers

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

like image 196
Amr Labib Avatar answered Mar 15 '23 02:03

Amr Labib