Skip to content

Commit

Permalink
feat: implements useLazyProfile hook
Browse files Browse the repository at this point in the history
  • Loading branch information
cesarenaldi committed Oct 8, 2023
1 parent 63af2f6 commit 7149811
Show file tree
Hide file tree
Showing 12 changed files with 374 additions and 48 deletions.
2 changes: 2 additions & 0 deletions examples/web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { UseSearchProfiles } from './discovery/UseSearchProfiles';
import { UseSearchPublications } from './discovery/UseSearchPublications';
import {
ProfilesPage,
UseLazyProfile,
UseMutualFollowers,
UseProfile,
UseProfileActionHistory,
Expand Down Expand Up @@ -88,6 +89,7 @@ export function App() {
<Route path="/profiles">
<Route index element={<ProfilesPage />} />
<Route path="useProfile" element={<UseProfile />} />
<Route path="useLazyProfile" element={<UseLazyProfile />} />
<Route path="useProfiles" element={<UseProfiles />} />
<Route path="useProfileFollowers" element={<UseProfileFollowers />} />
<Route path="useProfileFollowing" element={<UseProfileFollowing />} />
Expand Down
5 changes: 4 additions & 1 deletion examples/web/src/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { Breadcrumbs } from './components/Breadcrumbs';
export function Layout() {
return (
<>
<Breadcrumbs />
<div style={{ marginBottom: '1em' }}>
<Breadcrumbs />
</div>

<Outlet />
</>
);
Expand Down
8 changes: 4 additions & 4 deletions examples/web/src/LogInPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ProfileId, useLogin, useProfiles } from '@lens-protocol/react';
import { profileId, useLogin, useProfiles } from '@lens-protocol/react';
import toast from 'react-hot-toast';
import { useNavigate } from 'react-router-dom';
import { useAccount, useConnect } from 'wagmi';
Expand All @@ -10,7 +10,7 @@ import { never } from './utils';

function ProfilesList({ owner }: { owner: string }) {
const navigate = useNavigate();
const { execute: login, isPending: isLoginPending } = useLogin();
const { execute: login, loading: isLoginPending } = useLogin();
const { data: profiles, error, loading } = useProfiles({ where: { ownedBy: [owner] } });

const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
Expand All @@ -19,11 +19,11 @@ function ProfilesList({ owner }: { owner: string }) {
const form = event.currentTarget;
const formData = new FormData(form);

const profileId = (formData.get('id') as string) ?? never();
const id = profileId(formData.get('id') as string) ?? never();

const result = await login({
address: owner,
profileId: profileId as ProfileId,
profileId: id,
});

if (result.isSuccess()) {
Expand Down
5 changes: 5 additions & 0 deletions examples/web/src/profiles/ProfilesPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ const profileHooks = [
description: `Fetch a single profile.`,
path: '/profiles/useProfile',
},
{
label: 'useLazyProfile',
description: `Lazy fetch a single profile.`,
path: '/profiles/useLazyProfile',
},
{
label: 'useProfiles',
description: `Fetch a list of profiles.`,
Expand Down
47 changes: 47 additions & 0 deletions examples/web/src/profiles/UseLazyProfile.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { profileId, useLazyProfile } from '@lens-protocol/react';
import toast from 'react-hot-toast';

import { ErrorMessage } from '../components/error/ErrorMessage';
import { never } from '../utils';
import { ProfileCard } from './components/ProfileCard';

export function UseLazyProfile() {
const { data: profile, error, loading, execute } = useLazyProfile();

const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();

const form = event.currentTarget;
const formData = new FormData(form);

const id = profileId(formData.get('id') as string) ?? never();

const result = await execute({ forProfileId: id });

if (result.isFailure()) {
toast.error(result.error.message);
}
};

return (
<div>
<form onSubmit={onSubmit}>
<fieldset>
<legend>Which Profile you want to log-in with?</legend>

<input name="id" defaultValue="0x01" />

<div>
<button disabled={loading} type="submit">
{loading ? 'Loading...' : 'Load'}
</button>
</div>
</fieldset>
</form>

{profile && <ProfileCard profile={profile} />}

{error && <ErrorMessage error={error} />}
</div>
);
}
1 change: 1 addition & 0 deletions examples/web/src/profiles/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './ProfilesPage';
export * from './UseLazyProfile';
export * from './UseMutualFollowers';
export * from './UseProfile';
export * from './UseProfileActionHistory';
Expand Down
9 changes: 6 additions & 3 deletions packages/react/src/authentication/useLogin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { useAsyncTask } from '../helpers/tasks';
import { Profile } from '@lens-protocol/api-bindings';
import { LoginError, LoginRequest } from '@lens-protocol/domain/use-cases/authentication';

import { UseDeferredTask, useDeferredTask } from '../helpers/tasks';
import { useLoginController } from './adapters/useLoginController';

export function useLogin() {
export function useLogin(): UseDeferredTask<Profile, LoginError, LoginRequest> {
const login = useLoginController();
return useAsyncTask(login);
return useDeferredTask(login);
}
59 changes: 58 additions & 1 deletion packages/react/src/helpers/reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
DocumentNode,
LazyQueryExecFunction,
OperationVariables,
LazyQueryResultTuple as ApolloLazyResultTuple,
useLazyQuery,
} from '@apollo/client';
import {
Expand All @@ -14,7 +15,14 @@ import {
PaginatedResultInfo,
LimitType,
} from '@lens-protocol/api-bindings';
import { Prettify } from '@lens-protocol/shared-kernel';
import {
failure,
IEquatableError,
never,
Prettify,
PromiseResult,
success,
} from '@lens-protocol/shared-kernel';
import { useCallback, useEffect, useRef, useState } from 'react';

import { useSharedDependencies } from '../shared';
Expand Down Expand Up @@ -99,6 +107,9 @@ export type QueryData<R> = { result: R };

type InferResult<T extends QueryData<unknown>> = T extends QueryData<infer R> ? R : never;

/**
* @internal
*/
export function useReadResult<
T extends QueryData<R>,
R = InferResult<T>,
Expand All @@ -107,6 +118,52 @@ export function useReadResult<
return buildReadResult(data?.result, error);
}

/**
* @experimental This is a pathfinder type for new lazy query hooks. It can change at any time.
*/
export type LazyReadResult<
TArgs,
TValue,
TError extends IEquatableError = UnspecifiedError,
> = ReadResult<TValue, TError> & {
/**
* Fetches the data for this query.
*
* @returns A promise that resolves when the data has been fetched.
*/
execute: (args: TArgs) => PromiseResult<TValue, TError>;
};

/**
* @internal
*/
export function useLazyReadResult<
TData extends QueryData<TResult>,
TResult = InferResult<TData>,
TVariables extends OperationVariables = { [key: string]: never },
>([execute, { error, data }]: ApolloLazyResultTuple<TData, TVariables>): LazyReadResult<
TVariables,
TResult,
UnspecifiedError
> {
return {
...buildReadResult(data?.result, error),

execute: useCallback(
async (variables: TVariables) => {
const result = await execute({ variables });

if (result.error) {
return failure(new UnspecifiedError(result.error));
}

return success(result.data ? result.data.result : never());
},
[execute],
),
};
}

export type OmitCursor<T> = Omit<T, 'cursor'>;

export type PaginatedArgs<T> = Prettify<
Expand Down
Loading

0 comments on commit 7149811

Please sign in to comment.