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
import './App.css'; import './Dog.js'; import FetchAPI from './FetchAPI'; function DogApp() { return ( <div className="DogApp"> <FetchAPI /> </div> ); } export default DogApp;
FetchAPI.js
import React, { useState, useEffect } from 'react' const FetchAPI = () => { const [data, setData] = useState([]); const apiGet = () => { const API_KEY = ""; fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`) .then((response) => response.json()) .then((json) => { console.log(json); setData(json); }); }; useEffect(() => { //call data when pagee refreshes/initially loads apiGet(); }, []); return ( <div> {data.map((item) => ( <img src={item.url}></img> ))} My API <button onClick={apiGet}>Fetch API</button> <pre>{JSON.stringify(data, null, 2)}</pre> <br /> </div> ) } export default FetchAPI;
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:
const apiGet = () => { const API_KEY = ""; fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`) .then((response) => response.json()) .then((json) => { console.log(json); setData([...data,json]); // if json is single object // setData([...data,...json]); // if json is array of one object then you should use this line }); };