Skip to content

Commit 33668a5

Browse files
committed
persist access token
1 parent 3d3d7d7 commit 33668a5

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

apps/playground/src/store/index.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/* eslint-disable import/exports-last */
2+
import { jwtDecode } from 'jwt-decode';
23
import { pick } from 'lodash-es';
34
import { create } from 'zustand';
45
import { createJSONStorage, devtools, persist, subscribeWithSelector } from 'zustand/middleware';
@@ -31,7 +32,7 @@ export const useAppStore = create(
3132
{
3233
merge: (_persistedState, currentState) => {
3334
const persistedState = _persistedState as
34-
| Partial<Pick<AppStore, 'instruments' | 'selectedInstrument' | 'settings'>>
35+
| (Partial<Pick<AppStore, 'instruments' | 'selectedInstrument' | 'settings'>> & { _accessToken?: string })
3536
| undefined;
3637
const instruments = [
3738
...currentState.instruments,
@@ -43,10 +44,26 @@ export const useAppStore = create(
4344
instruments.find(({ id }) => id === persistedState?.selectedInstrument?.id) ??
4445
currentState.selectedInstrument;
4546
const settings = persistedState?.settings ?? currentState.settings;
46-
return { ...currentState, instruments, selectedInstrument, settings };
47+
const state: AppStore = { ...currentState, instruments, selectedInstrument, settings };
48+
if (persistedState?._accessToken) {
49+
try {
50+
state.auth = {
51+
accessToken: persistedState._accessToken,
52+
payload: jwtDecode(persistedState._accessToken)
53+
};
54+
} catch (_) {
55+
// if token is expired, ignore
56+
}
57+
}
58+
return state;
4759
},
4860
name: 'app',
49-
partialize: (state) => pick(state, ['instruments', 'selectedInstrument', 'settings']),
61+
partialize: (state) => {
62+
return {
63+
...pick(state, ['instruments', 'selectedInstrument', 'settings']),
64+
_accessToken: state.auth?.accessToken
65+
};
66+
},
5067
storage: createJSONStorage(() => localStorage),
5168
version: 1
5269
}

0 commit comments

Comments
 (0)