I started converting my code to TypeScript but for some reason i cannot get to work.
The code does not give an error but it does not show the list.
type song = {
id: number,
artist: string,
titre: string;
links: string[] | number,
has_youtube_link: number,
has_picture: number,
hour: number,
minutes: number,
votes: number
}
interface Songs {
listOfSongs: song[]
}
const LastPlayedSongs: React.FC = () => {
const [songs, setSong] = useState<Songs | null>(null)
useEffect(() => {
fetch("APILink")
.then(response => response.json())
.then(response => {
setSong(response);
})
.catch(err => {
console.log(err);
});
}, [])
return (
<>
<ul>
{songs?.listOfSongs?.map((song) => (
<li key={song.id}>{song.titre}, {song.id}</li>
))}
</ul>
</>
);
}
If i use the song type directly instead of the Songs interface it works.
type song = {
id: number,
artist: string,
titre: string;
links: string[] | number,
has_youtube_link: number,
has_picture: number,
hour: number,
minutes: number,
votes: number
}
const LastPlayedSongs: React.FC = () => {
const [songs, setSong] = useState<song[] | null>(null)
useEffect(() => {
fetch("APILink")
.then(response => response.json())
.then(response => {
setSong(response);
})
.catch(err => {
console.log(err);
});
}, [])
return (
<>
<ul>
{songs?.map((song) => (
<li key={song.id}>{song.titre}, {song.id}</li>
))}
</ul>
</>
);
}
Does anyone knows how to make the first one wor or give some informations on what I am doing wrong.
Kind regards
You should eighther change your interface or set the state correctly to the object attribute.
type Songs = song []
thenuseState<Songs>([])
and thensetSong(response)
setSong({listOfSongs:response})
preferably don't make your state nullable, it is an array and initially can be an empty array