Reputation: 677
I have this code here. I keep getting an error:
TypeError: Cannot read property 'map' of undefined.
Here are a few facts:
singleCategory.title
Always displays correctly.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
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