Home > Software design >  reading output of API in react
reading output of API in react

Time:02-03

I am calling one API in react. for that I am getting output in below format.

{
    "first_page_uri": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages.json?PageSize=50&Page=0",
    "end": 49,
    "previous_page_uri": null,
    "messages": [
        {
            "body": "",
            "num_segments": "1",
            "direction": "outbound-api",
            "from": " 12058557185",
            "date_updated": "Mon, 29 Aug 2022 09:07:47  0000",
            "price": "-0.04410",
            "error_message": null,
            "uri": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx.json",
            "account_sid": "xxxxxxxxxxxxxxxxx",
            "num_media": "0",
            "to": " 919823772514",
            "date_created": "Mon, 29 Aug 2022 09:07:42  0000",
            "status": "delivered",
            "sid": "SMfa2e62cf71761db915657b02605bc689",
            "date_sent": "Mon, 29 Aug 2022 09:07:43  0000",
            "messaging_service_sid": "xxxxxxxxxxxxxxxxx",
            "error_code": null,
            "price_unit": "USD",
            "api_version": "2010-04-01",
            "subresource_uris": {
                "media": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Media.json",
                "feedback": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Feedback.json"
            }
        },
        {
            "body": "",
            "num_segments": "1",
            "direction": "outbound-api",
            "from": " 12058557185",
            "date_updated": "Mon, 29 Aug 2022 05:51:57  0000",
            "price": "-0.04410",
            "error_message": null,
            "uri": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx.json",
            "account_sid": "AC9ab9e25e89eaa96c474e9a39867bb2f3",
            "num_media": "0",
            "to": " 919823772514",
            "date_created": "Mon, 29 Aug 2022 05:51:47  0000",
            "status": "delivered",
            "sid": "SM5237fb62ff472b5e124fdd2ea073fffe",
            "date_sent": "Mon, 29 Aug 2022 05:51:47  0000",
            "messaging_service_sid": "MG00d095919337aa95aeb5b74c8f0bd81c",
            "error_code": null,
            "price_unit": "USD",
            "api_version": "2010-04-01",
            "subresource_uris": {
                "media": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Media.json",
                "feedback": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Feedback.json"
            }
        },
        {
            "body": "",
            "num_segments": "1",
            "direction": "outbound-api",
            "from": " 12058557185",
            "date_updated": "Mon, 29 Aug 2022 05:24:09  0000",
            "price": "-0.04410",
            "error_message": null,
            "uri": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx.json",
            "account_sid": "xxxxxxxxxxxxxxxxx",
            "num_media": "0",
            "to": " 919727930925",
            "date_created": "Mon, 29 Aug 2022 05:24:05  0000",
            "status": "delivered",
            "sid": "SM1528c06455368cfb7e00ab8283ed773c",
            "date_sent": "Mon, 29 Aug 2022 05:24:05  0000",
            "messaging_service_sid": "MG00d095919337aa95aeb5b74c8f0bd81c",
            "error_code": null,
            "price_unit": "USD",
            "api_version": "2010-04-01",
            "subresource_uris": {
                "media": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Media.json",
                "feedback": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Feedback.json"
            }
        }

,`

I want to read differnet fields on it to perform some operation in UI. for example I want to read status, body, from etc.

alert("Message is:" JSON.stringify(response.data))

this line is giving output of an API properly. but when I write

alert("Message is:" JSON.stringify(response.data.messages))
alert("Message is:" JSON.stringify(response.data.messages.from))
alert("Message is:" JSON.stringify(response.data.messages[0].from))

I am getting undefined and exceptions. my goal is to print the value in UI for specific status.

Can somrebody help me on that.

I tried lot of options and googling but nothing helped. I am new to javascript

CodePudding user response:

The JSON.stringify() method is used to convert a JavaScript object or value to a JSON string. To convert a JSON string back to a JavaScript object, you can use the JSON.parse() method. Once you've parsed the JSON string, you can access and manipulate its properties just like you would with any other JavaScript object.

if the response is a JavaScript object, you can access its properties and values directly. You can use the dot notation to access the properties of the object, In the example you provided.

alert("Message is:" response.data.messages[0].from)

CodePudding user response:

You should use JSON.parse instead of JSON.stringify.

JSON.parse convert json string to js object and JSON.stringify do the reversed job.

So, your code should look like:

alert("Message is:" JSON.parse(response.data.messages))
alert("Message is:" JSON.parse(response.data.messages.from))
alert("Message is:" JSON.parse(response.data.messages[0].from))

One more note here, to access nested property in JS object and avoid access anything from undefined, you should use JS optional chaining feature like below:

alert("Message is:" JSON.parse(response?.data?.messages))
alert("Message is:" JSON.parse(response?.data?.messages?.from))

The ? take care of null check for you.

CodePudding user response:

Try this, but first replace this api with your api

import React from 'react';
import './style.css';

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: null,
    };
  }

  componentDidMount() {
    fetch('https://reqres.in/api/users') // replace this api with your api
    .then((response) => {
      
      response.json().then((result) => {
        console.warn(result.data);
        this.setState({ data: result.data });
      });
    });
  }
  render() {
    return (
      <div>
        {this.state.data
          ? this.state.data.map((item, i) => (
              <div>
                <p>
                  {i} --- {item.body} {item.from}{' '}
                </p>
              </div>
            ))
          : null}
      </div>
    );
  }
}

export default App;

CodePudding user response:

Now this is a relatively complex topic for a beginner, let's start at the beginning.

Objects

What you get from the api request is an object. An object has properties, like first_page_uri, end, and so on. In JSON that will look like this:

{
  "first_page_uri": "this is a value",
  "end": 42
}

If you parsed the json string to a javascript object, like I assume you already have. You will have your object handle / variable. In your case that should be response.data.

With that handle you are able to get those object properties by accessing them using . after the handle and their name. For example you can display first_page_uri by writing this:

alert(response.data.first_page_uri)

Lists (Arrays)

Inside the response, there is a list. A list in JSON is represented like this:

"my_list": [
  "a",
  "b",
  "c"
]

In this case the list has 3 values containing the strings a, b and c.

If you have a list in javascript, to get any of the values you can do the following:

alert(my_list[index])

Where my_list is the list and index is a value between 0 for the first element a and in this case 2 for the last element c.

Caution: we start counting from 0.

To show b in an alert we would write:

alert(my_list[1])

Combination of both

The attribute messages in your response is such a list. It contains not strings, but objects. Like so:

{
  "messages": [
    {
      "body": "this is a message"
    },
    {
      "body": "this is another message"
    }
  ]
}

In this case if you wanted to retrieve the first message body and alert it, you would need to combine both patterns from above:

alert(response.body.messages[0].body)

I am assuming your object is in response.body. We are accessing messages and then selecting the first with [0] and then selecting body from that message.

Possible solutions

The problems you are encountering are probably the following: alert is only able to show simple data types like string, number and so on. So trying to print out a whole list for example will not work.

I assume your other code is correct by the fact that you say that:

alert("Message is:" JSON.stringify(response.data))

works.

All you would need to do to fix your code, is to remove the second line:

alert("Message is:" JSON.parse(response.data.messages.from))

.from makes js try to access a property of a list. As discussed above. Objects have properties, lists do not. So react throws an exception.

Your other lines:

alert("Message is:" JSON.stringify(response.data.messages))
alert("Message is:" JSON.stringify(response.data.messages[0].from))

should work. As they seem to be correct.

The UI

Now regarding the UI part you are talking about...

If you are inside a react component, which would probably look somewhat like this:

const ComponentName = (/* maybe stuff here */) => {
  // maybe a lot of stuff here
  return (
    /* this is the interesting part */
  )
}

You want to be looking for the return part. Inside there you can write HTML-like code. A simple UI output to show all messages would be:

const ComponentName = () => {
  // here you do your api stuff so you get the response variable
  const response;
  return (
    <>
      <h1>All messages:</h1>
      {
        response.body.messages.map((message) => (
          <p>{message.body}</p>
        ))
      }
    </>
  )
}

I did use a new thing here: the map function on a list. I put it in the recommended reading section below.

The part in the middle:

<h1>All messages:</h1>
{
   response.body.messages.map((message) => (
     <p>{message.body}</p>
   ))
}

Is the important part. You can more or less put it anywhere in the return statement and it should show up.

Recommended reading

To learn more you probably want to look up the following things:

My thoughts (please ignore if unsuited)

If you are very new to javascript and this is a free time project. I would recommend taking it a step slower. While I do not want to discourage you from continuing with what you are doing, I assume that you can learn quicker and more effectively by stepping back and for example start with a HTML, CSS and JS only project without libraries. That should make you more comfortable in the concepts involved before jumping into a more complicated project. Especially if you do not have much or any experience with other languages.

A good start for that would be this project. It does include jQuery, but you do not need to use it.

I wish you the best of luck going forward!

  • Related