Skip to content

Commit

Permalink
feat: more refactor, session cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
simodrws committed Jun 14, 2023
1 parent 638f479 commit fb15d63
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 60 deletions.
@@ -1,7 +1,7 @@
import React, { ReactNode, createContext, useContext, useMemo } from 'react';
import { useMasaClient } from './use-masa-client';
import { useIdentity } from '../masa-feature/use-identity';
import { useSession } from '../masa-feature/use-session';
import { useMasaClient } from './masa-client/use-masa-client';
import { useIdentity } from './masa-feature/use-identity';
import { useSession } from './masa-feature/use-session';

export interface MasaClientProviderValue {
masa?: ReturnType<typeof useMasaClient>['sdk'];
Expand Down
96 changes: 54 additions & 42 deletions src/refactor/masa-feature/use-session.ts
Expand Up @@ -5,26 +5,32 @@ import { useWallet } from '../wallet-client/wallet/use-wallet';
import { useMasaClient } from '../masa-client/use-masa-client';
import { QcContext } from '../masa-provider';

// * NOTE: react-query does not allow us to pass undefined as a function return,
// * NOTE: so we need to convert an undefined result in every query to null
// * TODO: split up the queries, pass context via function variable to avoid dependency cycle
// * FIXME: we are getting the session 3 times on every change, we should only get it once
export const useSession = () => {
const { address, isDisconnected, previousAddress } = useWallet();
const { masa } = useMasaClient();
const queryClient = useQueryClient({ context: QcContext });
// console.log({ address, previousAddress });
const [{ loading: isCheckingSession }, checkSession] =

// * callbacks
const [{ loading: isCheckingSession }, checkSessionAsync] =
useAsyncFn(async () => {
if (!address) return null;
if (!masa) return null;
if (isDisconnected) return null;

const hasSesh = await masa?.session.checkLogin();
if (hasSesh !== undefined || hasSesh !== null) return hasSesh;

return null;
}, [masa, address]);
}, [masa, address, isDisconnected]);

