I've seen this happening when a hook was using after a conditional statement. Moving the hook usage above the conditional statement fixed the problem.
Reference: https://reactjs.org/docs/hooks-rules.html
Answer from fpintos on Stack OverflowI've seen this happening when a hook was using after a conditional statement. Moving the hook usage above the conditional statement fixed the problem.
Reference: https://reactjs.org/docs/hooks-rules.html
I know this question is really old, but hopefully posting this can help someone else in the future. In my situation, I got this error when I used Array.map() without specifying a unique key attribute on the top-level child element in the loop.
It took me days to figure out my mistake, and for whatever reason, there was no clear error message indicating the root cause. It's clear in the docs that a unique key should be used on all child items of a list, but I don't think that's a very good reason to allow such a cryptic error message to surface.
https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key
prevDep.length undefined Cannot read properties of undefined (reading 'length')
React - Cannot read property 'length' of undefined
`@preact/signals-react` 1.3.6 is brokes useSyncExternalStoreWithSelector
[Compiler Bug]: TypeError: Cannot read properties of undefined (reading 'length')
Changing this if condition from this:
if (props.items.length === 0) {
To
if (!props.items?.length) {
Should work.
Similarly if using for places,you can check using ternary operator if length exists in array of places.
How? Because items could possibly be null or undefined from apis, so the length property on array might be missing.
Moreover, using ! Not operator would make this condition true if length of items is 0 or is null or undefined or any falsy value
The other answers are focusing on prop.items list but in your question you mention that you get the exception when trying to access the length of the places inside users.
You are getting the error message because some users may not have any places listed inside them, hence, no places list -> no length property.
To fix this, you need to check if the places list exists and then access its length:
placeCount={ user.places ? user.places.length : 0 }
Here, we use a ternary operator to check if user.places exists, then we use the length, else use zero.
Edit: As pointed out by Phil in the comments below, you can also use coalescing operator, which is much cleaner, like this:
placeCount={ user.places?.length ?? 0 }
The syntax simply translates as if user.places has a value for length, then use that value, else use zero as a default value.
