Issue
Should be a simple one... I just want to get data.user.roles, but data could be empty. In that case, I need an empty array as result. Also I need to define the type of user - which is in this case any.
So this is, what I came up with:
const { data } = useSession()
const user: any = data?.user || {} // define user
const roles = user?.roles || []
It works, but it doesn't feel very smart.
And I am not quite sure, if this would work if useSession doesn't return full dataset:
type Session = {
data: {
user?: {
roles?: string[]
}
}
}
const {
data: {
user: { roles = [] }
}
}: Session = useSession()
Solution
data is guaranteed to exist according to the Session type, so you don't need a ? after that. From there you just drill in and provide a fallback at the end.
const { data } = useSession()
const roles = data.user?.roles ?? []
Answered By - Alex Wayne
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.