I have an object, and i trying to access the object properties using destructuring. The problem is there are cases where state itself is undefined. Hence, i wanted to add optional chaining. However, i am stuck...
const {state: {one, two, three, four}} = useLocation()
My solution:
const {state?: {one, two, three, four}} = useLocation()
Problem: How can i add optional chaining for such syntax?
Otherwise the solution would be
useEffect(() => {
if (!state) {
setUserBirth(state?.userBirth);
setUserEmail(state?.userEmail);
setUserTel(state?.userTel);
setUserName(state?.userName);
setType(state?.type);
}
}, [state]);
But im wondering if i could directly apply optional chaining onto object destructuring
CodePudding user response:
You can do something like this
const {state: {one, two, three, four} = {}} = useLocation()
This will at least prevent the error when the state
is undefined