I try to fetch some data from an API. The API is formatted like this:
JavaScript
x
17
17
1
[
2
{
3
"1": {
4
"appid": 1,
5
"name": "bmw"
6
},
7
"2": {
8
"appid": 2,
9
"name": "mercedes"
10
},
11
"3": {
12
"appid": 3,
13
"name": "tesla"
14
}
15
}
16
]
17
And in react my app.js looks like this:
JavaScript
1
37
37
1
import React, { useState, useEffect } from "react";
2
import axios from "axios";
3
import ItemsGrid from "./components/items/ItemsGrid";
4
5
function App() {
6
const [items, setItems] = useState([]);
7
const [isLoading, setIsLoading] = useState(true);
8
9
useEffect(() => {
10
const fetchItems = async () => {
11
const result = await axios({
12
url: "http://localhost:3013/items",
13
method: "get",
14
timeout: 8000,
15
headers: {
16
"Content-Type": "application/json",
17
},
18
});
19
20
console.log(result.data);
21
setItems(result.data);
22
setIsLoading(false);
23
};
24
25
fetchItems();
26
}, []);
27
28
return (
29
<div className="App">
30
<ItemsGrid isLoading={isLoading} items={items} />
31
<h1>Hello</h1>
32
</div>
33
);
34
}
35
36
export default App;
37
And the ItemsGrid:
JavaScript
1
16
16
1
import React from "react";
2
3
const ItemsGrid = ({ items, isLoading }) => {
4
return isLoading ? (
5
<h1>Loading</h1>
6
) : (
7
<div>
8
{items.map((item) => (
9
<h1 key={item.appid}>{item.name}</h1>
10
))}
11
</div>
12
);
13
};
14
15
export default ItemsGrid;
16
So nothing is to see beacause I don’t know how to access the array. In the console log I see there is something:
JavaScript
1
5
1
[{…}]
2
0: {1: {…}, 2: {…}, 3: {…}}
3
length: 1
4
__proto__: Array(0)
5
Anyone know how to show the names via mapping?
Advertisement
Answer
If you want to turn the array with an object into a regular array you can use Object.values on the first element of the array:
JavaScript
1
18
18
1
useEffect(() => {
2
const fetchItems = async () => {
3
const result = await axios({
4
url: "http://localhost:3013/items",
5
method: "get",
6
timeout: 8000,
7
headers: {
8
"Content-Type": "application/json",
9
},
10
});
11
12
setItems(Object.values(result.data[0]));
13
setIsLoading(false);
14
};
15
16
fetchItems();
17
}, []);
18