I’ve managed to connect to an api, which returns images of dogs. However, I’m stuck on how to map more than one image, without repeating code. I essentially want to display a grid with(lets say 9) images, all with different dog images from this api.
At the moment, it displays one image with a json object mapped out underneath it.
App.js
JavaScript
x
17
17
1
import './App.css';
2
import './Dog.js';
3
import FetchAPI from './FetchAPI';
4
5
6
7
function DogApp() {
8
9
return (
10
<div className="DogApp">
11
<FetchAPI />
12
</div>
13
);
14
}
15
16
export default DogApp;
17
FetchAPI.js
JavaScript
1
43
43
1
import React, { useState, useEffect } from 'react'
2
3
const FetchAPI = () => {
4
5
const [data, setData] = useState([]);
6
7
const apiGet = () => {
8
const API_KEY = "";
9
fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
10
.then((response) => response.json())
11
.then((json) => {
12
console.log(json);
13
setData(json);
14
});
15
};
16
17
useEffect(() => { //call data when pagee refreshes/initially loads
18
apiGet();
19
}, []);
20
21
22
return (
23
24
<div>
25
{data.map((item) => (
26
<img src={item.url}></img>
27
))}
28
29
My API
30
<button onClick={apiGet}>Fetch API</button>
31
<pre>{JSON.stringify(data, null, 2)}</pre>
32
<br />
33
34
35
</div>
36
37
38
39
)
40
}
41
42
export default FetchAPI;
43
Advertisement
Answer
If your API returns single image at a time and you want more images on button click then you should have to append the new image into the array like:
JavaScript
1
11
11
1
const apiGet = () => {
2
const API_KEY = "";
3
fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
4
.then((response) => response.json())
5
.then((json) => {
6
console.log(json);
7
setData([data,json]); // if json is single object
8
// setData([...data,...json]); // if json is array of one object then you should use this line
9
});
10
};
11