Skip to content

Commit

Permalink
feat(state): make states readonly in components
Browse files Browse the repository at this point in the history
  • Loading branch information
NicolasRichel committed Jan 15, 2021
1 parent 0d886a4 commit 5d00974
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
19 changes: 13 additions & 6 deletions src/state/globalState.js
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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);
}
};

Expand All @@ -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,
Expand Down
13 changes: 7 additions & 6 deletions src/state/spacesState.js
Original file line number Diff line number Diff line change
@@ -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
};
}

0 comments on commit 5d00974

Please sign in to comment.