nishant
nishant

Reputation: 117

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.

Upvotes: 0

Views: 596

Answers (3)

Sree
Sree

Reputation: 1758

If a valid response is received. For Example:

{
"data": {
    "headers": {
        "name": "Nishant",
        "value": "random"
    }
}
}

var responseData = JSON.parse('{ "data": { "headers": { name: "Nishant", value: "random" } } }')

The first option will display the value in data object and the second will display the value inside the headers object.

<pre>responseData.data</pre> 
<pre>responseData.data.headers</pre> 

Upvotes: 1

aseferov
aseferov

Reputation: 6393

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>

Upvotes: 1

Prithwee Das
Prithwee Das

Reputation: 5226

render the text in a <pre> tag and use JSON.stringify

<pre>{JSON.stringify(request_data.body,null,2)}</pre>

Upvotes: 1

Related Questions