Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pagination support to usePromise, useCachedPromise and useFetch. #25

Merged
merged 17 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/utils-reference/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ npm install --save @raycast/utils

## Changelog

### v1.13.0

- Added pagination support to `usePromise`, `useCachedPromise` and `useFetch`.

### v1.12.5

- Add string array support for OAuth scope (Thanks @tonka3000!).
Expand Down
114 changes: 114 additions & 0 deletions docs/utils-reference/react-hooks/useCachedPromise.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,106 @@ export default function Command() {
}
```

## Pagination

{% hint style="info" %}
When paginating, the hook will only cache the result of the first page.
{% endhint %}

The hook has built-in support for pagination. In order to enable pagination, `fn`'s type needs to change from

> an asynchronous function or a function that returns a Promise

to

> a function that returns an asynchronous function or a function that returns a Promise

In practice, this means going from

```ts
const { isLoading, data } = useCachedPromise(
async (searchText: string) => {
const response = await fetch(`https://api.example?q=${searchText}`);
const data = await response.json();
return data;
},
[searchText],
{
// to make sure the screen isn't flickering when the searchText changes
keepPreviousData: true,
},
);
```

to

```ts
const { isLoading, data, pagination } = useCachedPromise(
(searchText: string) => async (options) => {
const response = await fetch(`https://api.example?q=${searchText}&page=${options.page}`);
const data = await response.json();
const hasMore = options.page < 50;
return { data, hasMore };
},
[searchText],
{
// to make sure the screen isn't flickering when the searchText changes
keepPreviousData: true,
},
);
```

You'll notice that, in the second case, the hook returns an additional item: `pagination`. This can be passed to Raycast's `List` or `Grid` components in order to enable pagination.
Another thing to notice is that the async function receives a [PaginationOptions](#paginationoptions) argument, and returns a specific data format:

```ts
{
data: any[];
hasMore: boolean;
}
```

Every time the promise resolves, the hook needs to figure out if it should paginate further, or if it should stop, and it uses `hasMore` for this.
In addition to this, the hook also needs `data`, and needs it to be an array, because internally it appends it to a list, thus making sure the `data` that the hook _returns_ always contains the data for all of the pages that have been loaded so far.

### Full Example

```tsx
import { setTimeout } from "node:timers/promises";
import { useState } from "react";
import { List } from "@raycast/api";
import { useCachedPromise } from "@raycast/utils";

export default function Command() {
const [searchText, setSearchText] = useState("");

const { isLoading, data, pagination } = useCachedPromise(
(searchText: string) => async (options: { page: number }) => {
await setTimeout(200);
const newData = Array.from({ length: 25 }, (_v, index) => ({
index,
page: options.page,
text: searchText,
}));
return { data: newData, hasMore: options.page < 10 };
},
[searchText],
);

return (
<List isLoading={isLoading} onSearchTextChange={setSearchText} pagination={pagination}>
{data?.map((item) => (
<List.Item
key={`${item.page} ${item.index} ${item.text}`}
title={`Page ${item.page} Item ${item.index}`}
subtitle={item.text}
/>
))}
</List>
);
}
```

## Types

### AsyncState
Expand Down Expand Up @@ -246,3 +346,17 @@ export type MutatePromise<T> = (
},
) => Promise<any>;
```

### PaginationOptions

An object passed to a `PaginatedPromise`, it has two properties:

- `page`: 0-indexed, this it's incremented every time the promise resolves, and is reset whenever `revalidate()` is called.
- `lastItem`: this is a copy of the last item in the `data` array from the last time the promise was executed. Provided for APIs that implement cursor-based pagination.

```ts
export type PaginationOptions<T = any> = {
page: number;
lastItem?: T;
};
```
123 changes: 119 additions & 4 deletions docs/utils-reference/react-hooks/useFetch.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ The last value will be kept between command runs.
## Signature

