Arnas Dičkus
Arnas Dičkus

Reputation: 677

Cannot read property 'map' of undefined error. React Typescript

I have this code here. I keep getting an error:

TypeError: Cannot read property 'map' of undefined.

Here are a few facts:

  1. I get data from the front-end javascript file. So there shouldn't be any async problems.
  2. singleCategory.title Always displays correctly.
  3. The error happens only if I refresh the page. If I comment out the map code and add code. So that React could inject it without refresh. It works. I only get an error if I refresh the page or try to navigate to it.enter image description here

Why does singleCategory.title display correctly but using map is undefined? Also map is undefined only on refresh. If code is injected it works properly.

const CoursesCategories: React.FC = () => {
    const [singleCategory, setSingleCategory] = useState<CategoriesInterface>([] as any);

    useEffect(() => {
        const fullUrl = window.location.href;
        const segments = new URL(fullUrl).pathname.split('/');
        const id = segments.pop() || segments.pop();

        for (let category of Categories ) {
            if (category.url === id) {
                setSingleCategory(category);
                console.log(singleCategory)
            }
        }
    }, [singleCategory]);


    return (
        <div>
            {
                singleCategory.courses !== [] ? (
                    <div>
                        <CategoryTitle title={singleCategory.title} />

                        <div className={wrapper.headerWrapper}>
                            {
                                singleCategory.courses.map((course: CoursesInterface) => (
                                    <h2 key={course.id}>{course.title}</h2>
                                    )
                                )
                            }
                        </div>
                    </div>
                ) : ''
            }

        </div>
    )
}

Edit 1. If I write like this I get.

Cannot read property 'length' of undefined

{ singleCategory.courses.length > 0 && singleCategory.courses.map((course: CoursesInterface) => (
                                    <h2 key={course.id}>{course.title}</h2>
                                )
                            )}

Upvotes: 1

Views: 326

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Since you're using typescript you could use optional chaining :

{ singleCategory.courses?.length > 0
    && singleCategory.courses?.map((course: CoursesInterface) => (
                                    <h2 key={course.id}>{course.title}</h2>
                                )
  )}

because at the first rendering that property is not available.

Upvotes: 2

Related Questions