Как я могу установить состояние пользователя равным нулю? - PullRequest
0 голосов
/ 03 августа 2020

Я использую VueX в Nuxt и Typescript. Я хочу, чтобы начальное состояние моего пользователя было нулевым. Настройка state.authenticatedUser:null работает нормально. Но как только я попытаюсь назначить ему IAuthenticatedUser, он не будет знать тип, так как я присвоил 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,
    },
})

1 Ответ

0 голосов
/ 03 августа 2020

Определите класс для состояния, которое инициализирует его значением null, и объявите, что state относится к этому классу, который должен работать

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

export const state: RootState = {} as RootState;

authenticatedUser тогда будет null, пока вы не назначите ему

state.authenticatedUser = {} as IAuthenticatedUser

Поскольку тип объявлен как разрешающий значение null, вы также сможете позже снова назначить null.

state.authenticatedUser = null
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...