Using Optional Chaining in Redux Selectors
Demonstrate the usage of optional chaining (`?.`) in Redux selectors to access deeply nested state properties in a safe way.
const selectUserEmail = state => state.user?.contact?.email;
// Usage in a component
const userEmail = useSelector(selectUserEmail);
Defines a selector 'selectUserEmail' using optional chaining to safely access 'email' inside the 'contact' object of 'user' in the state, even if 'user' or 'contact' may not be defined.
const selectUserProfilePicture = state => state.profile?.pictures?.[0]?.url;
// Usage in a component
const profilePictureUrl = useSelector(selectUserProfilePicture);
Creates a selector 'selectUserProfilePicture' that utilizes optional chaining to get the URL of the first picture in the 'pictures' array in 'profile'. This avoids errors if 'profile', 'pictures', or the first picture is not present.