useEffect keeps returning null data. Here's the code in my TypeScript app:
import TracksListing from './TracksListing';
import axios, { AxiosResponse } from 'axios'
import { useEffect, useState } from "react";
interface AlbumDetailsProps {
id?: string
}
const AlbumDetails: React.FC<AlbumDetailsProps> = ({ id }) => {
const [albums, setAlbums] = useState<AxiosResponse | null | any | void>([]);
useEffect(() => {
const fetchAlbum = async () => {
try {
const albumData = await axios.get(`http://localhost:8080/api/v1/album/${id}`);
setAlbums(albumData.data);
console.log(albums)
console.log("this is the ID:", id)
} catch (error) {
console.log(error);
}
}
fetchAlbum();
}, [])
return (
<>
{albums && albums.map((album: any) => (
album.tracks.trackTitles.map((title: string, index: number) => (
<TracksListing number={index + 1} title={title} artist={album.artist} length={album.tracks.trackLengths[index]} />
))
))}
</>
)
If I go to localhost:8080 with any IDs in that address then the data displays there, so I know it can be read for my webpage if I could figure out what the issue is. I'm also getting "Uncaught TypeError: albums.map is not a function" errors that I assume are due to the mapping of the data not working due to the data being null.
What confuses me is I had it semi-working earlier so that when I'd load the page and nothing displays, then go to VS Code and press Ctrl+S, suddenly it'd show the data was obtained, although it still wouldn't render the data on to the page.
I've tried setting the useEffect dependency to the albums state variable or the id and it doesn't help. I have this exact same useEffect to fetch a different set of data in another component and for some reason, it works there. I don't get what makes this case different.