Ayo Moses
Ayo Moses

Reputation: 1

Cannot read properties of undefined (reading 'name')

I keep getting this error: Cannot read properties of undefined (reading 'name') when I try to export this function

export const selectUserName = (state) => state.user.name 

in my react project. Please How do I Fix this

Upvotes: 0

Views: 390

Answers (2)

User object is null, that is causing issue, you can check if user object is not null

export const selectUserName = (state) => state.user && state.user.name 

More cleaner approach you can use optional chaining operator

export const selectUserName = (state) => state.user?.name 

Upvotes: 0

huMpty duMpty
huMpty duMpty

Reputation: 14470

user object probably null

export const selectUserName = (state) => state.user?.name 

Upvotes: 1

Related Questions