-
Hi, I'm using a pattern that allows to fetch the user session when the app is rendered, then when i update the session I would like a to trigger a new user refresh. It seems to work, but I'm not sure if this is the best way to deal with it. import { ApiClient } from "@modules/network/api";
import * as SecureStore from "expo-secure-store";
import { atom } from "jotai";
import { atomWithDefault } from "jotai/utils";
import { z } from "zod";
export type AuthState = {
user: {
id: string;
name: string;
};
session: AppSession;
} | null;
const sessionSchema = z.object({
id: z.string(),
expiresAt: z.date(),
fresh: z.boolean(),
userId: z.string(),
});
export type AppSession = z.infer<typeof sessionSchema>;
const storageKey = "auth_session";
const sessionAtom = atomWithDefault(async () => {
const sessionFromStage = await SecureStore.getItemAsync(storageKey);
return sessionFromStage ? (JSON.parse(sessionFromStage) as AppSession) : null;
});
const AuthSessionAtom = atom(async (get, { signal }) => {
const session = await get(sessionAtom);
if (!session) return null;
const { data } = await ApiClient.get("/auth/mobile/check-session", {
headers: { Authorization: `Bearer ${session.id}` },
signal,
});
return data as AuthState;
});
export const PublicAuthSessionAtom = atom(
async (get) => get(AuthSessionAtom),
async (_, set, session: AppSession) => {
await SecureStore.setItemAsync(storageKey, JSON.stringify(session));
set(sessionAtom, Promise.resolve(session));
},
); Thanks |
Beta Was this translation helpful? Give feedback.
Answered by
dai-shi
Oct 16, 2024
Replies: 1 comment
-
I would probably use atomWithRefresh, but this pattern is also fine and can be a little more efficient. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
ScreamZ
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would probably use atomWithRefresh, but this pattern is also fine and can be a little more efficient.