I tried destructuring only the props that I wanted from the state used to store the JSON data, and then use a state for a counter value so I can have some next/prev buttons and display only 1 image at a time (using as the index for the array, the counter value, therefore it would be 1 item at a time and the next/prev buttons would incremend/decrement by 1 ). I have done this on a previous project and it worked but for some reason now it does not.
Any ideas why not working, or perhaps some insight for a different approach ?
import React, { useEffect, useState } from "react"; import Loading from "./loading";
const key = "#!$!#$!#$#!$!#$#!#$!$#!$!#$!$#!$";
const url = `https://api.unsplash.com/photos/?client_id=${key}`;
console.log(url);
//main Component
function App() {
//states
const [loading, setLoading] = useState(true);
const [images, setImages] = useState([]);
const [counter, setCounter] = useState(0);
const fetchImages = async () => {
setLoading(true);
try {
const response = await fetch(url);
const image = await response.json();
setLoading(false);
setImages(image);
} catch (error) {
console.log(error);
setLoading(true);
}
};
useEffect(() => {
fetchImages();
}, [url]);
//loading
if (loading) {
return (
<main>
<Loading></Loading>
</main>
);
}
//primary return
const { id, created_at, description, urls } = images[counter];
return (
<main>
{urls.map((image) => {
return <img src={image.full}></img>;
})}
</main>
);
}
export default App;