I am using VueX within Nuxt and Typescript. I would like to have the initial state of my user be null. Setting state.authenticatedUser:null
works fine. But once I try to asign a IAuthenticatedUser to it, it won't know the type since I assigned null and it will throw an error in my mutation where I put the comment.
So how can I have my authenticatedUser be null initially?
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,
},
})
Define a class for the state that initializes it to null and declare state
to be of that class should work
export class RootState {
authenticatedUser: (IAuthenticatedUser | null) = null
}
export const state: RootState = {} as RootState;
authenticatedUser
will then be null
until you assign to it
state.authenticatedUser = {} as IAuthenticatedUser
Since the type is declared to allow null, you should also later be able to assign null again.
state.authenticatedUser = null