1

How do I render an object that I've fetched in React?

Here is my code:

const PrayerTimesByCity = () => {
  // Initiate array for fetching data from AlAdhan API
  const [data, setPrayerTimes] = useState({});

  useEffect(() => {
    fetch(
      "http://api.aladhan.com/v1/timingsByCity?city=Helsingborg&country=Sweden&method=0"
    )
      .then((resp) => resp.json())
      .then((data) => setPrayerTimes(data));
  }, []);

  console.log(data);

  return <div> // Here is where I want my objects to return </div>;
};

Here is what the fetched data returns:

{
  "code": 200,
  "status": "OK",
  "data": {
    "timings": {
      "Fajr": "06:42",
      "Sunrise": "09:00",
      "Dhuhr": "12:13",
      "Asr": "13:17",
      "Sunset": "15:27",
      "Maghrib": "16:00",
      "Isha": "17:29",
      "Imsak": "06:32",
      "Midnight": "00:13"
    }
}

I want to extract "data" and then "timings" and then each respective item and its key. How do I do this in my return statement in my component?

Thanks for any answer in advance

2 Answers2

1

By using Object.keys(data):

const PrayerTimesByCity = () => {
  // Initiate array for fetching data from AlAdhan API
  const [data, setPrayerTimes] = useState({});

  useEffect(() => {
    fetch(
      "http://api.aladhan.com/v1/timingsByCity?city=Helsingborg&country=Sweden&method=0"
    )
      .then((resp) => resp.json())
      .then((data) => setPrayerTimes(data));
  }, []);

  console.log(data);

  return (
  <div>
  {Object.keys(data.timings).map((key, index) =>
    <span key={index}>{key}:{data.timings[key]}</span>
  )}
  </div>
  );
};

Another solution for one time transforming from object to array would be:

const PrayerTimesByCity = () => {
  // Initiate array for fetching data from AlAdhan API
  const [data, setPrayerTimes] = useState([]);

  useEffect(() => {
    fetch(
      "http://api.aladhan.com/v1/timingsByCity?city=Helsingborg&country=Sweden&method=0"
    )
      .then((resp) => resp.json())
      .then((data) => setPrayerTimes(Object.entries(data.data.timings)));
  }, []);

  console.log(data);

  return (
  <div>
  {data.map(([key, value], index) =>
    <span key={index}>{key}:{value}</span>
  )}
  </div>
  );
};
Heartbit
  • 1,698
  • 2
  • 14
  • 26
1

You should return {data.data.timings.Fajr},{data.data.timings.Sunrise},... if your component directly displays the data. If your component only returns the data, that needs to be displayed in another component, you should type: return data.data.timings;

Chita
  • 11
  • 2