1

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>
                                )
                            )}
2
  • 2
    useEffect runs after the first render so singleCategory is not defined on that render. Generally conditionally render the map and it will render with the fetched data on the second render. Commented Dec 5, 2020 at 12:26
  • 1
    add a conditionnal render to your .map() { singleCategory.courses.length > 0 && singleCategory.course.map(...)} Commented Dec 5, 2020 at 12:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.