```ts
function useFetch<T, U>(
url: string,
export function useFetch<V, U, T = V>(
url: RequestInfo,
options?: RequestInit & {
parseResponse?: (response: Response) => Promise<T>;
parseResponse?: (response: Response) => Promise<V>;
mapResult?: (result: V) => { data: T }
initialData?: U;
keepPreviousData?: boolean;
execute?: boolean;
Expand All @@ -33,7 +34,8 @@ function useFetch<T, U>(
With a few options:

- `options` extends [`RequestInit`](https://github.com/nodejs/undici/blob/v5.7.0/types/fetch.d.ts#L103-L117) allowing you to specify a body, headers, etc. to apply to the request.
- `options.parseResponse` is a function that accepts the Response as an argument and returns the data the hooks will return. By default, the hook will return `response.json()` if the response has a JSON `Content-Type` header or `response.text()` otherwise.
- `options.parseResponse` is a function that accepts the Response as an argument and returns the data the hook will return. By default, the hook will return `response.json()` if the response has a JSON `Content-Type` header or `response.text()` otherwise.
- `options.mapResult` is an optional function that accepts whatever `options.parseResponse` returns as an argument, processes the response, and returns an object wrapping the result, i.e. `(response) => { return { data: response> } };`.

Including the [useCachedPromise](./useCachedPromise.md)'s options:

Expand Down Expand Up @@ -164,6 +166,105 @@ export default function Command() {
}
```

## Pagination

{% hint style="info" %}
When paginating, the hook will only cache the result of the first page.
{% endhint %}

The hook has built-in support for pagination. In order to enable pagination, `url`s type needs to change from `RequestInfo` to a function that receives a [PaginationOptions](#paginationoptions) argument, and returns a `RequestInfo`.

In practice, this means going from

```ts
const { isLoading, data } = useFetch(
"https://api.ycombinator.com/v0.1/companies?" + new URLSearchParams({ q: searchText }).toString(),
{
mapResult(result: SearchResult) {
return {
data: result.companies,
};
},
keepPreviousData: true,
initialData: [],
},
);
```

to

```ts
const { isLoading, data, pagination } = useFetch(
(options) =>
"https://api.ycombinator.com/v0.1/companies?" +
new URLSearchParams({ page: String(options.page + 1), q: searchText }).toString(),
{
mapResult(result: SearchResult) {
return {
data: result.companies,
hasMore: result.page < result.totalPages,
};
},
keepPreviousData: true,
initialData: [],
},
);
```

You'll notice that, in the second case, the hook returns an additional item: `pagination`. This can be passed to Raycast's `List` or `Grid` components in order to enable pagination.
Another thing to notice is that `mapResult`, which is normally optional, is actually required when using pagination. Furthermore, its return type is

```ts
{
data: any[],
hasMore?: boolean;
}
```

Every time the URL is fetched, the hook needs to figure out if it should paginate further, or if it should stop, and it uses the `hasMore` for this.
In addition to this, the hook also needs `data`, and needs it to be an array, because internally it appends it to a list, thus making sure the `data` that the hook _returns_ always contains the data for all of the pages that have been fetched so far.

### Full Example

```tsx
import { Icon, Image, List } from "@raycast/api";
import { useFetch } from "@raycast/utils";
import { useState } from "react";

type SearchResult = { companies: Company[]; page: number; totalPages: number };
type Company = { id: number; name: string; smallLogoUrl?: string };
export default function Command() {
const [searchText, setSearchText] = useState("");
const { isLoading, data, pagination } = useFetch(
(options) =>
"https://api.ycombinator.com/v0.1/companies?" +
new URLSearchParams({ page: String(options.page + 1), q: searchText }).toString(),
{
mapResult(result: SearchResult) {
return {
data: result.companies,
hasMore: result.page < result.totalPages,
};
},
keepPreviousData: true,
initialData: [],
},
);

return (
<List isLoading={isLoading} pagination={pagination} onSearchTextChange={setSearchText}>
{data.map((company) => (
<List.Item
key={company.id}
icon={{ source: company.smallLogoUrl ?? Icon.MinusCircle, mask: Image.Mask.RoundedRectangle }}
title={company.name}
/>
))}
</List>
);
}
```

## Types

### AsyncState
Expand Down Expand Up @@ -214,3 +315,17 @@ export type MutatePromise<T> = (
},
) => Promise<any>;
```

### PaginationOptions

An object passed to a `PaginatedRequestInfo`, it has two properties:

- `page`: 0-indexed, this it's incremented every time the promise resolves, and is reset whenever `revalidate()` is called.
- `lastItem`: this is a copy of the last item in the `data` array from the last time the promise was executed. Provided for APIs that implement cursor-based pagination.

```ts
export type PaginationOptions<T = any> = {
page: number;
lastItem?: T;
};
```
101 changes: 101 additions & 0 deletions docs/utils-reference/react-hooks/usePromise.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,93 @@ export default function Command() {
}
```

