Skip to content

Commit

Permalink
Clean up useSession hook
Browse files Browse the repository at this point in the history
  • Loading branch information
kristianpd committed Jul 5, 2023
1 parent 8f02f42 commit a125ff4
Showing 1 changed file with 9 additions and 13 deletions.
22 changes: 9 additions & 13 deletions packages/react/src/auth/useSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@ export interface GadgetUser {
[key: string]: any;
}

const useGetSessionAndUser = () => {
/**
* Used for fetching the current `Session` record from Gadget. Will suspend while the user is being fetched.
* @returns The current session
*/
export const useSession = (): GadgetSession => {
const api = useApi();
if ("currentSession" in api && "session" in api && "user" in api) {
return useGet(api.currentSession as any, {
const [{ data: session, error }] = useGet(api.currentSession as any, {
suspense: true,
select: {
...(api.session as any).findMany.defaultSelection,
Expand All @@ -26,18 +30,10 @@ const useGetSessionAndUser = () => {
},
},
});
if (error) throw error;
if (!session) throw new Error("currentSession not found but should be present");
return session;
} else {
throw new Error("api client does not have a Session or User model");
}
};

/**
* Used for fetching the current `Session` record from Gadget. Will suspend while the user is being fetched.
* @returns The current session
*/
export const useSession = (): GadgetSession => {
const [{ data: session, error }] = useGetSessionAndUser();
if (error) throw error;
if (!session) throw new Error("currentSession not found but should be present");
return session;
};

0 comments on commit a125ff4

Please sign in to comment.