Skip to content

Why you should destructure?

stan-js relates highly on Proxy, and it comes with some limitations that you should be aware of.

export const store = createStore({
accessToken: null as string | null,
userInfo: null as UserInfo | null,
get isAuthenticated() {
return Boolean(this.accessToken) && Boolean(this.userInfo)
}
})

At first, you may not spot the problem with this code, but let’s first change how our computed value is defined:

export const store = createStore({
accessToken: null as string | null,
userInfo: null as UserInfo | null,
get isAuthenticated() {
if (!this.accessToken) {
return false
}
return Boolean(this.userInfo)
}
})

It does exactly the same thing, but it is much easier to spot the problem now.

At the initial load stan-js has seen that isAuthenticated getter tried to access only accessToken property, because it was escaped with false before it accessed userInfo property. So it didn’t subscribe to userInfo change.

We can fix this by changing our implementation to:

export const store = createStore({
accessToken: null as string | null,
userInfo: null as UserInfo | null,
get isAuthenticated() {
return [this.accessToken, this.userInfo].every(Boolean)
}
})

And this will work as expected. But we highly encourage you to use destructuring assignment to avoid this kind of problems.

export const store = createStore({
accessToken: null as string | null,
userInfo: null as UserInfo | null,
get isAuthenticated() {
const { accessToken, userInfo } = this
return Boolean(accessToken) && Boolean(userInfo)
}
})