Skip to content

Commit

Permalink
docs: add preload API documentation in v2 (#336)
Browse files Browse the repository at this point in the history
* Empty commit for v2 branch

* docs: add preload API documentation in v2

* Apply suggestions from code review

Co-authored-by: Jiachi Liu <inbox@huozhi.im>

* Update pages/docs/prefetching.en-US.md

Co-authored-by: Jiachi Liu <inbox@huozhi.im>

* apply suggestions to other languages

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
  • Loading branch information
koba04 and huozhi authored Aug 30, 2022
1 parent e81afb7 commit fa6488c
Show file tree
Hide file tree
Showing 14 changed files with 598 additions and 159 deletions.
73 changes: 66 additions & 7 deletions pages/docs/prefetching.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,79 @@ It will prefetch the data when the HTML loads, even before JavaScript starts to

## Programmatically Prefetch

Sometimes, you want to preload a resource conditionally. For example, preloading the data when the user is [hovering](https://github.com/GoogleChromeLabs/quicklink) [a](https://github.com/guess-js/guess) [link](https://instant.page). The most intuitive way is to have a function to refetch and set the cache via the global [mutate](/docs/mutation):
SWR provides the `preload` API to prefetch the resources programmatically and store the results in the cache. `preload` accepts `key` and `fetcher` as the arguments. You can call `preload` even outside of React.

```js
import { mutate } from 'swr'
```jsx
import { useState } from 'react'
import useSWR, { preload } from 'swr'

const fetcher = (url) => fetch(url).then((res) => res.json())

// Preload the resource before rendering the User component below,
// this prevents potential waterfalls in your application.
// You can also start preloading when hovering the button or link, too.
preload('/api/user', fetcher)

function User() {
const { data } = useSWR('/api/user', fetcher)
...
}

function prefetch () {
mutate('/api/data', fetch('/api/data').then(res => res.json()))
// the second parameter is a Promise
// SWR will use the result when it resolves
export default function App() {
const [show, setShow] = useState(false)
return (
<div>
<button onClick={() => setShow(true)}>Show User</button>
{show ? <User /> : null}
</div>
)
}
```

You can also preload it when hovering the button:

```jsx
function App({ userId }) {
const [show, setShow] = useState(false)
return (
<div>
<button
onClick={() => setShow(true)}
onHover={() => preload('/api/user?id=' + userId, fetcher)}
>
Show User
</button>
{show ? <User /> : null}
</div>
)
}
```

Together with techniques like [page prefetching](https://nextjs.org/docs/api-reference/next/router#routerprefetch) in Next.js, you will be able to load both next page and data instantly.

In Suspense mode, you should utilize `preload` to avoid waterfall problems.

```jsx
import useSWR, { preload } from 'swr'

// should call before rendering
preload('/api/user', fetcher);
preload('/api/movies', fetcher);

const Page = () => {
// The below useSWR hooks will suspend the rendering, but the requests to `/api/user` and `/api/movies` have started by `preload` already,
// so the waterfall problem doesn't happen.
const { data: user } = useSWR('/api/user', fetcher, { suspense: true });
const { data: movies } = useSWR('/api/movies', fetcher, { suspense: true });
return (
<div>
<User user={user} />
<Movies movies={movies} />
</div>
);
}
```

## Pre-fill Data

If you want to pre-fill existing data into the SWR cache, you can use the `fallbackData` option. For example:
Expand Down
73 changes: 66 additions & 7 deletions pages/docs/prefetching.es-ES.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,79 @@ Se precargarán los datos cuando se cargue el HTML, incluso antes de que el Java

## Programmatically Prefetch

A veces, se quiere precargar un recurso de forma condicional. Por ejemplo, precargar los datos cuando el usuario está [hovering](https://github.com/GoogleChromeLabs/quicklink) [a](https://github.com/guess-js/guess) [link](https://instant.page). La forma más intuitiva es tener una función que recupere y fije la caché a través de la función global [mutate](/docs/mutation):
SWR provides the `preload` API to prefetch the resources programmatically and store the results in the cache. `preload` accepts `key` and `fetcher` as the arguments. You can call `preload` even outside of React.

```js
import { mutate } from 'swr'
```jsx
import { useState } from 'react'
import useSWR, { preload } from 'swr'

const fetcher = (url) => fetch(url).then((res) => res.json())

// Preload the resource before rendering the User component below,
// this prevents potential waterfalls in your application.
// You can also start preloading when hovering the button or link, too.
preload('/api/user', fetcher)

function User() {
const { data } = useSWR('/api/user', fetcher)
...
}

function prefetch () {
mutate('/api/data', fetch('/api/data').then(res => res.json()))
// el segundo parametró es una Promise
// SWR utilizará el resultado cuando resuelva
export default function App() {
const [show, setShow] = useState(false)
return (
<div>
<button onClick={() => setShow(true)}>Show User</button>
{show ? <User /> : null}
</div>
)
}
```

You can also preload it when hovering the button:

```jsx
function App({ userId }) {
const [show, setShow] = useState(false)
return (
<div>
<button
onClick={() => setShow(true)}
onHover={() => preload('/api/user?id=' + userId, fetcher)}
>
Show User
</button>
{show ? <User /> : null}
</div>
)
}
```

Junto con técnicas como [page prefetching](https://nextjs.org/docs/api-reference/next/router#routerprefetch) en Next.js, podrás cargar tanto la siguiente página como los datos al instante.

In Suspense mode, you should utilize `preload` to avoid waterfall problems.

```jsx
import useSWR, { preload } from 'swr'

// should call before rendering
preload('/api/user', fetcher);
preload('/api/movies', fetcher);

const Page = () => {
// The below useSWR hooks will suspend the rendering, but the requests to `/api/user` and `/api/movies` have started by `preload` already,
// so the waterfall problem doesn't happen.
const { data: user } = useSWR('/api/user', fetcher, { suspense: true });
const { data: movies } = useSWR('/api/movies', fetcher, { suspense: true });
return (
<div>
<User user={user} />
<Movies movies={movies} />
</div>
);
}
```

## Pre-fill Data

If you want to pre-fill existing data into the SWR cache, you can use the `fallbackData` option. For example:
Expand Down
73 changes: 66 additions & 7 deletions pages/docs/prefetching.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,79 @@ JavaScriptのダウンロードが開始される前であっても、HTMLの読

## プログラムによるプリフェッチ

しばしば、リソースを条件付きでプリロードしたい場合があります。たとえば、ユーザーが [hovering](https://github.com/GoogleChromeLabs/quicklink) [a](https://github.com/guess-js/guess) [link](https://instant.page) にカーソルを合わせたときにデータをプリロードするような場合です。最も直観的な方法は、グローバルミューテートを使ってキャッシュを再取得し、設定する関数を作成することです
SWR は `preload` というデータをプログラマブルにプリフェッチして結果をキャッシュに保存する API を提供しています。`preload``key``fetcher` を引数として受け取ります。`preload` は React の外からも呼ぶことが可能です

```js
import { mutate } from 'swr'
```jsx
import { useState } from 'react'
import useSWR, { preload } from 'swr'

const fetcher = (url) => fetch(url).then((res) => res.json())

// User コンポーネントがレンダリングされる前にプリロードします
// これによりウォーターフォール問題の発生を避けられます
// また、ボタンやリンクにホバーされたタイミングでプリロードを開始することもできます
preload('/api/user', fetcher)

function User() {
const { data } = useSWR('/api/user', fetcher)
...
}

function prefetch () {
mutate('/api/data', fetch('/api/data').then(res => res.json()))
// 2番目のパラメータはPromise
// SWRは、その結果を解決する際に使用します。
export default function App() {
const [show, setShow] = useState(false)
return (
<div>
<button onClick={() => setShow(true)}>Show User</button>
{show ? <User /> : null}
</div>
)
}
```

またボタンをホバーしたタイミングでプリロードすることもできます

```jsx
function App({ userId }) {
const [show, setShow] = useState(false)
return (
<div>
<button
onClick={() => setShow(true)}
onHover={() => preload('/api/user?id=' + userId, fetcher)}
>
Show User
</button>
{show ? <User /> : null}
</div>
)
}
```

Next.js の [ページプリフェッチ](https://nextjs.org/docs/api-reference/next/router#routerprefetch) などの技術と合わせて、次のページとデータの両方を瞬時に読み込むことができるようになります。

サスペンスモードでは特に `preload` を利用してウォーターフォール問題を避けた方がいいでしょう。

```jsx
import useSWR, { preload } from 'swr'

// レンダリング前に呼ぶべき
preload('/api/user', fetcher);
preload('/api/movies', fetcher);

const Page = () => {
// 下記の useSWR はレンダリングを中断しますが、`/api/user` と`/api/movies` に対するリクエストは `preload` によって開始されています
// そのため、ウォーターフォール問題は起きません
const { data: user } = useSWR('/api/user', fetcher, { suspense: true });
const { data: movies } = useSWR('/api/movies', fetcher, { suspense: true });
return (
<div>
<User user={user} />
<Movies movies={movies} />
</div>
);
}
```

## 事前データ

もし既に存在しているデータを SWR にキャッシュしたい場合は、 `fallbackData` オプションを使うことができます。たとえば:
Expand Down
73 changes: 66 additions & 7 deletions pages/docs/prefetching.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,79 @@ HTML `<head>` 안에 넣기만 하면 됩니다. 쉽고 빠르며 네이티브

## 프로그래밍 방식으로 프리패치

조건부로 리소스를 프리로드 하길 원할 수도 있습니다. 예를 들면, 사용자가 [어떤](https://github.com/guess-js/guess) [링크](https://instant.page)[호버링](https://github.com/GoogleChromeLabs/quicklink)할 때 데이터 프리로딩. 가장 직관적인 방법은 전역 [mutate](/docs/mutation)를 통해 캐시를 다시 가져오고 설정하는 함수를 두는 것입니다.
SWR provides the `preload` API to prefetch the resources programmatically and store the results in the cache. `preload` accepts `key` and `fetcher` as the arguments. You can call `preload` even outside of React.

```js
import { mutate } from 'swr'
```jsx
import { useState } from 'react'
import useSWR, { preload } from 'swr'

const fetcher = (url) => fetch(url).then((res) => res.json())

// Preload the resource before rendering the User component below,
// this prevents potential waterfalls in your application.
// You can also start preloading when hovering the button or link, too.
preload('/api/user', fetcher)

function User() {
const { data } = useSWR('/api/user', fetcher)
...
}

function prefetch () {
mutate('/api/data', fetch('/api/data').then(res => res.json()))
// 두 번째 파라미터는 Promise입니다
// 프로미스가 이행될 때 SWR은 그 결과를 사용합니다
export default function App() {
const [show, setShow] = useState(false)
return (
<div>
<button onClick={() => setShow(true)}>Show User</button>
{show ? <User /> : null}
</div>
)
}
```

You can also preload it when hovering the button:

```jsx
function App({ userId }) {
const [show, setShow] = useState(false)
return (
<div>
<button
onClick={() => setShow(true)}
onHover={() => preload('/api/user?id=' + userId, fetcher)}
>
Show User
</button>
{show ? <User /> : null}
</div>
)
}
```

Next.js내의 [페이지 프리패칭](https://nextjs.org/docs/api-reference/next/router#routerprefetch)같은 기술과 함께 다음 페이지와 데이터 모두를 즉시 로드할 수 있습니다.

In Suspense mode, you should utilize `preload` to avoid waterfall problems.

```jsx
import useSWR, { preload } from 'swr'

// should call before rendering
preload('/api/user', fetcher);
preload('/api/movies', fetcher);

const Page = () => {
// The below useSWR hooks will suspend the rendering, but the requests to `/api/user` and `/api/movies` have started by `preload` already,
// so the waterfall problem doesn't happen.
const { data: user } = useSWR('/api/user', fetcher, { suspense: true });
const { data: movies } = useSWR('/api/movies', fetcher, { suspense: true });
return (
<div>
<User user={user} />
<Movies movies={movies} />
</div>
);
}
```

## 데이터 프리필

이미 존재하는 데이터를 SWR 캐시에 미리 채우길 원한다면, `fallbackData` 옵션을 사용할 수 있습니다. 예를 들면:
Expand Down
Loading

0 comments on commit fa6488c

Please sign in to comment.