Category.js:55 Uncaught TypeError: categories is not iterable
Solution 1:
When you call const category = useSelector(state => state.category)
to get category , you was not sure whether or not category
has been fetched successfully yet ( focus on the calling getAllCategory()
on your useEffect
).
You just need to check before iterate categories
, and some refactor your code like this is fine:
const renderCategories = (categories) => {
if(!Array.isArray(categories)) return null
return categories.map((category, i) => (
<li key={`category-${i}`}>
{category.name}
{Array.isArray(category.children) && category.children.length > 0 ? (
<ul>{renderCategories(category.children)}</ul>
) : null}
</li>)
)
}
Also you can wrap your function renderCategories
with useCallback to make more effective
import { useCallback } from 'react'
const renderCategories = useCallback((categories) => {
if(!Array.isArray(categories)) return null
return categories.map((category, i) => (
<li key={`category-${i}`}>
{category.name}
{Array.isArray(category.children) && category.children.length > 0 ? (
<ul>{renderCategories(category.children)}</ul>
) : null}
</li>)
)
}, [])