Abhi
Abhi

Reputation: 480

React - How to access single value from array of array json object

I have a JSON in localstorage and i want to access some of the values from that.

I got proper email, but when i am trying to get 'company_name' It says

TypeError: cannot read property 'company' of undefined

Please help me with role_name too.

Thank you

Profile.js

import React, { Component } from 'react';
import axios from 'axios';

class Profile extends Component {

  constructor(props) {
    super(props);

    this.state = {
      getUserData:[],
    };
  }   

  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  };

  componentDidMount() {
    let getUserData = localStorage.getItem("userData"); 
    this.setState({ 
      getUserData: JSON.parse(getUserData), 
    });   
  }

  render() {
      return (
        <div>             
           <h3>Hello {this.state.getUserData.email}</h3>
            
           <h6>Company Name</h6>
                        
           <h5>{this.state.getUserData.user_profile.company.company_name}</h5>
                        
           <h6>Miles</h6>
                        
           <h5>{I want miles here}</h5>
                        
           <h6>Role Name</h6>
                       
           <h5>{I want role_name here}</h5>
        </div>
      )    
  }
}

export default Profile;

My JSON is like this-

{"id":6,"email":"[email protected]","phone":"","is_active":1,"is_verified":1,"is_deleted":0,"qb_id":null,"qb_password":null,"token":"eyJ0eXAiOiJKV1Qi","common_chat_supervisor_id":"60a7a109ce5b15001ecf6e28","user_profile":{"id":6,"user_id":6,"company_id":2,"first_name":"","last_name":null,"profile_photo":null,"gender":null,"date_of_join":null,"date_of_birth":null,"user_roles":[{"id":6,"role_id":7,"user_profile_id":6,"role_name":"company_employee","role_display_name":"Company Employee"}],"company":{"id":2,"company_name":"AMAZON INDIA","company_type":2,"con_name":"ANKIT BOKARE","con_email":"[email protected]","company_address1":"Brigade Gateway, 8th floor, 26/1","company_address2":"Dr. Rajkumar Road, Malleshwaram(W)","company_city":"Bangalore","company_state":"Karnataka","company_country":"INDIA","company_zipcode":"560055"},"locations":{"id":5,"user_profile_id":6,"city_id":1,"miles":"1","region":"1","site":"Gujrat"}}}

Upvotes: 0

Views: 35

Answers (1)

Priyank Kachhela
Priyank Kachhela

Reputation: 2635

First if your userData in local storage is object than you can initialize getUserData as blank object like below:-

  constructor(props) {
    super(props);

    this.state = {
      getUserData: {},
    };
  } 

Now When your component mounts first time, getUserData will be blank object so when it try to access user_profile from blank object it will return undefined.

To solve this issue you can use optional chaining like below:-

<h5>{this.state.getUserData?.user_profile?.company?.company_name}</h5>

Upvotes: 1

Related Questions