Sayed Sajjad Haidari
Sayed Sajjad Haidari

Reputation: 11

how to avoid undefined data when getting data from redux using useSelector?

Please let me know how to get data conditionally (if exists) when working with useSelector in reactJs component. Sometimes the required data is not available untill a certain component renders first.

Upvotes: 0

Views: 453

Answers (1)

Henry Le
Henry Le

Reputation: 451

You can use the optional chaining operator ?. to safely access a property on an object that might not exist. You can combine this with the logical OR operator || to set a default value if the user or user_name is not set.

const user_name = useSelector(state => state.user?.user_name) || ''

Upvotes: 2

Related Questions