Skip to content

Commit

Permalink
feat: wip still a bit broken
Browse files Browse the repository at this point in the history
  • Loading branch information
simodrws committed Jun 9, 2023
1 parent 233efbe commit 8216333
Show file tree
Hide file tree
Showing 12 changed files with 314 additions and 29 deletions.
8 changes: 7 additions & 1 deletion .eslintrc
@@ -1,7 +1,13 @@
{
"parser": "@typescript-eslint/parser",

"plugins": ["@typescript-eslint", "promise", "unicorn", "react-hooks"],
"plugins": [
"@typescript-eslint",
"promise",
"unicorn",
"react-hooks",
"@tanstack/query"
],
"parserOptions": {
"project": "./tsconfig.json"
},
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -80,6 +80,7 @@
"@storybook/addons": "^7.0.2",
"@storybook/react": "^7.0.18",
"@storybook/react-webpack5": "^7.0.12",
"@tanstack/eslint-plugin-query": "^4.29.9",
"@tanstack/react-query-devtools": "^4.29.12",
"@types/jest": "^29.5.0",
"@types/mocha": "^10.0.1",
Expand Down
1 change: 1 addition & 0 deletions src/refactor/config.ts
Expand Up @@ -25,6 +25,7 @@ export interface MasaReactConfig {
};

masaConfig: Omit<MasaArgs, 'signer'>;

}

export const defaultConfig: Partial<MasaReactConfig> = {
Expand Down
20 changes: 14 additions & 6 deletions src/refactor/masa-client/masa-client-provider.tsx
@@ -1,20 +1,28 @@
import React, { ReactNode, createContext, useContext, useMemo } from 'react';
import { useMasaClient } from './masa-client';
import { useMasaClient } from './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'];
session?: ReturnType<typeof useSession>['session'];
identity?: ReturnType<typeof useIdentity>['identity'];
}

export const MasaClientContext = createContext({} as MasaClientProviderValue);

export const MasaClientProvider = ({ children }: { children: ReactNode }) => {
const { sdk: masa } = useMasaClient();
const { session } = useSession();

const masaClientProviderValue = useMemo(
() => ({
masa,
}),
[masa]
const masaClientProviderValue: MasaClientProviderValue = useMemo(
() =>
({
masa,

session,
} as MasaClientProviderValue),
[masa, session]
);
return (
<MasaClientContext.Provider value={masaClientProviderValue}>
Expand Down
61 changes: 61 additions & 0 deletions src/refactor/masa-client/query-client.ts
@@ -0,0 +1,61 @@
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
import { Query, QueryClient, QueryKey } from '@tanstack/react-query';
import type {
PersistedClient,
Persister,
} from '@tanstack/react-query-persist-client';
import { persistQueryClient } from '@tanstack/react-query-persist-client';
import { noopStorage } from '@wagmi/core';
import { createStorage } from 'wagmi';

export const createQueryClient = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 24, // 24 hours
networkMode: 'offlineFirst',
refetchOnWindowFocus: false,
retry: 0,
},
mutations: {
networkMode: 'offlineFirst',
},
},
});

const storage = createStorage({
storage:
typeof window !== 'undefined' && window.localStorage
? window.localStorage
: noopStorage,
});
let persister: Persister | undefined;

if (typeof window !== 'undefined') {
persister = createSyncStoragePersister({
key: 'masa-cache',
storage,
// Serialization is handled in `storage`.
serialize: (x: unknown) => x as string,
// Deserialization is handled in `storage`.
deserialize: (x: unknown) => x as PersistedClient,
});
}

if (persister)
persistQueryClient({
queryClient,
persister,
dehydrateOptions: {
shouldDehydrateQuery: (
query: Query<unknown, unknown, unknown, QueryKey>
) =>
query.cacheTime !== 0 &&
// Note: adding a `persist` flag to a query key will instruct the
// persister whether or not to persist the response of the query.
(query.queryKey[0] as { persist?: boolean }).persist !== false,
},
});

return queryClient;
};
Expand Up @@ -34,6 +34,7 @@ export const useMasaClient = () => {
const masaClient = useMemo(
() => ({
sdk: masa,
masa,
}),
[masa]
);
Expand Down
28 changes: 28 additions & 0 deletions src/refactor/masa-feature/use-identity.ts
@@ -0,0 +1,28 @@
import { useAsync, useAsyncFn } from 'react-use';
import { useMasaClient } from '../masa-client/use-masa-client';
import { useWallet } from '../wallet-client/wallet/use-wallet';

export const useIdentity = () => {
const { sdk: masa } = useMasaClient();
const { address } = useWallet();

const [{ value: identity, loading: isLoadingIdentity }, loadIdentity] =
useAsyncFn(async () => {
try {
if (!masa) return undefined;
return await masa.identity.load(address);
} catch (error) {
console.log('IM IN THIS ERROR', { error });
throw error;
}
}, [address, masa]);

useAsync(async () => {
await loadIdentity();
}, [loadIdentity]);

return {
identity,
isLoadingIdentity,
};
};
99 changes: 99 additions & 0 deletions src/refactor/masa-feature/use-session.ts
@@ -0,0 +1,99 @@
import { useQuery } from '@tanstack/react-query';
import { useAsync, useAsyncFn } from 'react-use';
import { useWallet } from '../wallet-client/wallet/use-wallet';
import { useMasaClient } from '../masa-client/use-masa-client';

export const useSession = () => {
const { address, isDisconnected } = useWallet();
const { masa } = useMasaClient();

const [{ loading: isLoggingIn }, loginSession] = useAsyncFn(async () => {
if (!masa) return undefined;
if (!address) return undefined;
const loginObj = await masa.session.login();

if (!loginObj) {
return undefined;
}
return {
address: loginObj.address,
userId: loginObj.userId,
cookie: loginObj.cookie,
};
}, [masa, address]);

const { data: hasSession, refetch: checkLogin } = useQuery({
queryKey: ['session-check', { address }],
enabled: !!masa && !!address,

queryFn: async () => {
const hasSesh = await masa?.session.checkLogin();
if (hasSesh) return hasSesh;
return null;
},
});

const {
data: session,
refetch: getSession,
isPreviousData,
} = useQuery({
queryKey: ['session', { address, hasSession }],
enabled: !!masa && !!address && hasSession !== undefined,

queryFn: async () => {
if (hasSession && address !== session?.user?.address) {
await masa?.session.logout();
}
const sesh = await masa?.session.getSession();
return sesh
? {
...sesh,
}
: undefined;
},
});

useAsync(async () => {
const { data: refetchSess } = await getSession();
console.log('DEBUG AM I HERE ?', {
hasSession,
refetchSess,
address,
session,
isPreviousData,
});

if (isDisconnected) {
await masa?.session.logout();
// return;
}
if (session !== address && hasSession) {
// await masa?.session.logout();
const { data: res } = await getSession();

Check failure on line 73 in src/refactor/masa-feature/use-session.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node

'res' is declared but its value is never read.
}
}, [
session,
hasSession,
address,
masa,
getSession,
isDisconnected,
isPreviousData,
]);

const [{ loading: isLoggingOut }, logoutSession] = useAsyncFn(async () => {
await masa?.session.logout();
}, [masa]);
return {
// checkLogin,
session,
hasSession,
loginSession,
logoutSession,
isLoggingIn,
isLoggingOut,
getSession,
checkLogin,
};
};
18 changes: 12 additions & 6 deletions src/refactor/masa-provider.tsx
@@ -1,9 +1,12 @@
import React, { ReactNode, createContext, useContext, useMemo } from 'react';
import { QueryClientProvider } from '@tanstack/react-query';

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 { createQueryClient } from './masa-client/query-client';

export interface MasaProviderValue {}

Expand All @@ -19,18 +22,21 @@ export const MasaProvider = ({
verbose?: boolean;
}) => {
const masaProviderValue = useMemo(() => ({} as MasaProviderValue), []);

const queryClient = useMemo(() => createQueryClient(), []);
return (
<MasaBaseProvider
config={{ ...config, masaConfig: { ...config.masaConfig, verbose } }}
>
<WagmiRainbowkitProvider>
<WalletProvider>
<MasaClientProvider>
<MasaContext.Provider value={masaProviderValue}>
{children}
</MasaContext.Provider>
</MasaClientProvider>
<QueryClientProvider client={queryClient}>
<MasaClientProvider>
<MasaContext.Provider value={masaProviderValue}>
{children}
</MasaContext.Provider>
</MasaClientProvider>

</QueryClientProvider>
</WalletProvider>
</WagmiRainbowkitProvider>
</MasaBaseProvider>
Expand Down

0 comments on commit 8216333

Please sign in to comment.