From 5d009746d8a73140eeecb7af0002db835ae99f1c Mon Sep 17 00:00:00 2001 From: NicolasRichel Date: Thu, 7 Jan 2021 08:55:41 +0100 Subject: [PATCH] feat(state): make states readonly in components --- src/router/index.js | 2 +- src/state/globalState.js | 19 +++++++++++++------ src/state/spacesState.js | 13 +++++++------ 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/router/index.js b/src/router/index.js index c1227b196..d6a114617 100644 --- a/src/router/index.js +++ b/src/router/index.js @@ -39,7 +39,7 @@ const router = createRouter({ }); router.beforeEach(async (to, from, next) => { - const { isAuthenticated, authenticate } = useGlobalState() + const { isAuthenticated, authenticate } = useGlobalState(); if (isAuthenticated.value) { next(); } else if (to.matched.some(r => r.meta.requiresAuth)) { diff --git a/src/state/globalState.js b/src/state/globalState.js index 150c61500..baea80d5b 100644 --- a/src/state/globalState.js +++ b/src/state/globalState.js @@ -1,5 +1,5 @@ import { UserManager, WebStorageStateStore } from 'oidc-client'; -import { reactive, toRefs, watch } from 'vue'; +import { reactive, readonly, toRefs, watchEffect } from 'vue'; import { setupApiClient } from '@/api'; import { oidcConfig } from '@/config/oidcConfig'; @@ -17,10 +17,12 @@ const userManager = new UserManager({ const authenticate = async (redirectPath) => { const user = await getUser(); if (user) { - state.isAuthenticated = true; - state.user = user; + if (!state.isAuthenticated) { + state.isAuthenticated = true; + state.user = user; + } } else { - await signIn(redirectPath) + await signIn(redirectPath); } }; @@ -32,11 +34,16 @@ const signInCallback = () => userManager.signinRedirectCallback(); const signOut = () => userManager.signoutRedirect(); -watch(() => state.user && setupApiClient(state.user.access_token)); +watchEffect(() => { + if (state.user) { + setupApiClient(state.user.access_token); + } +}); export function useGlobalState() { + const readonlyState = readonly(state); return { - ...toRefs(state), + ...toRefs(readonlyState), authenticate, signIn, signInCallback, diff --git a/src/state/spacesState.js b/src/state/spacesState.js index 599c02259..9f2d999a5 100644 --- a/src/state/spacesState.js +++ b/src/state/spacesState.js @@ -1,17 +1,18 @@ -import { reactive, toRefs } from 'vue'; +import { reactive, readonly, toRefs } from 'vue'; import SpacesService from '@/api/SpacesService'; const state = reactive({ spaces: [] }); -export function useSpacesState() { - const fetchSpaces = () => SpacesService.fetchUserSpaces().then( - spaces => state.spaces = spaces - ); +const fetchSpaces = () => SpacesService.fetchUserSpaces().then( + spaces => state.spaces = spaces +); +export function useSpacesState() { + const readonlyState = readonly(state); return { - ...toRefs(state), + ...toRefs(readonlyState), fetchSpaces }; }