I essentially want the page to initially load with a total of 9 images from this api. If I add another image, and retrieve it on page load, it displays a duplicate, and only when I fetch the api again, does the api make a random call, and load a new image.
Right now, on page load, one image is displayed, with text retrieved from the json object and stored in a parapragh.
My end goal is to have the page load with 9 different images of the dogs, and have a button that fetches the json data for each unique dog, so all images will be linked to a unique button.
I’m having trouble wrapping my head around a few of the concepts, and React is very new to me.
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([...data,json]); if json is single object
setData([...data, ...json]); // if json is array of one object then use this line
});
};
useEffect(() => { //call data when pagee refreshes/initially loads
apiGet();
}, []);
return (
<div>
{data.map((item) => (
<div class="dog">
<img src={item.url}></img>
<button onClick={apiGet}>Fetch API</button>
</div>
))}
{data.map((item) => (
<p>{JSON.stringify(item.breeds)}</p>
))}
{/*<pre>{JSON.stringify(data, null, 2)}</pre> */}
<br />
</div>
)
}
export default FetchAPI;