Home > Enterprise >  React Cannot read properties of undefined (reading 'map')
React Cannot read properties of undefined (reading 'map')

Time:12-02

I am getting this error: "TypeError: Cannot read properties of undefined (reading 'map')" in my code, and I'm not sure why at all, I seem to have no errors in the code IDE itself, and I have checked through this many times Thank you for reading!

    const { user } = useAuth0();
    const [{songs, setSongs}] = useState([])

    useEffect(() => {
        if (user) {
            const requestOptions = {
                method: 'GET'
            };
            let url = 'https://present-deck.com/getsongs/'   user.sub
            fetch(url, requestOptions)
            .then(response => {
                return response.json();
            }).then(jsonResponse => {
                setSongs(jsonResponse)
            }).catch (error => {
                console.log(error);
            }) 
            console.log(songs)
        }
    }, [user])
    return (
        <>
        <ul>
            {songs.map((el) => (
                <li key={el} className="tailwindCssStuff"
                onClick={ () => {if (listedSongs.indexOf(el.title) === -1){
                    addListedSongs(listedSongs.concat(el.title))}}}>
                {el.title}</li>
            ))}
        </ul>
        </>
    )
}```

CodePudding user response:

const [{songs, setSongs}] = useState([])

should be const [songs, setSongs] = useState([])

CodePudding user response:

You have an unnecessary set of braces when de-structuring your state, which is resulting in your songs and setSongs being undefined.

Instead you want:

const [songs, setSongs] = useState([])
  • Related