Loading component in React not displaying while page is loading
I have a page that displays media from an API and created a Loading component to show a loading state while the API is loading. I'm able to get the loading component to show on a page that displays 1 item from the API, but on a another page where I'm loading multiple items it does not display. How would I go about creating a loading component for this?
export default function Explore() {
const [media, setMedia] = useState([]);
const [faves, setFaves] = useState([]);
useEffect(() => {
const abortController = new AbortController();
const opts = { signal: abortController.signal };
fetch(`https://api.nasa.gov/planetary/apod?api_key=${apiKey}&count=15`, opts)
.then((response) => response.json())
.then((data) => setMedia(data))
.catch((error) => console.log(error.message));
return () => abortController.abort();
}, []);
if (!media) return <Loading />;
const addFave = (fave) => {
const isAlreadyStarred = faves.filter(
item => item === fave
)
if (isAlreadyStarred.length > 0) {
return;
}
const newFavesList = [...faves, fave];
setFaves(newFavesList);
// saveToLocalStorage(newFavesList);
};
const removeFave = (e) => {
const url = e.target.getAttribute("url")
setFaves(faves.filter(favorite => favorite.url !== url));
};
return (...)
Loading component displays when fetching API a different way:
export default function Today() {
const [mediaData, setMediaData] = useState(null);
useEffect(() => {
fetchMedia();
async function fetchMedia() {
const res = await fetch(`https://api.nasa.gov/planetary/apod?api_key=${apiKey}`);
const data = await res.json();
setMediaData(data);
console.log(data);
}
}, []);
if (!mediaData) return <Loading />;
return (...)
Solution 1:
![]
is falsy. If you change it to something like
if (!media.length) return <Loading />;
that should work for you