Skip to content
Advertisement

TypeError: Cannot read property ‘map’ of undefined. React

I am new to React and I am having a problem. How to iterate over an array in an array? When trying to iterate over an array using the map() method, an error occurs

my code:

import React, {useState, useEffect} from 'react';

import Header from '../modules/header/header';
import Footer from '../modules/footer/footer';

import './pages.scss';

function PageWorksItem({ match, location }) {

    const { params: { id } } = match;
    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [works, setItems] = useState([]);

    useEffect(() => {
        let cleanupFunction = false;
        fetch(`http://localhost:3001/works/${id}`)
            .then(res => res.json())
            .then(
                (result) => {
                    console.log(result);
                    setIsLoaded(true);
                    if(!cleanupFunction) setItems(result);
                },
                (error) => {
                    setIsLoaded(true);
                    setError(error);
                }
            )
            return () => cleanupFunction = true;
        }, [])

        if (error) {
            return <div className="works error">Error: {error.message}</div>;
        } else if (!isLoaded) {
            return <div className="works loading">. . .</div>;
        } else {
            return (
                <>
                    <Header />
                    <div className="works item">
                        {works.tags.map(item => (
                            <li>{item}</li>
                        ))}
                    </div>
                    <Footer />
                </>
            );
        }
    }

export default PageWorksItem;

JSON fragment:

{
    "works": [
        { 
            "id": 1, 
            "name": "21 one line SPA images",
            "cat": "Illustrations",
            "tags": ["one", "two", "free"]
        }
    ]
}

if you specify {works.tags} or with an index {works.tags[0]} – everything works, but if you iterate over the array, an error occurs.

Advertisement

Answer

You are using works.tag.map. But the initialization value of works is an empty array []: const [works, setItems] = useState([]);. So works.tag is undefined and this error occurred. You can fix this issue by add optional chaining like this:

{works.tags?.map((item, index)=> (
   <li key={index}>{item}</li>
))}

Note: You need to add unique key in child componet when using map

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement