Next.js Discord

Discord Forum

Error: Cannot read properties of undefined (reading 'length')

Unanswered
Canada Warbler posted this in #help-forum
Open in Discord
Canada WarblerOP
I'm trying to make an image slider and I've been running into this problem randomly, the code would work and function normally but then it would throw this error as soon as I reload the page

21 Replies

When you first load the page state is undefined as you initialize state as empty. Have in mind that Effects run after your component is rendered so the first time it renders it can’t access the length property, items it’s not an array yet.

You can’t access any property of undefined, so quick fix would be to give an empty array as the initial value for your state
Canada WarblerOP
I got the same error
Where do you call loadShow()?
@Canada Warbler I got the same error
How do you make sure your items array is actually populated with at least 4 items so you can access the one in index 3?
Canada WarblerOP
Oh no you can't do that and expect it to work. That function will execute on render when the array is []
So it's not even populated by the effect yet. Like I said before:
Have in mind that Effects run after your component is rendered
Canada WarblerOP
ahhhh
honestly coding this was kinda of a struggle
I got it to work tho
a friend and I were able to refactor it into this
Wayyyy better. Before you were basically using direct DOM manipulation (which tbh is still happening), you were not leveraging React at all.
I was about to call you out for that but first I was answering to your original question why wasn't it working
Canada WarblerOP
yeah looking back on it yeah I was, I was console logging items and it always came bac with nothing and I was so confused but frustrated that it wasnt working that I literally overlooked it
fair tbh, I couldn't even see what was wrong with it if my life depended on it
😭
That last code screenshot you sent, still feels like you're fighting React.
Can I see the return JSX part?
Canada WarblerOP