What is the best method for resetting the user state to null?

I'm currently utilizing VueX in Nuxt with Typescript. My goal is to set the initial state of my user to null. When I try setting state.authenticatedUser:null, everything works smoothly. However, when I attempt to assign an IAuthenticatedUser type to it, I encounter an issue because I initialized it as null, leading to an error in my mutation function.

How can I ensure that my authenticatedUser starts off as null?

import { getAccessorType, mutationTree, actionTree } from 'nuxt-typed-vuex';

import IAuthenticatedUser from '~/ts/interfaces/firebase/user/authenticated_user.ts';
import * as counter from './counter';

type RootState = ReturnType<typeof state>

export const state = () => ({
    authenticatedUser: {} as IAuthenticatedUser, //I want this to be null
})

export const getters = {

}

export const mutations = mutationTree(state, {
    setAuthenticatedUser(state, newValue: IAuthenticatedUser) {
        state.authenticatedUser = newValue // If state.authenticateUser == null I cannot asign newValue becuase state.authenticateUser has a type of null
    },
    logOut(){
        state.authenticatedUser = null; // I cannot do this since it not of type IAuthenticatedUser
    }
})

export const actions = actionTree(
    { state, getters, mutations },
    {
        async onAuthenticationStateChangedAction({ commit, dispatch }, { authUser, claims }) {

            if (!authUser) {
                commit('logOut');
                return
            }

            const { uid, email, emailVerified, displayName, photoURL } = authUser

            commit('setAuthenticatedUser', {
                uid,
                email,
                emailVerified,
                displayName,
                photoURL,
            })
        }
    }
)

export const accessorType = getAccessorType({
    actions,
    getters,
    mutations,
    state,
    modules: {
        counter,
    },
})

Answer №1

To create a class for the state that starts as null and specify state to be of that class, follow these steps:

export class RootState {
    authenticatedUser: (IAuthenticatedUser | null) = null
}

export const state: RootState = {} as RootState;

authenticatedUser will initially be null until you assign a value to it

state.authenticatedUser = {} as IAuthenticatedUser

Since the type allows for null, you can also reassign it to null later if needed.

state.authenticatedUser = null

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using VueJS for reactive binding效果

I am attempting to assign a class using the following syntax: :class="{active: favs.medium_title.fontWeight === 'bold'}" However, the fontWeight attribute is not yet defined when the component loads. This is an excerpt from my object: favs: { ...

Guide on incorporating a Vue component into multiple components and leveraging a method to invoke it

Do you have a Vue Component called AlertSimple that displays alerts? Are you looking to make this component automatically available in all components and call it with a simple method like this: this.$alertSimple.show( 'Alert Title', 'Alert m ...

An error occurred while attempting to set up Next-auth in the process of developing

In my Next.js app, I have implemented next-auth for authentication. During local development, everything works fine with 'npm install' and 'npm run dev', but when I try to build the project, I encounter this error message: ./node_modul ...

iOS 10.3.1 causing Ionic 2 (click) event to trigger twice

I am currently working on an Ionic 2 app and I am facing an issue with the click event. When I test the app on a device and click on a button, let's say to trigger an alert, the function executes once. However, if I click on the button again, the fun ...

Creating a unique user interface for VSCode extension

Recently, I've delved into the world of developing extensions for Visual Studio. Unfortunately, my expertise in TypeScript and Visual Studio Code is quite limited. My goal is to create an extension that mirrors the functionality of activate-power-mod ...

Ionic - Smooth horizontal tab scrolling for sorted categories

Currently, we are developing a web/mobile application that includes horizontal scroll tabs to represent Categories. While this feature works well on mobile devices, it requires additional functionality for web browsers. Specifically, we need to add two arr ...

Loop through a collection of unique identifiers for documents and establish event listeners in Firestore

Within my Vuex store, there is an action designed to retrieve a list of uids for followed users from the current user's Firestore UserDataCollection document. The action then processes each uid to extract data that will be displayed on the UI. While t ...

Troubleshooting Vue Single File Components Displaying Missing Styles

I'm currently attempting to incorporate styles into a vuejs single file component. I've successfully achieved this in a node app previously, but now I am working with a python/flask backend (not that it should make a difference). The Vue componen ...

Using Angular 4 to monitor changes in two-way binding properties

Recently, I developed a unique toggle-sorting component that examines if the current sorting parameters align with its sorting slug and manages clicks to reflect any changes. // toggle-sorting.component.ts @Input() sortingSlug: string; @Input() currSorti ...

Comprehending the principles of Vue components and navigation paths

I have embarked on the journey of mastering the art of website development, utilizing a Vue frontend in conjunction with an Express REST backend. One of the new routes I created looks like this: /path/to/vue-client/routes/index.js import Vue from ' ...

Guide on sending a form from a separate component upon clicking the OK button in a modal window using Bootstrap Vue

I've encountered a situation in my Vue app where I have a component called TodoForm that handles a basic form. I want to implement functionality using bootstrap-vue so that when the OK button within a bootstrap modal is clicked, the form is submitted. ...

The Vue.js 2 router seems to malfunction when triggered programmatically, yet it functions properly when used as a

index js file I tried using Vue Router programatically, but it was not working for me. After searching online, I found that everyone used this.$router.push(). import Vue from 'vue' import Router from 'vue-router' import HelloWorld fro ...

Create a Typescript generic function that can return a variety of data types including strings, numbers, and

I have a function written in Typescript and I am looking to determine the return type based on the value retrieved from process.env. For instance, the variables in my Node process.env can be strings, numbers, or booleans. I want to fetch them with their s ...

Incorporate new class into preexisting modules from external library

I am currently working on expanding Phaser by incorporating a new module called Phaser.Physics.Box2D. While Phaser already utilizes this module internally, it is an additional plugin and I am determined to create my own version. TypeScript is the language ...

Exploring the relationships between nested tuple types

When exploring the concept of mapped tuple types in TypeScript, the documentation provides an example: type MapToPromise<T> = { [K in keyof T]: Promise<T[K]> }; type Coordinate = [number, number] type PromiseCoordinate = MapToPromise<Coor ...

Configuring TypeScript to utilize worker_threads

Currently, I am attempting to implement WebWorkers in my Typescript project and I have encountered a hurdle. Despite having installed @types/node and updating everything, 'worker_threads' has transitioned from an experimental feature to a stable ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Do I need to open Chrome if I want to switch web notifications to Android TWA?

Through the use of TWA technology, we were able to create an Android app that can open a PWA page without displaying an Address bar. Unfortunately, this setup presented a challenge. The absence of the Address bar made it difficult to switch web Push Noti ...

There is an error in the TypeScript code where it is not possible to assign a string or

I'm struggling to resolve a typescript error. Upon checking the console log, I noticed that the regions returned by Set are an array of strings, which aligns perfectly with the region type in my state. Why isn't this setup working as expected? S ...

What is the best way to make a library accessible throughout an entire Vue.js 3 project?

As mentioned in a recent blog post on Vue.js libraries and plugins, the recommended method for including commonly used libraries like axios in Vue.js 2 is by setting them as properties of the Vue prototype object: import axios from 'axios'; Objec ...