Skip to content
Advertisement

VUEX, what to do when $store.state is null

When users are not logged into my website, the state of user is set to null. However, this throws up a lot of issues on some pages where i look to see if this.$store.user

For example, if I were to have a simple check such as

if (this.$store.getters.userInfo.likedProjects.includes(title)) {this.hasLiked = true}

and the user is not logged in (thus, setting the state of user to null by default) I get this error;

_this.$store.getters.userInfo is null

How should I correctly handle this sort of issues so that my console does not get flooded with typescript errors?

My initial idea was to first check if user.loggedIn == true and wrap everything inside of that, but that seems awfully messy just to avoid some errors…

Advertisement

Answer

Use optional chaining, which is available in TypeScript 3.7+:

if (this.$store.getters.userInfo?.likedProjects.includes(title)) {
    this.hasLiked = true;
}

If userInfo is null or undefined, then the entire statement this.$store.getters.userInfo?.likedProjects.includes(title) will return undefined instead of throwing an error.

If likedProjects may also be null or undefined, then you need to use optional chaining on that property too, i.e.:

if (this.$store.getters.userInfo?.likedProjects?.includes(title)) {
    this.hasLiked = true;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement