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

docs: add isLoading and keepPreviousData pages in v2 #343

Merged
merged 25 commits into from
Sep 4, 2022
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
a151bbe
docs: add the Return Values page
koba04 Aug 24, 2022
1a816e0
docs: add isLoading and keepPreviousData option
koba04 Aug 27, 2022
3d31ece
docs: fix header levels
koba04 Aug 27, 2022
59340e6
docs: add a video for keepPreviousData
koba04 Aug 27, 2022
93eef90
docs: move arguments page to next to return values page
koba04 Aug 30, 2022
e2274cc
docs: update diagrams for returning values
koba04 Aug 30, 2022
ef9ee10
docs: update the performance document to add isLoading
koba04 Aug 31, 2022
fc18ba8
docs: keep the list of return values in the options document
koba04 Aug 31, 2022
b2429c5
use isLoading instead of !data
koba04 Aug 31, 2022
da4caf7
translate options.md into Japanese
koba04 Aug 31, 2022
16abf5b
docs: add a detail link for keepPreviousData
koba04 Sep 1, 2022
8c8ba4f
tweak the description of isLoading
koba04 Sep 1, 2022
41f49dc
revert to move the arguments page
koba04 Sep 2, 2022
3509408
move the return values page into the advanced section
koba04 Sep 2, 2022
c363774
rename the Options page to API Options
koba04 Sep 2, 2022
358eccc
fix links to the return values
koba04 Sep 2, 2022
2dd5497
fix a typo
koba04 Sep 2, 2022
7f79c09
add an excalidraw file for the state machine diagrams
koba04 Sep 3, 2022
c5758bf
rename the page from Return Values to Understanding SWR
koba04 Sep 3, 2022
a07951f
rename the Options page to API
koba04 Sep 3, 2022
83f0d81
translate Understanding SWR into Japanese
koba04 Sep 3, 2022
33814f1
tweak
koba04 Sep 3, 2022
5c01f41
change /docs/options links to /docs/api
koba04 Sep 3, 2022
21f0e80
Update pages/docs/advanced/meta.en-US.json
koba04 Sep 4, 2022
2e5b289
change the link of Understanding SWR
koba04 Sep 4, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.en-US.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"return-values": "Return Values",
koba04 marked this conversation as resolved.
Show resolved Hide resolved
"cache": "Cache",
"performance": "Performance",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.es-ES.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"return-values": "Valores devueltos",
"cache": "Cache",
"performance": "Rendimiento",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ja.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"return-values": "返り値",
"cache": "キャッシュ",
"performance": "パフォーマンス",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ko.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"return-values": "반환 값",
"cache": "캐시",
"performance": "성능",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.pt-BR.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"return-values": "Valores Retornados",
"cache": "Cache",
"performance": "Desempenho",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ru.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"return-values": "Возвращаемые значения",
"cache": "Кеш",
"performance": "Производительность",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.zh-CN.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"return-values": "返回值",
"cache": "缓存",
"performance": "性能",
"react-native": "React Native",
Expand Down
16 changes: 8 additions & 8 deletions pages/docs/advanced/performance.en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -57,25 +57,25 @@ For example, some API responses return a server timestamp that you might want to

## Dependency Collection

`useSWR` returns 3 **stateful** values: `data`, `error` and `isValidating`, each one can be updated independently.
`useSWR` returns 4 **stateful** values: `data`, `error`, `isLoading` and `isValidating`, each one can be updated independently.
For example, if we print those values within a full data-fetching lifecycle, it will be something like this:

```jsx
function App () {
const { data, error, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isValidating)
const { data, error, isLoading, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isLoading, isValidating)
return null
}
```

In the worst case (the first request failed, then the retry was successful), you will see 4 lines of logs:

```js
// console.log(data, error, isValidating)
undefined undefined true // => start fetching
undefined Error false // => end fetching, got an error
undefined Error true // => start retrying
Data undefined false // => end retrying, get the data
// console.log(data, error, isLoading, isValidating)
undefined undefined true true // => start fetching
undefined Error false false // => end fetching, got an error
undefined Error true true // => start retrying
Data undefined false false // => end retrying, get the data
```

