Skip to content

Commit

Permalink
fix: isolate tokens by address (#114)
Browse files Browse the repository at this point in the history
  • Loading branch information
swkatmask authored May 28, 2024
1 parent 1e68394 commit 1a2e471
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 10 deletions.
6 changes: 3 additions & 3 deletions src/hooks/useAuthFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import { Response } from '@/types/api'

export function useAuthFetch<T extends Response<unknown>>() {
const login = useLogin()
const { token } = useAccountStore()
const { tokenMap } = useAccountStore()
const account = useAccount()
return useCallback<typeof fetchJSON<T>>(
async (input, init) => {
const address = account.address
if (!address) throw new Error('No wallet connected')
let jwtToken = token
let jwtToken = tokenMap[address.toLowerCase()]
if (!jwtToken) {
jwtToken = await login.mutateAsync()
}
Expand All @@ -34,6 +34,6 @@ export function useAuthFetch<T extends Response<unknown>>() {
}
return await send()
},
[account.address, login, token],
[account.address, login, tokenMap],
)
}
2 changes: 1 addition & 1 deletion src/hooks/useLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function useLogin() {
}),
})
if (loginRes.code === 200) {
updateToken(loginRes.data.token)
account.address && updateToken(account.address, loginRes.data.token)
return loginRes.data.token
} else {
throw new Error('Failed to login')
Expand Down
13 changes: 7 additions & 6 deletions src/store/accountStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,24 @@ import { persist } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'

interface AccountState {
token: string
updateToken(token: string): void
tokenMap: Record<string, string>
updateToken(address: string, token: string): void
clearToken(): void
}

export const useAccountStore = create<AccountState, [['zustand/persist', AccountState], ['zustand/immer', never]]>(
persist(
immer((set) => ({
token: '',
updateToken: (token: string) => {
tokenMap: {},
updateToken: (address: string, token: string) => {
set((state) => {
state.token = token.trim()
const key = address.toLowerCase()
state.tokenMap[key] = token.trim()
})
},
clearToken() {
set((state) => {
state.token = ''
state.tokenMap = {}
})
},
})),
Expand Down

0 comments on commit 1a2e471

Please sign in to comment.