Search code examples
javascriptreactjsjavascript-objects

Unable to display data received as object from backend ,


I am fetching data from the backend, it has a particular sub-part called headers which further has an additional name:value pairs . like this - data : { headers : {name:"Nishant", value:"random" } }, I want to display all the fields inside a modal , When I try to use Object.keys() , this error is thrown - "cannot convert undefined or null to object".

render(){
 return(
   let request_data = this.props.head // has the entire data
   let data = request_data.headers //contains the headers section to be displayed.
   <div className="modal-body">
            <div className="row">
              <div className="col-lg-6">
              {
                <div>
                  {// want to display the headers data here }
                  { (request_data.body !== '') ? <div>Body : {request_data.body}</div> : ''}
                </div>
              }
              </div>
           </div>
    </div>
 );
}

Not Sure what to do as I tried Using Object.keys but an error is thrown saying "cannot convert undefined or null to object". Although by Using JSON.stringify() I am getting the result but not in the expected look and feel.


Solution

  • Check header is not undefined before get values;

                <div className="col-lg-6">
                    {
                        <div>
                            {request_data.header ? Object.values(request_data.header).map(value => value) : null}
    
                            {(request_data.body !== '') ? <div>Body : {request_data.body}</div> : ''}
                        </div>
                    }
                </div>