## Pagination

The hook has built-in support for pagination. In order to enable pagination, `fn`'s type needs to change from

> an asynchronous function or a function that returns a Promise

to

> a function that returns an asynchronous function or a function that returns a Promise

In practice, this means going from

```ts
const { isLoading, data } = usePromise(
async (searchText: string) => {
const data = await getUser(); // or any asynchronous logic you need to perform
return data;
},
[searchText],
);
```

to

```ts
const { isLoading, data, pagination } = usePromise(
(searchText: string) =>
async ({ page, lastItem }) => {
const data = await getUsers(); // or any other asynchronous logic you need to perform
const hasMore = page < 50; //
return { data, hasMore };
},
[searchText],
);
```

You'll notice that, in the second case, the hook returns an additional item: `pagination`. This can be passed to Raycast's `List` or `Grid` components in order to enable pagination.
Another thing to notice is that the async function receives a [PaginationOptions](#paginationoptions) argument, and returns a specific data format:

```ts
{
data: any[];
hasMore: boolean;
}
```

Every time the promise resolves, the hook needs to figure out if it should paginate further, or if it should stop, and it uses `hasMore` for this.
In addition to this, the hook also needs `data`, and needs it to be an array, because internally it appends it to a list, thus making sure the `data` that the hook _returns_ always contains the data for all of the pages that have been loaded so far.

### Full Example

```tsx
import { setTimeout } from "node:timers/promises";
import { useState } from "react";
import { List } from "@raycast/api";
import { usePromise } from "@raycast/utils";

export default function Command() {
const [searchText, setSearchText] = useState("");

const { isLoading, data, pagination } = usePromise(
(searchText: string) => async (options: { page: number }) => {
await setTimeout(200);
const newData = Array.from({ length: 25 }, (_v, index) => ({
index,
page: options.page,
text: searchText,
}));
return { data: newData, hasMore: options.page < 10 };
},
[searchText],
);

return (
<List isLoading={isLoading} onSearchTextChange={setSearchText} pagination={pagination}>
{data?.map((item) => (
<List.Item
key={`${item.page} ${item.index} ${item.text}`}
title={`Page ${item.page} Item ${item.index}`}
subtitle={item.text}
/>
))}
</List>
);
}
```

## Types

### AsyncState
Expand Down Expand Up @@ -194,3 +281,17 @@ export type MutatePromise<T> = (
},
) => Promise<any>;
```

### PaginationOptions

An object passed to a `PaginatedPromise`, it has two properties:

- `page`: 0-indexed, this it's incremented every time the promise resolves, and is reset whenever `revalidate()` is called.
- `lastItem`: this is a copy of the last item in the `data` array from the last time the promise was executed. Provided for APIs that implement cursor-based pagination.

```ts
export type PaginationOptions<T = any> = {
page: number;
lastItem?: T;
};
```
Loading
Loading