Failed to set identifier in AsyncStorage

I can not setItemwith AsyncStorage. The following is my code. Therefore, I get the name in the state from TextInput, and then I want to save it in AsyncStorage onPress TouchableOpacity. I get an error message:

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.

+4
source share
2 answers

You need to import AsyncStoragefromreact-native

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

You also need to keep the function binding asyncSetName

uncomment this line

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

Also, as @Chris pointed out, you need to change the name of your class so that it differs from AsyncStorage

+4
source
  • As @Amir said, you need to import AsyncStoragefrom react-native, and also keep the binding as it suggests.
  • , , - , AsyncStorage
  • , , AsyncStorage. @AppName, @AppName${this.state.name}. , .
+3

Source: https://habr.com/ru/post/1689831/


All Articles