Reputation: 174
What i'm trying to do: Have some practice with fetching data in react, and i used a covid19 api with number of cases etc...
Here's the code :
import { useState, useEffect } from "react";
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios("api_here",);
setData([result.data]);
};
fetchData();
}, [])
console.log(data);//i have a screen-shot below for the output
return (
<ul>
{data.map((items, index) => (
<li key={index}>{JSON.stringify(items)}</li>
//<li key={index}>{items}</li> This doesn't work
))}
</ul>
)} export default Home;
The problem is that the data is an array of 1 element, image here:
And data.map is iterating only on json[0] but i need to iterate over every country from the json.
I tried doing something like :
setData([result.data][0])
//or
data[0].map......
But doesn't work
Upvotes: 0
Views: 698
Reputation: 5094
You can Convert the Object of Objects to Array of Objects.
import { useState, useEffect } from "react";
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios("api_here",);
let res = [result.data];
res = Object.entries(res[0]).map((e) => ( { [e[0]]: e[1] } ));
setData(res);
};
fetchData();
}, [])
console.log(data);
return (
<ul>
{data.map((items, index) => (
<li key={index}>{JSON.stringify(items)}</li>
//<li key={index}>{items}</li> This doesn't work
))}
</ul>
)} export default Home;
Upvotes: 0
Reputation: 3337
Your data is a map of key -> value so to iterate over all countries (keys).
<ul>
{Object.keys(data).map((key, index) => (
<li key={index}>{JSON.stringify(data[key])}</li>
))}
</ul>
Upvotes: 2