From beddbd4aac41d8b3343739413eb6c050b20a0832 Mon Sep 17 00:00:00 2001 From: Toru Kobayashi Date: Fri, 23 Feb 2024 01:10:39 +0900 Subject: [PATCH] docs: add revalidate as a function --- pages/docs/mutation.en-US.mdx | 2 +- pages/docs/mutation.es-ES.mdx | 2 +- pages/docs/mutation.fr-FR.mdx | 2 +- pages/docs/mutation.ja.mdx | 2 +- pages/docs/mutation.ko.mdx | 2 +- pages/docs/mutation.pt-BR.mdx | 2 +- pages/docs/mutation.ru.mdx | 2 +- pages/docs/mutation.zh-CN.mdx | 2 +- pages/docs/pagination.en-US.mdx | 24 ++++++++++++++++++++++++ pages/docs/pagination.es-ES.mdx | 24 ++++++++++++++++++++++++ pages/docs/pagination.fr-FR.mdx | 24 ++++++++++++++++++++++++ pages/docs/pagination.ja.mdx | 24 ++++++++++++++++++++++++ pages/docs/pagination.ko.mdx | 24 ++++++++++++++++++++++++ pages/docs/pagination.pt-BR.mdx | 24 ++++++++++++++++++++++++ pages/docs/pagination.ru.mdx | 24 ++++++++++++++++++++++++ pages/docs/pagination.zh-CN.mdx | 24 ++++++++++++++++++++++++ 16 files changed, 200 insertions(+), 8 deletions(-) diff --git a/pages/docs/mutation.en-US.mdx b/pages/docs/mutation.en-US.mdx index cbbb83f0..1c7a70bc 100644 --- a/pages/docs/mutation.en-US.mdx +++ b/pages/docs/mutation.en-US.mdx @@ -104,7 +104,7 @@ It broadcasts to SWR hooks under the same [cache provider](/docs/advanced/cache) - `data`: data to update the client cache, or an async function for the remote mutation - `options`: accepts the following options - `optimisticData`: data to immediately update the client cache, or a function that receives current data and returns the new client cache data, usually used in optimistic UI. - - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. + - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. If set to a function, the function receives `data` and `key`. - `populateCache = true`: should the result of the remote mutation be written to the cache, or a function that receives new result and current result as arguments and returns the mutation result. - `rollbackOnError = true`: should the cache rollback if the remote mutation errors, or a function that receives the error thrown from fetcher as arguments and returns a boolean whether should rollback or not. - `throwOnError = true`: should the mutate call throw the error when fails. diff --git a/pages/docs/mutation.es-ES.mdx b/pages/docs/mutation.es-ES.mdx index 483e12fd..2c9a8c4e 100644 --- a/pages/docs/mutation.es-ES.mdx +++ b/pages/docs/mutation.es-ES.mdx @@ -105,7 +105,7 @@ It broadcasts to SWR hooks under the same [cache provider](/docs/advanced/cache) - `data`: data to update the client cache, or an async function for the remote mutation - `options`: accepts the following options - `optimisticData`: data to immediately update the client cache, or a function that receives current data and returns the new client cache data, usually used in optimistic UI. - - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. + - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. If set to a function, the function receives `data` and `key`. - `populateCache = true`: should the result of the remote mutation be written to the cache, or a function that receives new result and current result as arguments and returns the mutation result. - `rollbackOnError = true`: should the cache rollback if the remote mutation errors, or a function that receives the error thrown from fetcher as arguments and returns a boolean whether should rollback or not. - `throwOnError = true`: should the mutate call throw the error when fails. diff --git a/pages/docs/mutation.fr-FR.mdx b/pages/docs/mutation.fr-FR.mdx index c1c836ad..39791529 100644 --- a/pages/docs/mutation.fr-FR.mdx +++ b/pages/docs/mutation.fr-FR.mdx @@ -102,7 +102,7 @@ function App () { - `data`: données pour mettre à jour le cache client, ou une fonction asynchrone pour la mutation distante - `options`: accepte les options suivantes - `optimisticData`: données pour mettre à jour immédiatement le cache client, ou une fonction qui reçoit les données actuelles et renvoie les nouvelles données du cache client, généralement utilisée dans l'UI optimiste. - - `revalidate = true`: est-ce que le cache doit se révalider une fois que la mise à jour asynchrone est résolue. + - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. If set to a function, the function receives `data` and `key`. - `populateCache = true`: est-ce que le résultat de la mutation distante doit être écrit dans le cache, ou une fonction qui reçoit le nouveau résultat et le résultat actuel comme arguments et renvoie le résultat de la mutation. - `rollbackOnError = true`: est-ce que le cache doit revenir à l'état précédent si la mutation distante échoue, ou une fonction qui reçoit l'erreur renvoyée par la fonction de récupération comme arguments et renvoie un booléen pour savoir si le cache doit revenir à l'état précédent ou non. - `throwOnError = true`: est-ce que l'appel à la mutation doit renvoyer l'erreur quand elle échoue. diff --git a/pages/docs/mutation.ja.mdx b/pages/docs/mutation.ja.mdx index fe10b581..c05145f3 100644 --- a/pages/docs/mutation.ja.mdx +++ b/pages/docs/mutation.ja.mdx @@ -105,7 +105,7 @@ import { Callout } from 'nextra-theme-docs' - `data`: クライアントキャッシュを更新するためのデータ、またはリモートミューテーションのための非同期関数 - `options`: 下記のオプションを受け取ります - `optimisticData`: クライアントキャッシュを即座に更新するためのデータ、または現在のデータを受け取り新しいクライアントキャッシュデータを返す関数。楽観的 UI のために使われます - - `revalidate = true`: 非同期の更新処理を完了した後にキャッシュの再検証を行うかどうか + - `revalidate = true`: 非同期の更新処理を完了した後にキャッシュの再検証を行うかどうか。関数を渡した場合 `data` と `key` を受け取ります - `populateCache = true`: リモートミューテーションの結果をキャッシュに書き込むかどうか、またはリモートミューテーションの結果と現在のデータを引数として受け取り、ミューテーションの結果を返す関数 - `rollbackOnError = true`: リモートミューテーションがエラーだった場合にキャッシュをロールバックするかどうか、または発生したエラーを引数として受け取りロールバックするかどうかの真偽値を返す関数 - `throwOnError = true`: ミューテートの呼び出しが失敗した場合にエラーを投げるかどうか diff --git a/pages/docs/mutation.ko.mdx b/pages/docs/mutation.ko.mdx index 0593dc82..87819780 100644 --- a/pages/docs/mutation.ko.mdx +++ b/pages/docs/mutation.ko.mdx @@ -103,7 +103,7 @@ import { Callout } from 'nextra-theme-docs' - `data`: 데이터를 사용하여 클라이언트 캐시를 업데이트 하거나 클라이언트에서 서버로 데이터를 보내, 서버에서 데이터를 변경하는 작업(remote mutation)을 위한 비동기 함수를 사용할 수 있습니다. - `options`: 다음 옵션을 허용합니다. - `optimisticData`: 데이터를 즉시 업데이트 하는 함수 또는 현재 데이터를 수신하여 새 클라이언트 캐시를 반환하는 함수로, 일반적으로 optimistic UI에서 사용 - - `revalidate = true`: 비동기 업데이트가 완료되면 캐시의 유효성을 다시 검사하는 데 사용 + - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. If set to a function, the function receives `data` and `key`. - `populateCache = true`: remote mutation 결과를 캐시에 기록하거나, 새 결과와 현재 결과를 인자로 받아 mutation 결과를 반환하는 함수를 호출할 수 있습니다. - `rollbackOnError = true`: remote mutation 과정에서 오류가 발생하면 캐시를 롤백해야 하는지, fetcher에서 던져진 오류를 인자로 받아 롤백할지에 대한 여부를 boolean으로 반환하는 함수를 지정할 수 있습니다. - `throwOnError = true`: 호출이 실패했을 때 오류를 발생시킬 수 있습니다. diff --git a/pages/docs/mutation.pt-BR.mdx b/pages/docs/mutation.pt-BR.mdx index 5245964a..455ad0ce 100644 --- a/pages/docs/mutation.pt-BR.mdx +++ b/pages/docs/mutation.pt-BR.mdx @@ -102,7 +102,7 @@ O hook transmite para todos os hooks SWR sob o mesmo escopo de [provedor de cach - `data`: dados para atualizar o cache do cliente, ou uma função assíncrona para mutação remota - `options`: aceita as seguintes opções - `optimisticData`: dados para imediatamente atualizar o cache do cliente, ou uma função que recebe os dados atuais e retorna os novos dados do cache do cliente, normalmente usado para UI otimista. - - `revalidate = true`: o cache deve revalidar uma vez que a atualização assíncrona resolve. + - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. If set to a function, the function receives `data` and `key`. - `populateCache = true`: o resultado da mutação remota será escrita no cache, ou uma função que recebe o novo resultado e o resultado atual como argumentos e retorna o resultado da mutação. - `rollbackOnError = true`: o cache deve reverter se a mutação remota der erro, ou uma função que recebe o erro lançado pelo fetcher como argumentos e retorna um boolean se deve reverter ou não. - `throwOnError = true`: a chamada de mutação deve lançar um erro quando falhar diff --git a/pages/docs/mutation.ru.mdx b/pages/docs/mutation.ru.mdx index 16b1c9e9..6844ab0d 100644 --- a/pages/docs/mutation.ru.mdx +++ b/pages/docs/mutation.ru.mdx @@ -105,7 +105,7 @@ import { Callout } from 'nextra-theme-docs' - `data`: данные для обновления кеша клиента или асинхронная функция для удаленной мутации - `options`: принимает следующие опции - `optimisticData`: данные для немедленного обновления кеша клиента или функция, которая получает текущие данные и возвращает новые данные кеша клиента, обычно используемые в оптимистичном UI. - - `revalidate = true`: должен ли кеш ревалидироваться после разрешения асинхронного обновления. + - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. If set to a function, the function receives `data` and `key`. - `populateCache = true`: следует ли записывать результат удаленной мутации в кеш, или функция, которая получает в качестве аргументов новый результат и текущий результат и возвращает результат мутации. - `rollbackOnError = true`: должен ли кеш откатиться, при сбое удаленной мутации, или функция, которая получает в качестве аргументов ошибку, выданную fetcher-ом, и возвращает логическое значение, следует ли выполнять откат или нет. - `throwOnError = true`: должен ли вызов мутации вызывать ошибку при сбое. diff --git a/pages/docs/mutation.zh-CN.mdx b/pages/docs/mutation.zh-CN.mdx index 4fd896aa..0db4cf56 100644 --- a/pages/docs/mutation.zh-CN.mdx +++ b/pages/docs/mutation.zh-CN.mdx @@ -102,7 +102,7 @@ import { Callout } from 'nextra-theme-docs' - `data`:用于更新客户端缓存的数据,或者是一个用于进行远程数据更改的异步函数。 - `options`:接受下列选项 - `optimisticData`:用于立即更新客户端缓存的数据,或是一个接受当前数据并返回新的客户端缓存数据的函数,通常用于乐观 UI。 - - `revalidate = true`:一旦异步更新完成,重新验证缓存。 + - `revalidate = true`: should the cache revalidate once the asynchronous update resolves. If set to a function, the function receives `data` and `key`. - `populateCache = true`:将远程数据更改的结果写入缓存,或者将接收新结果和当前结果作为参数并返回数据更改结果的函数。 - `rollbackOnError = true`:如果远程数据更改失败,缓存会回滚。或者接受一个函数,它接收从 fetcher 抛出的错误作为参数,并返回一个布尔值判断是否应该回滚。 - `throwOnError = true`:数据更改失败时抛出错误。 diff --git a/pages/docs/pagination.en-US.mdx b/pages/docs/pagination.en-US.mdx index e511a276..c41b8640 100644 --- a/pages/docs/pagination.en-US.mdx +++ b/pages/docs/pagination.en-US.mdx @@ -346,6 +346,30 @@ function App () { The `previousPageData` argument of the `getKey` function becomes `null` when you enable the `parallel` option. +### Revalidate Specific Pages [#revalidate-specific-pages] + + + Please update to the latest version (≥ 2.2.5) to use this API. + + +The default behavior of the mutation of `useSWRInfinite` is to revalidate all pages that have been loaded. But you might want to revalidate only the specific pages that have been changed. You can revalidate only specific pages by passing a function to the `revalidate` option. + +The `revalidate` function is called for each page. + +```jsx +function App() { + const { mutate, size } = useSWRInfinite( + (index) => [`/api/?page=${index + 1}`, index + 1], + fetcher + ); + + mutate({ + // only revalidate the last page + revalidate: (data, [url, page]) => page === size + }); +} +``` + ### Global Mutate with `useSWRInfinite` [#global-mutate-with-useswrinfinite] `useSWRInfinite` stores all page data into the cache with a special cache key along with each page data, so you have to use `unstable_serialize` in `swr/infinite` to revalidate the data with the global mutate. diff --git a/pages/docs/pagination.es-ES.mdx b/pages/docs/pagination.es-ES.mdx index c2b4d124..5596fe60 100644 --- a/pages/docs/pagination.es-ES.mdx +++ b/pages/docs/pagination.es-ES.mdx @@ -348,6 +348,30 @@ function App () { The `previousPageData` argument of the `getKey` function becomes `null` when you enable the `parallel` option. +### Revalidate Specific Pages [#revalidate-specific-pages] + + + Please update to the latest version (≥ 2.2.5) to use this API. + + +The default behavior of the mutation of `useSWRInfinite` is to revalidate all pages that have been loaded. But you might want to revalidate only the specific pages that have been changed. You can revalidate only specific pages by passing a function to the `revalidate` option. + +The `revalidate` function is called for each page. + +```jsx +function App() { + const { mutate, size } = useSWRInfinite( + (index) => [`/api/?page=${index + 1}`, index + 1], + fetcher + ); + + mutate({ + // only revalidate the last page + revalidate: (data, [url, page]) => page === size + }); +} +``` + ### Global Mutate with `useSWRInfinite` [#global-mutate-with-useswrinfinite] `useSWRInfinite` stores all page data into the cache with a special cache key along with each page data, so you have to use `unstable_serialize` in `swr/infinite` to revalidate the data with the global mutate. diff --git a/pages/docs/pagination.fr-FR.mdx b/pages/docs/pagination.fr-FR.mdx index cc370c4b..b71441c0 100644 --- a/pages/docs/pagination.fr-FR.mdx +++ b/pages/docs/pagination.fr-FR.mdx @@ -335,6 +335,30 @@ function App () { L'argument `previousPageData` de la fonction `getKey` devient `null` quand vous activez l'option `parallel`. +### Revalidate Specific Pages [#revalidate-specific-pages] + + + Please update to the latest version (≥ 2.2.5) to use this API. + + +The default behavior of the mutation of `useSWRInfinite` is to revalidate all pages that have been loaded. But you might want to revalidate only the specific pages that have been changed. You can revalidate only specific pages by passing a function to the `revalidate` option. + +The `revalidate` function is called for each page. + +```jsx +function App() { + const { mutate, size } = useSWRInfinite( + (index) => [`/api/?page=${index + 1}`, index + 1], + fetcher + ); + + mutate({ + // only revalidate the last page + revalidate: (data, [url, page]) => page === size + }); +} +``` + ### Mutation Globale avec `useSWRInfinite` [#global-mutate-with-useswrinfinite] `useSWRInfinite` stocke toutes les données de page dans le cache avec une clé de cache spéciale avec chaque donnée de page, donc vous devez utiliser `unstable_serialize` dans `swr/infinite` pour revalider les données avec la mutation globale. diff --git a/pages/docs/pagination.ja.mdx b/pages/docs/pagination.ja.mdx index 9f10d7f1..6046cc53 100644 --- a/pages/docs/pagination.ja.mdx +++ b/pages/docs/pagination.ja.mdx @@ -346,6 +346,30 @@ function App () { `parallel` オプションを有効にした場合、`getKey` 関数の `previousPageData` 引数は `null` になります。 +### 特定のページのみ再検証する [#revalidate-specific-pages] + + + この API を利用するには最新バージョン (≥ 2.2.5) に更新してください。 + + +`useSWRInfinite` のミューテーションのデフォルトの挙動はすでにロードされた全てのページを再検証することです。しかし、変更されたページのみを再検証したいこともあります。`revalidate` オプションに関数を渡すことで特定のページのみを再検証できます。 + +`useSWRInfinite` の `revadalite` オプションに関数を渡した場合、この関数はページ毎に呼ばれます。 + +```jsx +function App() { + const { mutate, size } = useSWRInfinite( + (index) => [`/api/?page=${index + 1}`, index + 1], + fetcher + ); + + mutate({ + // 最後のページのみを再検証する + revalidate: (data, [url, page]) => page === size + }); +} +``` + ### Global Mutate with `useSWRInfinite` [#global-mutate-with-useswrinfinite] `useSWRInfinite` は各ページのデータに加え、全てのページデータを特別な形式のキーでキャッシュに保存するため、グローバルなミューテートを使い再検証するためには、`swr/infinite` にある `unstable_serialize` を使う必要があります。 diff --git a/pages/docs/pagination.ko.mdx b/pages/docs/pagination.ko.mdx index 6ae376c6..f2b391ff 100644 --- a/pages/docs/pagination.ko.mdx +++ b/pages/docs/pagination.ko.mdx @@ -346,10 +346,34 @@ function App () { The `previousPageData` argument of the `getKey` function becomes `null` when you enable the `parallel` option. +### Revalidate Specific Pages [#revalidate-specific-pages] + + + Please update to the latest version (≥ 2.2.5) to use this API. + + +The default behavior of the mutation of `useSWRInfinite` is to revalidate all pages that have been loaded. But you might want to revalidate only the specific pages that have been changed. You can revalidate only specific pages by passing a function to the `revalidate` option. + +```jsx +function App() { + const { mutate, size } = useSWRInfinite( + (index) => [`/api/?page=${index + 1}`, index + 1], + fetcher + ); + + mutate({ + // only revalidate the last page + revalidate: (data, [url, page]) => page === size + }); +} +``` + ### `useSWRInfinite`를 사용한 Global Mutate [#global-mutate-with-useswrinfinite] `useSWRInfinite`는 모든 페이지 데이터를 각 페이지 데이터와 함께 특수 캐시 키로 저장하므로 global mutate로 데이터를 다시 감증하려면 `swr/infinite`에서 `unstable_serialize`를 사용해야 합니다. +The `revalidate` function is called for each page. + ```jsx import { useSWRConfig } from "swr" import { unstable_serialize } from "swr/infinite" diff --git a/pages/docs/pagination.pt-BR.mdx b/pages/docs/pagination.pt-BR.mdx index 1c1dd7dc..600bbcf5 100644 --- a/pages/docs/pagination.pt-BR.mdx +++ b/pages/docs/pagination.pt-BR.mdx @@ -347,6 +347,30 @@ function App () { O argumento `previousPageData` da função `getKey` se torna `null` quando você habilita a opção `parallel`. +### Revalidate Specific Pages [#revalidate-specific-pages] + + + Please update to the latest version (≥ 2.2.5) to use this API. + + +The default behavior of the mutation of `useSWRInfinite` is to revalidate all pages that have been loaded. But you might want to revalidate only the specific pages that have been changed. You can revalidate only specific pages by passing a function to the `revalidate` option. + +The `revalidate` function is called for each page. + +```jsx +function App() { + const { mutate, size } = useSWRInfinite( + (index) => [`/api/?page=${index + 1}`, index + 1], + fetcher + ); + + mutate({ + // only revalidate the last page + revalidate: (data, [url, page]) => page === size + }); +} +``` + ### Mutação Global com `useSWRInfinite` [#global-mutate-with-useswrinfinite] `useSWRInfinite` armazena todos os dados da página com uma chave de cache especial junto com cada dado da página. Você deve usar `unstable_serialize` em `swr/infinite` para revalidar os dados com a mutação global. diff --git a/pages/docs/pagination.ru.mdx b/pages/docs/pagination.ru.mdx index b80a7514..03622519 100644 --- a/pages/docs/pagination.ru.mdx +++ b/pages/docs/pagination.ru.mdx @@ -346,6 +346,30 @@ function App () { Аргумент `previousPageData` функции `getKey` становится `null`, когда вы включаете опцию `parallel`. +### Revalidate Specific Pages [#revalidate-specific-pages] + + + Please update to the latest version (≥ 2.2.5) to use this API. + + +The default behavior of the mutation of `useSWRInfinite` is to revalidate all pages that have been loaded. But you might want to revalidate only the specific pages that have been changed. You can revalidate only specific pages by passing a function to the `revalidate` option. + +The `revalidate` function is called for each page. + +```jsx +function App() { + const { mutate, size } = useSWRInfinite( + (index) => [`/api/?page=${index + 1}`, index + 1], + fetcher + ); + + mutate({ + // only revalidate the last page + revalidate: (data, [url, page]) => page === size + }); +} +``` + ### Глобальная мутация с `useSWRInfinite` [#global-mutate-with-useswrinfinite] `useSWRInfinite` хранит все данные страниц в кеше со специальным ключом кеша вместе с данными каждой страницы, поэтому вам нужно использовать `unstable_serialize` в `swr/infinite`, чтобы ревалидировать данные с глобальной мутацией. diff --git a/pages/docs/pagination.zh-CN.mdx b/pages/docs/pagination.zh-CN.mdx index eb6aad97..45d43034 100644 --- a/pages/docs/pagination.zh-CN.mdx +++ b/pages/docs/pagination.zh-CN.mdx @@ -336,6 +336,30 @@ function App () { 当你启用了 `parallel` 选项,`getKey` 函数的参数 `previousPageData` 会变为 `null`。 +### Revalidate Specific Pages [#revalidate-specific-pages] + + + Please update to the latest version (≥ 2.2.5) to use this API. + + +The default behavior of the mutation of `useSWRInfinite` is to revalidate all pages that have been loaded. But you might want to revalidate only the specific pages that have been changed. You can revalidate only specific pages by passing a function to the `revalidate` option. + +The `revalidate` function is called for each page. + +```jsx +function App() { + const { mutate, size } = useSWRInfinite( + (index) => [`/api/?page=${index + 1}`, index + 1], + fetcher + ); + + mutate({ + // only revalidate the last page + revalidate: (data, [url, page]) => page === size + }); +} +``` + ### 全局变更 `useSWRInfinite` 数据 [#global-mutate-with-useswrinfinite]