Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch and display json object from api in the project

import React, { useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";

export default function Aapi() {
  const [record, setRecords] = useState([]);
  var arr = [];
  useEffect(() => {
    fetch("https://ipinfo.io/json?token=93ogbcdhee0a74")
      .then((response) => response.json())
      .then((jsonResponse) => {
        arr.push(jsonResponse.city, jsonResponse.country);
        setRecords(arr);
        console.log(arr);
      });
  }, []);
  return (
    <>
      {Array.isArray(record) ? (
        record.map((records) => {
          return (
            <div key={uuidv4()}>
              <p>{records.city + "+ "}</p>
            </div>
          );
        })
      ) : (
        <p>null</p>
      )}
    </>
  );
}


Here is the code ,
I am using an API from which I am fetching the json object and converting it array so as to use map function to display in my project as map function works on the array elements. It successfully gives output in console as array but I am not able to display it on the project.
If there is any error please mention it or any alternative to display json object (not array) in projects.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are trying to map over an object, but the map function works on arrays, not objects. To display the data from the JSON object in your project, you can iterate over the object’s keys and values using Object.entries() and render them accordingly. Here’s an updated version of your component:

import React, { useEffect, useState } from "react";

export default function Aapi() {
  const [record, setRecords] = useState({});
  
  useEffect(() => {
    fetch("https://ipinfo.io/json?token=93ogbcdhee0a74")
      .then((response) => response.json())
      .then((jsonResponse) => {
        setRecords(jsonResponse);
        console.log(jsonResponse);
      });
  }, []);
  
  return (
    <>
      {Object.entries(record).length > 0 ? (
        <div>
          {Object.entries(record).map(([key, value]) => (
            <div key={key}>
              <p>{`${key}: ${value}`}</p>
            </div>
          ))}
        </div>
      ) : (
        <p>null</p>
      )}
    </>
  );
}

We initialize record as an empty object because the API response is an object, not an array. Inside the useEffect, we set the record state to the JSON response object directly. We use Object.entries(record) to iterate over the object’s key-value pairs and render them as <p> elements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading