2

I'm trying to use Async storage to store two Text Input values stored as an object and pass it to a different view where they'll be displayed on a button press.

As mentioned in other StackOverflow posts I've used JSON.parse and JSON.stringify to pass the object as JSON data, still for some reason I;m getting the error JSON Parse Error: Unexpected Identifier "Undefined"(React Native)

Add Data

class AddData extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        text1: '' ,
        text2: ''

    };
}
  render() {
      function BtnPress() {
          alert('Hi')
      }
    return (
      <View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
          <TextInput
          style={{height: 40,width:200}}
          onChangeText={(text1) => this.setState({input1: text1})}
            />
          <TextInput
          style={{height: 40,width:200}}
          onChangeText={(text2) => this.setState({input2: text2})}
            />
            <Button
            onPress={() => {
                AsyncStorage.setItem('user', JSON.stringify({
                    name:'Rohit',
                    email: 'rohitgird12gmail.com'
                }));
                this.props.navigation.navigate('Home', {});
            }}
            title="Submit"
/>


      </View>


    );
  }
}

View to Display Data

class DetailsScreen extends React.Component {

         displayName = async ()=> {
            try {
              const myArray = await AsyncStorage.getItem('user');
              if (myArray !== null) {
                alert(JSON.parse(myArray.name));
              }
            } catch (error) {
                alert(error)
            }
        }
  render() {

    return (
      <View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
      <Button
      onPress={this.displayName}
      title="Get Data"
/>

      </View>
    );
  }
}

1 Answer 1

2

It looks like const myArray = await AsyncStorage.getItem('user'); is returning undefined while you defended yourself from null only, which is not sufficient here.

Antoher possible problem lies here : JSON.parse(myArray.name). Are you sure it's not supposed to be JSON.parse(myArray).name?

Sign up to request clarification or add additional context in comments.

1 Comment

You are right. It should be JSON.parse(myArray).name instead of JSON.parse(myArray.name)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.