Run side-effect on every 'get' (to rotate a token if necessary) #2703
Replies: 3 comments 2 replies
-
Thanks for opening up a discussion. |
Beta Was this translation helpful? Give feedback.
-
There might be a workaround with the current |
Beta Was this translation helpful? Give feedback.
-
How about storing the token on a ref and using a counter to trigger refreshes when the token changes? function createLoginAtom() {
const refAtom = atom(() => ({
token: null
})
const refreshAtom = atomWithReducer(
0,
s => ++s
)
const loginBaseAtom = atom(
(get, { setSelf }) => {
get(refreshAtom)
const ref = get(refAtom)
ref.token ??= get(loginBaseAtom)
if (isExpired(ref.token)) {
queueMicrotask(setSelf) // refresh
return ref.token = rotateToken()
}
return ref.token
},
(_, set) => set(refreshAtom)
)
return atom((get) => get(loginAtom)
} |
Beta Was this translation helpful? Give feedback.
-
I wonder what the best practice is to run a side effect whenever an atom is read. Could you help me out?
My use case is to have an atom with an always up to date oAuth-token. The should be rotated if necessary, using the following logic:
I tried using the amazing jotai-effect, but it doesn't work. The effect basically never runs, because the token from the storage does not change.
Beta Was this translation helpful? Give feedback.
All reactions