The state changes make sense. But that also means our component **rendered 4 times**.
Expand Down
20 changes: 10 additions & 10 deletions pages/docs/advanced/performance.es-ES.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function App() {

```

Cada componente `<Avatar/>` tiene un hook `useSWR` en su interior. Dado que tienen el mismo key SWR y
Cada componente `<Avatar/>` tiene un hook `useSWR` en su interior. Dado que tienen el mismo key SWR y
que se renderizan casi al mismo tiempo, **sólo se hará 1 solicitud de red**.

Se pueden reutilizar los hooks de datos (como `useUser` en el ejemplo anterior) en todas partes, sin preocuparse por el rendimiento
Expand All @@ -64,14 +64,14 @@ Por ejemplo, algunas respuestas de la API devuelven una marca de tiempo del serv

## Colección de dependencias

`useSWR` devuelve 3 valores de **estado**: `data`, `error` y `isValidating` cada uno de ellos puede actualizarse de forma independientemente.
`useSWR` devuelve 4 valores de **estado**: `data`, `error`, `isLoading` y `isValidating` cada uno de ellos puede actualizarse de forma independientemente.
Por ejemplo, si imprimimos esos valores dentro de un ciclo de vida completo de obtención de datos, será algo como esto:

```jsx

function App () {
const { data, error, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isValidating)
const { data, error, isLoading, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isLoading, isValidating)
return null
}

Expand All @@ -80,12 +80,12 @@ function App () {
En el peor de los casos (si la primera solicitud falló, entonces el reintento fue exitoso). Se verán 4 líneas de registros:

```js
// console.log(data, error, isValidating)
// console.log(data, error, isLoading, isValidating)

undefined undefined true // => start fetching
undefined Error false // => end fetching, got an error
undefined Error true // => start retrying
Data undefined false // => end retrying, get the data
undefined undefined true true // => start fetching
undefined Error false false // => end fetching, got an error
undefined Error true true // => start retrying
Data undefined false false // => end retrying, get the data
```

Los cambios de estado tienen sentido. Pero eso también significa que nuestro componente se **renderizo 4 veces.**
Expand All @@ -112,7 +112,7 @@ Data // => end retrying, get the data
El mismo proceso ha ocurrido internamente, hubo un error de la primera solicitud, entonces tenemos los datos del reintento.
Sin embargo, **SWR sólo actualiza los estados que utiliza el componente**, que ahora sólo es `data`.

Si no se utilizan siempre estos 3 estados, ya se está beneficiando de esta función. En [Vercel](https://vercel.com), esta optimización se
Si no se utilizan siempre estos 3 estados, ya se está beneficiando de esta función. En [Vercel](https://vercel.com), esta optimización se
traduce en un 60% menos de repeticiones.

## Tree Shaking
Expand Down
16 changes: 8 additions & 8 deletions pages/docs/advanced/performance.ja.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -57,25 +57,25 @@ SWR は、デフォルトでデータの変更を**詳細に比較**します。

## 依存関係のコレクション

`useSWR` が返す三つの**ステートフルな**値、つまり `data` 、`error` 、そして `isValidating` は、それぞれが独立して更新されます。
`useSWR` が返す四つの**ステートフルな**値、つまり `data` 、`error` `isLoading`、そして `isValidating` は、それぞれが独立して更新されます。
たとえば、完全なデータフェッチのライフサイクル内でこれらの値を出力すると次のようになります:

```jsx
function App () {
const { data, error, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isValidating)
const { data, error, isLoading, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isLoading, isValidating)
return null
}
```

最悪の場合(最初のリクエストが失敗し、次に再試行が成功した場合)には、4 行のログが表示されます:

```js
// console.log(data, error, isValidating)
undefined undefined true // => フェッチの開始
undefined Error false // => フェッチの完了、エラーを取得
undefined Error true // => 再試行の開始
Data undefined false // => 再試行の完了、データを取得
// console.log(data, error, isLoading, isValidating)
undefined undefined true true // => フェッチの開始
undefined Error false false // => フェッチの完了、エラーを取得
undefined Error false true // => 再試行の開始
Data undefined false false // => 再試行の完了、データを取得
```

この状態変化は理にかなっています。しかし、それはまた、コンポーネントが **4 回レンダリングされる**ことを意味します。
Expand Down
20 changes: 10 additions & 10 deletions pages/docs/advanced/performance.ko.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

SWR은 모든 종류의 웹 앱에서 중요한 기능들을 제공하므로 **성능**을 가장 중요시합니다.

SWR의 내장 **캐싱**과 **[중복 제거](/advanced/performance#deduplication)** 기능은 불필요한 네트워크 요청을 생략하지만,
SWR의 내장 **캐싱**과 **[중복 제거](/advanced/performance#deduplication)** 기능은 불필요한 네트워크 요청을 생략하지만,
`useSWR` hook 자체의 성능은 여전히 중요합니다. 복잡한 앱에서는 단일 페이지 렌더링에 `useSWR`이 수백 번 호출될 수 있습니다.

SWR은 앱에서 다음을 보장합니다:
Expand All @@ -14,7 +14,7 @@ SWR은 앱에서 다음을 보장합니다:

## 중복 제거

앱에서 SWR hook을 재사용하는 것은 아주 일반적입니다. 예를 들어, 앱이 현재 사용자의 아바타를 다섯 번 렌더링한다면:
앱에서 SWR hook을 재사용하는 것은 아주 일반적입니다. 예를 들어, 앱이 현재 사용자의 아바타를 다섯 번 렌더링한다면:

```jsx
function useUser () {
Expand Down Expand Up @@ -56,25 +56,25 @@ SWR은 기본적으로 데이터 변경을 **깊게 비교**합니다. `data`

## 의존성 수집

`useSWR`은 세 개의 **스테이트풀** 값을 반환합니다: `data`, `error`, `isValidating`, 각각은 독립적으로 업데이트됩니다.
`useSWR` returns 4 **stateful** values: `data`, `error`, `isLoading` and `isValidating`, each one can be updated independently.
예를 들어, 전체 데이터 가져오기 생명 주기에서 이 값들을 출력한다면 뭔가 다음과 같은 것입니다.

```jsx
function App () {
const { data, error, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isValidating)
const { data, error, isLoading, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isLoading, isValidating)
return null
}
```

최악의 경우에는(첫 번째 요청이 실패하고, 재시도가 성공), 네 줄의 로그가 보일 것입니다.

```js
// console.log(data, error, isValidating)
undefined undefined true // => 가져오기 시작
undefined Error false // => 가져오기 종료, 에러 발생
undefined Error true // => 재시도 시작
Data undefined false // => 재시도 종료, 데이터 얻음
// console.log(data, error, isLoading, isValidating)
undefined undefined true true // => 가져오기 시작
undefined Error false false // => 가져오기 종료, 에러 발생
undefined Error true true // => 재시도 시작
Data undefined false false // => 재시도 종료, 데이터 얻음
```

상태 변화는 말이 됩니다. 하지만 이는 컴포넌트가 **네 번 리렌더링 되었음**을 의미하기도 합니다.
Expand Down