Troubles with array of objects inside my interface in TypeScript & Reactjs

505 views Asked by At

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

1

There are 1 answers

2
Amir-Mousavi On BEST ANSWER

You should eighther change your interface or set the state correctly to the object attribute.

  1. type Songs = song [] then useState<Songs>([]) and then setSong(response)
  2. what you currently have as interface then setSong({listOfSongs:response})

preferably don't make your state nullable, it is an array and initially can be an empty array