Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering JSON API in react Using map method

I am having difficulty with the syntax and the structure of JSON objects/arrays and map method. I am new to React and on an initial stage of learning.

This is the JSON file code I pasted below:

[
  {
    "cloud":"Asia",
    "availability":{
      "last15Min":"100%",
      "last24Hour":"100%"
    },
    "data_centers":[
      {
        "title":"Bombay",
        "availability":{
          "last15Min":"100%",
          "last24Hour":"100%"
        }
      },
      {
        "title":"Bombay1",
        "availability":{
          "last15Min":"100%",
          "last24Hour":"100%"
        }
      }
    ]
  },
  {
    "cloud":"Europe",
    "availability":{
      "last15Min":"100%",
      "last24Hour":"100%"
    },
    "data_centers":[
      {
        "title": "Bombay",
        "availability": {
          "last15Min": "100%",
          "last24Hour": "100%"
        }
      },
      {
        "title":"Bombay1",
        "availability":{
          "last15Min":"100%",
          "last24Hour":"100%"
        }
      }
    ]
  }
]

Here is my code so far: I want to render each field using map method. What is the correct method to do that?

In componentDidMount I am getting the response in console.log http://prntscr.com/i09rqt

  constructor(props) {
    super(props)
    this.state = {
      clouds:[]
    }
  }

  componentDidMount() {
    var url="<api url>";
    fetch(url)
      .then(response => {
        return response.json();
      }).then(d => {
          let clouds = d.map((cloudData)=>{
            return(
              <div>{cloudData}</div>
            )
        })
        this.setState({clouds: clouds});
          console.log("state", this.state.clouds)
    })
  }

  render() {
    return (
      <div>
        {
          this.state.clouds.map((cloud =>
            <th key="">
                {cloud}
            </th>
          ))
        }
      </div>
    );
  }
like image 617
Bhawna Avatar asked Jan 14 '18 13:01

Bhawna


People also ask

Can you map a JSON React?

With the Ignite UI for React map, you can plot geographic data loaded from various file types. For example, you can load geographic locations from JavaScript Object Notation (JSON) file.

How display JSON data from API in React?

Fetching Data from API js import { useEffect } from "react"; import "./App. css"; function App() { useEffect(() => { fetch(`https://dummyjson.com/products`) . then((response) => response. json()) .

How do you render a list from a JSON API in React?

In the return statement of the RenderResult function, let's place {apiResponse} between <ul> elements, so we can render the array of lists. return( <div> <h1>React App</h1> <ul>{apiResponse}</ul> </div> ); As a result, this will render our list of Kintone records as unordered lists.

Does map work on JSON?

You can map the data types of your business model into JSON by using the examples. Data in JSON is either an object or an array. A JSON object is an unordered collection of names and values. A JSON array is an ordered sequence of values.


2 Answers

Previous answer is almost correct, fixing the fetch correctly will solve the problem.

componentDidMount() {
  var url = "https://demo8192935.mockable.io/mockApi";
  fetch(url)
    .then(response => {
      return response.json();
    })
    .then(d => {
      this.setState({ clouds: d });
      console.log("state", this.state.clouds)
    })
    .catch(error => console.log(error))
}

render() {
  return (
    <div>
      {
        this.state.clouds.map(((cloud, index) =>
          <th key={`${cloud.cloud}${index}`}>
            <div>
              <div>
                {cloud.cloud}
                <div>
                  {
                    cloud.data_centers.map(d => (
                      <div>
                        {d.title}
                      </div>
                    ))
                  }
                </div>
              </div>
            </div>
          </th>
        ))
      }
    </div>
  );
}
like image 124
Swapnil Avatar answered Oct 20 '22 21:10

Swapnil


There is no need to return a html element inside componentDidMount.

Try this:

constructor(props) {
    super(props)
    this.state = {
        clouds: []
    }
}

componentDidMount() {
    var url = "http://trust.zscaler.com.test/sample-api/third-party-monitoring/availability.json";
    fetch(url)
        .then(response => {
            this.setState({ clouds : response })
        }).catch(error => {
            console.log(error)
        })
}

render() {
    if (this.state.clouds && this.state.clouds.length > 0) {
        return (
            <div>
                {
                    this.state.clouds.map((items =>
                        <th key="">
                            {items.cloud}
                        </th>
                    ))
                }
            </div>
        );
    }

    return null;

}

Hope this helps you.

like image 39
Syed Avatar answered Oct 20 '22 20:10

Syed