const [{ loading: isLoggingIn }, loginSession] = useAsyncFn(async () => {
const [, loginSessionAsync] = useAsyncFn(async () => {
if (!masa) return null;
if (!address) return null;

if (isDisconnected) return null;
const loginObj = await masa.session.login();

if (!loginObj) {
Expand All @@ -35,7 +41,7 @@ export const useSession = () => {
userId: string;
address: string;
};
}, [masa, address]);
}, [masa, address, isDisconnected]);

const [, getSessionAsync] = useAsyncFn(async () => {
if (!masa) return null;
Expand All @@ -50,17 +56,19 @@ export const useSession = () => {
return seshFromGet;
}, [address, masa]);

// * queries
const {
data: sessionFromGet,
data: session,
isLoading: isFetchingSession,
refetch: getSessionCB,
refetch: getSession,
isRefetching: isRefetchingSession,
} = useQuery({
queryKey: ['session-obj', address],
queryKey: ['session', address],
enabled: false,
context: QcContext,
onSuccess: async (data: ISession | null) => {
if (data) {
const resultCheck = await checkSession();
const resultCheck = await checkSessionAsync();
if (!resultCheck) {
// await queryClient.invalidateQueries(['session-check', address]);
}
Expand All @@ -69,39 +77,43 @@ export const useSession = () => {
queryFn: async () => getSessionAsync(),
});

const { data: hasSession, refetch: checkLogin } = useQuery({
const {
data: hasSession,
refetch: checkLogin,
isRefetching: isCheckingLogin,
} = useQuery({
queryKey: ['session-check', address],
enabled: !!masa,
context: QcContext,
onSuccess: async (data: boolean) => {
switch (data) {
case true: {
const checkedLogin = await checkSession();
const checkedLogin = await checkSessionAsync();

if (!checkedLogin) {
await queryClient.invalidateQueries(['session-obj', address]);
await queryClient.invalidateQueries(['session-check', address]);
await queryClient.invalidateQueries(['session', address]);
await queryClient.invalidateQueries(['session-check', address]);
await queryClient.invalidateQueries(['session-login', address]);
return;
}

if (sessionFromGet && address === sessionFromGet?.user.address) {
if (session && address === session?.user.address) {
return;
}

await queryClient.invalidateQueries(['session-obj', address]);
await queryClient.fetchQuery(['session-obj', address]);
await queryClient.invalidateQueries(['session', address]);
await queryClient.fetchQuery(['session', address]);
break;
}

case false: {
queryClient.setQueryData(['session-login', address], null);
queryClient.setQueryData(['session', address], null);
queryClient.setQueryData(['session-obj', address], null);
break;
}
case undefined: {
queryClient.setQueryData(['session-login', address], null);
queryClient.setQueryData(['session', address], null);
queryClient.setQueryData(['session-obj', address], null);
break;
}
default: {
Expand All @@ -114,7 +126,7 @@ export const useSession = () => {
if (!address) return false;
if (!masa) return false;

const hasSesh = await checkSession();
const hasSesh = await checkSessionAsync();

if (hasSesh) {
return hasSesh;
Expand All @@ -124,18 +136,19 @@ export const useSession = () => {
},
});

// * logout callback
const [{ loading: isLoggingOut }, logoutSession] = useAsyncFn(async () => {
if (hasSession) {
await masa?.session.logout();
}

await queryClient.invalidateQueries(['session-check', address]);
await queryClient.invalidateQueries(['session-login', address]);
await queryClient.invalidateQueries(['session', address]);
await queryClient.invalidateQueries(['session-obj', address]);
}, [masa, queryClient, address, hasSession]);

const { data: session, refetch: getSession } = useQuery({
queryKey: ['session', address],
const { refetch: loginSession, isRefetching: isLoggingIn } = useQuery({
queryKey: ['session-login', address],
enabled: false,
context: QcContext,
refetchOnMount: false,
Expand All @@ -145,48 +158,47 @@ export const useSession = () => {
},

queryFn: async () => {
const hasIt = await checkSession();

if (hasIt) {
const sesshFromGet = await masa?.session.getSession();
if (isDisconnected) return null;
const hasIt = await checkSessionAsync();

if (sesshFromGet === undefined || sesshFromGet === null) {
return null;
}

return sesshFromGet;
}

const sesh = await loginSession();

if (sesh === undefined || sesh === null) return null;
if (hasIt) return null;

return sesh;
await loginSessionAsync();
return null;
},
});

useAsync(async () => {
if (isDisconnected) {
await logoutSession();
}

if (previousAddress !== address) {
await checkLogin();
}
}, [address, previousAddress, checkLogin, isDisconnected, logoutSession]);

return {
session,
sessionFromGet,
getSessionCB,
getSession,
isFetchingSession,
isRefetchingSession,
hasSession,
checkSession,
checkSessionAsync,
isCheckingSession,
isCheckingLogin,
loginSession,
logoutSession,
isLoggingIn,
isLoggingOut,
getSession,
isLoggedIn: hasSession,
checkLogin,
isLoadingSession:
isLoggingIn ||
isLoggingOut ||
isFetchingSession ||
isCheckingLogin ||
isCheckingSession ||
isRefetchingSession,
};
};
2 changes: 1 addition & 1 deletion src/refactor/masa-provider.tsx
Expand Up @@ -5,7 +5,7 @@ import MasaBaseProvider from './base-provider';
import { MasaReactConfig } from './config';
import WalletProvider from './wallet-client/wallet-client-provider';
import WagmiRainbowkitProvider from './wallet-client/wagmi-rainbowkit-provider';
import MasaClientProvider from './masa-client/masa-client-provider';
import MasaClientProvider from './masa-client-provider';

import { createQueryClient } from './masa-client/query-client';

Expand Down
29 changes: 18 additions & 11 deletions src/refactor/masanew.stories.tsx
Expand Up @@ -225,15 +225,16 @@ const MasaInfo = () => {
// const { identity, isLoadingIdentity } = useIdentity();
const {
session,
// loginSession,
loginSession,
logoutSession,
isLoggingIn,
isLoggingOut,
sessionFromGet,

hasSession,
getSession,
isLoadingSession,
checkLogin,
} = useSession();
const { isDisconnected } = useWallet();

// console.log('STORY', { hasSession, session });
return (
Expand All @@ -251,17 +252,15 @@ const MasaInfo = () => {
<li>
<ul>
<h3>Session</h3>
<li>isLoadingSession: {String(isLoadingSession)}</li>
<li>hasSession: {String(hasSession)}</li>
<li>isLoggingIn: {String(isLoggingIn)}</li>
<li>isLoggingOut: {String(isLoggingOut)}</li>
<li>
Session: <br />
<code>{JSON.stringify(session, null, 4)}</code>
</li>
<li>
Session From Get: <br />
<code>{JSON.stringify(sessionFromGet, null, 4)}</code>
</li>

{/* <li>Session User: {JSON.stringify(session?.user, null, 2)}</li>
<li>Session Challenge: {session?.challenge}</li>
<li>session cookie: {JSON.stringify(session?.cookie, null, 2)}</li> */}
Expand All @@ -271,9 +270,9 @@ const MasaInfo = () => {
<ul>
<li>
<Button
disabled={!!hasSession}
disabled={!!hasSession || isDisconnected || isLoadingSession}
type="button"
onClick={() => getSession() as unknown as () => void}
onClick={() => loginSession() as unknown as () => void}
>
Login Session RQ
</Button>
Expand All @@ -288,12 +287,20 @@ const MasaInfo = () => {
</Button>
</li> */}
<li>
<Button disabled={!hasSession} type="button" onClick={logoutSession}>
<Button
disabled={!hasSession || isLoadingSession}
type="button"
onClick={logoutSession}
>
Logout Session
</Button>
</li>
<li>
<Button type="button" onClick={() => checkLogin()}>
<Button
disabled={isDisconnected || isLoadingSession}
type="button"
onClick={() => checkLogin()}
>
Check Login
</Button>
</li>
Expand Down
6 changes: 3 additions & 3 deletions src/refactor/wallet-client/wallet/use-wallet.ts
Expand Up @@ -19,7 +19,9 @@ const useWallet = () => {
const { openAccountModal } = useAccountModal();
const { isConnected, isConnecting, isDisconnected, connector, address } =
useAccount();
const [previousAddress, setPreviousAddress] = useState(address);
const [previousAddress, setPreviousAddress] = useState<
`0x${string}` | undefined
>(undefined);
const [compareAddress, setCompareAddress] = useState(address);
const { data: signer, isLoading: isLoadingSigner } = useSigner();
const { disconnect, disconnectAsync } = useDisconnect();
Expand All @@ -39,8 +41,6 @@ const useWallet = () => {
setPreviousAddress(undefined);
}

console.log('addr changed', { address });

if (compareAddress !== address) {
setPreviousAddress(compareAddress);
setCompareAddress(address);
Expand Down

0 comments on commit fb15d63

Please sign in to comment.