Reputation: 11
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
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