0

Hello StackOverflow I want to pass data in my JSON object into my drawer class. I could not access this object in my second class I am pretty new in react native so any suggestions would be more appreciated

Below code for my classes My userLoginFunction it will give me my json object screenshot given below

UserLoginFunction = () =>{
 const { UserContact }  = this.state ;
 const { UserPassword }  = this.state ;
 if(this.state.UserContact == ""){
   ToastAndroid.show('Pleas Enter Contact Number Correctly ',ToastAndroid.SHORT)
 }
 else if (this.state.UserPassword == ""){
   ToastAndroid.show('Please Enter Password Correctly',ToastAndroid.SHORT)
 }
 else{

fetch(urls.localhosturl + urls.login, { 
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
 
    user_contact: UserContact,
    user_password: UserPassword,
   
 
  })
 
})
      
      .then((response) => response.json())
      .then((responseJson) => {

        
        // If server response message same as Data Matched
         if(responseJson.status === '200')
          {
            //Save User Details to Local Storage
            AsyncStorage.setItem("responseJson", JSON.stringify(responseJson));            this.props.navigation.navigate("Home","DrawerComponent",{userData:responseJson.data,
            });
            console.log(responseJson.data)
        }
        else{
          ToastAndroid.show(responseJson,ToastAndroid.SHORT);
          //Alert.alert(string,responseJson);
          
        }

      }).catch((error) => {
        console.error(error);
      });
 
    }
  }
JSON Object coming from userLoginFunction

This is my drawercomponent class in which I want to access that json object data like user_name, etc. ...

class DrawerComponent extends React.Component {  
  drawerOptions = [
    {title: 'About Us', route: 'AboutUs', icon: 'md-card'},
    {title: 'Journey Prayers', route: 'Prayers', icon: 'md-ribbon'},
    {title: 'Recharge', route: 'Recharge', icon: 'md-cash'},
    {title: 'Help Line', route: 'HelpLine', icon: 'md-call'},
    {title: 'Media', route: 'Media', icon: 'md-radio'},
    {title: 'Motorway Sites', route: 'MotorwaySites', icon: 'md-pin'},
    {title: 'Notifications', route: 'Notifications', icon: 'md-notifications'},
    
  ];

  render() {
    
    return (
      <SafeAreaView style = {{flex : 1}}>
        <ScrollView>
      <View style = {{height : 150 , backgroundColor : 'white' , alignItems : 'center' , justifyContent : 'center'}}>
            <Image source = {require('../images/profile.jpg') } style = {{height : 120 , width : 120 ,
          borderRadius : 60 , marginTop : 45}} />
          //here i want to display username from json object
          <Text>Haseeb</Text>
          
       </View>
      <View style = {{ marginTop : 30,height : 30 , backgroundColor : 'white' , alignItems : 'center' , justifyContent : 'center'}}>
          <Text style= {{fontWeight: 'bold',fontSize: 20,textAlign: 'center'}}>
          </Text>
      </View>
      <View style={{borderBottomColor: '#dedede',marginTop: 25, borderBottomWidth: 1}}/>


      <View style={{flex: 1, marginTop: 10}}>
        {this.drawerOptions.map(item => (


          <TouchableOpacity
            style={{padding: 16}}
            onPress={() => {
              this.props.navigation.toggleDrawer();
              this.props.navigation.navigate(item.route);
            }}
            key={item.title}>
            <Text >
            <Ionicons name = {item.icon} size={24} style={{color: '#282828'}} />
            <Text>  </Text>
              {item.title}</Text>
          </TouchableOpacity>
        ))}
      </View>
      </ScrollView>
      </SafeAreaView>
    );
  }
}

2
  • 2
    Side note: JSON is a textual notation for data exchange. (More here.) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. You have an object (the result of calling .json()), not a JSON object. Commented Aug 4, 2020 at 8:35
  • 1
    Please reduce the code in the question question to a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the [<>] toolbar button). Stack Snippets support React, including JSX; here's how to do one. Commented Aug 4, 2020 at 8:37

2 Answers 2

1

Well, you are on a good way. You already save the item into your local storage, so in the second component, you only have to load it when the component mounts. For that you would use the getItem method of AsyncStorage and save the result in your state:

class DrawerComponent extends React.Component {
  state = { myItem: { data: { user_name: "" } } }

  componentDidMount() {
    const stringifiedItem = AsyncStorage.getItem("responseJson");
    if (stringifiedItem) {
      // Turn the string back into an object
      const myItem = JSON.parse(stringifiedItem);
      // Put it into state
      this.setState({ myItem });
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Depends on how it was originally saved in the responseJson object. Looking at your screenshot, it should be accessible via this.state.myItem.data.user_name.
when I want to display this in <Text>this.state.myItem.data.user_name</Text> it give me error "TypeError:undefined is not an object (evaluating 'this.state.myItem.data.user_name') "
0

this is how to get async storage data in anywhere in class if u have the whole object saved.

state = { userData: {}}

  async componentDidMount() {
    const stringifiedItem = await AsyncStorage.getItem("responseJson");
    // Turn the string back into an object
    const userData = JSON.parse(stringifiedItem);
    // Put it into state
    this.setState({ userData:userData.data });
    //console.log(userData.data)
    
  }
  
  

This is how to get data from async storage to text component

<Text>{this.state.userData.user_name}</Text>

Comments

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.