From 7eae66ded039b17059d31bd57fd93d31e48fef67 Mon Sep 17 00:00:00 2001 From: Toru Kobayashi Date: Sat, 6 Aug 2022 00:35:50 +0900 Subject: [PATCH 1/3] Empty commit for v2 branch From 456cb33ddc4b3efbb582736a992eae45f60e78c1 Mon Sep 17 00:00:00 2001 From: Toru Kobayashi Date: Wed, 24 Aug 2022 00:54:23 +0900 Subject: [PATCH 2/3] docs: add mutate filter functions documentation in v2 --- pages/docs/advanced/cache.en-US.mdx | 4 +- pages/docs/advanced/cache.ja.mdx | 2 + pages/docs/advanced/cache.ko.mdx | 2 + pages/docs/advanced/cache.pt-BR.mdx | 406 ++++++++++++++-------------- pages/docs/advanced/cache.ru.mdx | 14 +- pages/docs/advanced/cache.zh-CN.mdx | 4 +- pages/docs/mutation.en-US.md | 51 ++++ pages/docs/mutation.es-ES.md | 51 ++++ pages/docs/mutation.ja.md | 51 ++++ pages/docs/mutation.ko.md | 51 ++++ pages/docs/mutation.pt-BR.md | 51 ++++ pages/docs/mutation.ru.md | 51 ++++ pages/docs/mutation.zh-CN.md | 51 ++++ 13 files changed, 579 insertions(+), 210 deletions(-) diff --git a/pages/docs/advanced/cache.en-US.mdx b/pages/docs/advanced/cache.en-US.mdx index 524840dd..84e536c2 100644 --- a/pages/docs/advanced/cache.en-US.mdx +++ b/pages/docs/advanced/cache.en-US.mdx @@ -60,7 +60,7 @@ import { Cache } from 'components/diagrams/cache' When nested, SWR hooks will use the upper-level cache provider. If there is no upper-level cache provider, it fallbacks to the default cache provider, which is an empty `Map`. - If a cache provider is used, the global `mutate` will **not** work for SWR hooks under that `` boundary. Please use [this](#access-current-cache-provider) instead. + If a cache provider is used, the global `mutate` will **not** work for SWR hooks under that `` boundary. Please use [this](#access-current-cache-provider) instead. ## Access Current Cache Provider @@ -197,3 +197,5 @@ const { cache } = useSWRConfig() cache.get(key) // Get the current data for a key. cache.clear() // ⚠️ Clear all the cache. SWR will revalidate upon re-render. ``` + +You can use [`mutate`](/docs/mutation) to modify the cache. diff --git a/pages/docs/advanced/cache.ja.mdx b/pages/docs/advanced/cache.ja.mdx index c03ab01f..edd0adfe 100644 --- a/pages/docs/advanced/cache.ja.mdx +++ b/pages/docs/advanced/cache.ja.mdx @@ -197,3 +197,5 @@ const { cache } = useSWRConfig() cache.get(key) // キーの現在のデータを取得します。 cache.clear() // ⚠️ すべてのキャッシュをクリアします。 SWRは、再レンダリング時に再検証します。 ``` + +[`mutate`](/docs/mutation) をキャッシュを更新するために利用できます。 diff --git a/pages/docs/advanced/cache.ko.mdx b/pages/docs/advanced/cache.ko.mdx index 2c6b013f..769d5dc7 100644 --- a/pages/docs/advanced/cache.ko.mdx +++ b/pages/docs/advanced/cache.ko.mdx @@ -197,3 +197,5 @@ const { cache } = useSWRConfig() cache.get(key) // 키에 대한 현재 데이터 가져오기. cache.clear() // ⚠️ 모든 캐시를 삭제하기. SWR은 다시 렌더링할 때 재검증합니다. ``` + +You can use [`mutate`](/docs/mutation) to modify the cache. diff --git a/pages/docs/advanced/cache.pt-BR.mdx b/pages/docs/advanced/cache.pt-BR.mdx index 19c83174..2e6dfe14 100644 --- a/pages/docs/advanced/cache.pt-BR.mdx +++ b/pages/docs/advanced/cache.pt-BR.mdx @@ -1,202 +1,204 @@ -import Callout from 'nextra-theme-docs/callout' - -# Cache - - - Atualize para a última versão (≥ 1.0.0) para usar este recurso. - - - - -Na maioria dos casos, você não deve escrever diretamente no cache, o que pode causar comportamentos indefinidos do SWR. -Se você precisa mutar manualmente uma chave, por favor, considere usar as APIs do SWR.
-Veja também: [Mutação](/docs/mutation), [Redefinir Cache Entre Casos de Teste](#redefinir-cache-entre-casos-de-teste). - -
- -Por padrão, SWR usa um cache global para armazenar e compartilhar dados entre todos os componentes. Mas você pode customizar este comportamento com a opção `provider` do `SWRConfig`. - -Cache Providers são destinados a permitir SWR com armazenamentos mais personalizados. - -## Cache Provider - -Um cache provider é um objeto (parecido com um Map) que corresponde à definição de tipo TypeScript da seguinte definição (que pode ser importado de `swr`): - -```typescript -interface Cache { - get(key: string): Data | undefined - set(key: string, value: Data): void - delete(key: string): void -} -``` - -Por exemplo, um [Map do JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) pode ser usado diretamente como cache provider para SWR. - -## Criar Cache Provider - -A opção `provider` do `SWRConfig` recebe uma função que retorna um [cache provider](#cache-provider). O provider será usado por todos os hooks SWR dentro dos limites de configuração do `SWRConfig`. Por exemplo: - -```jsx -import useSWR, { SWRConfig } from 'swr' - -function App() { - return ( - new Map() }}> - - - ) -} -``` - -Todos os hooks SWR dentro de `` lerão e escreverão naquela instância Map. Você também pode usar outras implementações de cache provider para seu caso específico. - - - No exemplo acima, quando o componente `` é re-montado, o provider também é re-criado. Cache Providers devem ser colocados mais alto na árvore de componentes, ou fora do render. - - -import { Cache } from 'components/diagrams/cache' - -
- -
- -Quando aninhado, hooks SWR irão usar o cache provider mais alto. Se não houver cache provider mais alto, ele irá usar o provider padrão, que é um `Map` vazio. - - - Se um cache provider é usado, o `mutate` global **não** funcionará para os hooks SWR dentro do limite de configuração ``. Por favor, use [isto](#acessar-cache-provider-atual) em vez disso. - - -## Acessar Cache Provider Atual - -Quando dentro de um Componente React, você precisa usar o hook [`useSWRConfig`](/docs/global-configuration#acesso-às-configurações-globais) para obter acesso ao cache provider atual e outras configurações, incluindo `mutate`: - -```jsx -import { useSWRConfig } from 'swr' - -function Avatar() { - const { cache, mutate, ...extraConfig } = useSWRConfig() - // ... -} -``` - -Se não estiver sob nenhum ``, será retornado as configurações padrão. - -## Experimental: Estender o Cache Provider - - - Este é um recurso experimental, o comportamento pode mudar em futuras atualizações. - - -Quando vários componentes `` são aninhados, o cache provider pode ser estendido. - -O primeiro argumento para a função `provider` é o cache provider do nível superior do `` (ou o cache padrão se não houver `` pai), você pode usá-lo para estender o cache provider: - -```jsx - newCache }}> - ... - -``` - -## Exemplos - -### Mudar Várias Chaves de RegEx - -Com a flexibilidade da API do cache provider, você pode até criar um auxiliar de "mutação parcial". - -No exemplo abaixo, `matchMutate` pode receber uma expressão regular como chave e ser usada para alterar aqueles que corresponderem a esse padrão. - -```js -function useMatchMutate() { - const { cache, mutate } = useSWRConfig() - return (matcher, ...args) => { - if (!(cache instanceof Map)) { - throw new Error('matchMutate requer que o cache provider seja uma instância de Map') - } - - const keys = [] - - for (const key of cache.keys()) { - if (matcher.test(key)) { - keys.push(key) - } - } - - const mutations = keys.map((key) => mutate(key, ...args)) - return Promise.all(mutations) - } -} -``` - -Em seguida, dentro de seu componente: - -```jsx -function Button() { - const matchMutate = useMatchMutate() - return -} -``` - - - Observe que este exemplo requer que o cache provider seja uma instância de Map. - - -### Cache Persistente Baseado em LocalStorage - -Você pode querer sincronizar seu cache com `localStorage`. Aqui está um exemplo de implementação: - -```jsx -function localStorageProvider() { - // Ao inicializar, restauramos os dados de `localStorage` em um mapa. - const map = new Map(JSON.parse(localStorage.getItem('app-cache') || '[]')) - - // Antes de descarregar o aplicativo, gravamos todos os dados em `localStorage`. - window.addEventListener('beforeunload', () => { - const appCache = JSON.stringify(Array.from(map.entries())) - localStorage.setItem('app-cache', appCache) - }) - - // Ainda usamos o mapa para gravação e leitura para desempenho. - return map -} -``` - -Em seguida, use-o como provider: - -```jsx - - - -``` - - - Como melhoria, você também pode usar o cache de memória como um buffer e gravar em `localStorage` periodicamente. Você também pode implementar um cache em camadas semelhante ao IndexedDB ou WebSQL. - - -### Redefinir Cache Entre Casos de Teste - -Ao testar seu aplicativo, talvez você queira redefinir o cache SWR entre os casos de teste. Você pode simplesmente envolver seu aplicativo com um cache provider vazio. Aqui está um exemplo com Jest: - -```jsx -describe('test suite', async () => { - it('test case', async () => { - render( - new Map() }}> - - - ) - }) -}) -``` - -### Acesso ao Cache - -Alerta: você não deve gravar diretamente no cache, isso pode causar um comportamento indefinido. - -```jsx -const { cache } = useSWRConfig() - -cache.get(key) // Obtém os dados atuais para uma chave. -cache.clear() // ⚠️ Limpa todo o cache. O SWR será revalidado após a re-renderização. -``` +import Callout from 'nextra-theme-docs/callout' + +# Cache + + + Atualize para a última versão (≥ 1.0.0) para usar este recurso. + + + + +Na maioria dos casos, você não deve escrever diretamente no cache, o que pode causar comportamentos indefinidos do SWR. +Se você precisa mutar manualmente uma chave, por favor, considere usar as APIs do SWR.
+Veja também: [Mutação](/docs/mutation), [Redefinir Cache Entre Casos de Teste](#redefinir-cache-entre-casos-de-teste). + +
+ +Por padrão, SWR usa um cache global para armazenar e compartilhar dados entre todos os componentes. Mas você pode customizar este comportamento com a opção `provider` do `SWRConfig`. + +Cache Providers são destinados a permitir SWR com armazenamentos mais personalizados. + +## Cache Provider + +Um cache provider é um objeto (parecido com um Map) que corresponde à definição de tipo TypeScript da seguinte definição (que pode ser importado de `swr`): + +```typescript +interface Cache { + get(key: string): Data | undefined + set(key: string, value: Data): void + delete(key: string): void +} +``` + +Por exemplo, um [Map do JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) pode ser usado diretamente como cache provider para SWR. + +## Criar Cache Provider + +A opção `provider` do `SWRConfig` recebe uma função que retorna um [cache provider](#cache-provider). O provider será usado por todos os hooks SWR dentro dos limites de configuração do `SWRConfig`. Por exemplo: + +```jsx +import useSWR, { SWRConfig } from 'swr' + +function App() { + return ( + new Map() }}> + + + ) +} +``` + +Todos os hooks SWR dentro de `` lerão e escreverão naquela instância Map. Você também pode usar outras implementações de cache provider para seu caso específico. + + + No exemplo acima, quando o componente `` é re-montado, o provider também é re-criado. Cache Providers devem ser colocados mais alto na árvore de componentes, ou fora do render. + + +import { Cache } from 'components/diagrams/cache' + +
+ +
+ +Quando aninhado, hooks SWR irão usar o cache provider mais alto. Se não houver cache provider mais alto, ele irá usar o provider padrão, que é um `Map` vazio. + + + Se um cache provider é usado, o `mutate` global **não** funcionará para os hooks SWR dentro do limite de configuração ``. Por favor, use [isto](#acessar-cache-provider-atual) em vez disso. + + +## Acessar Cache Provider Atual + +Quando dentro de um Componente React, você precisa usar o hook [`useSWRConfig`](/docs/global-configuration#acesso-às-configurações-globais) para obter acesso ao cache provider atual e outras configurações, incluindo `mutate`: + +```jsx +import { useSWRConfig } from 'swr' + +function Avatar() { + const { cache, mutate, ...extraConfig } = useSWRConfig() + // ... +} +``` + +Se não estiver sob nenhum ``, será retornado as configurações padrão. + +## Experimental: Estender o Cache Provider + + + Este é um recurso experimental, o comportamento pode mudar em futuras atualizações. + + +Quando vários componentes `` são aninhados, o cache provider pode ser estendido. + +O primeiro argumento para a função `provider` é o cache provider do nível superior do `` (ou o cache padrão se não houver `` pai), você pode usá-lo para estender o cache provider: + +```jsx + newCache }}> + ... + +``` + +## Exemplos + +### Mudar Várias Chaves de RegEx + +Com a flexibilidade da API do cache provider, você pode até criar um auxiliar de "mutação parcial". + +No exemplo abaixo, `matchMutate` pode receber uma expressão regular como chave e ser usada para alterar aqueles que corresponderem a esse padrão. + +```js +function useMatchMutate() { + const { cache, mutate } = useSWRConfig() + return (matcher, ...args) => { + if (!(cache instanceof Map)) { + throw new Error('matchMutate requer que o cache provider seja uma instância de Map') + } + + const keys = [] + + for (const key of cache.keys()) { + if (matcher.test(key)) { + keys.push(key) + } + } + + const mutations = keys.map((key) => mutate(key, ...args)) + return Promise.all(mutations) + } +} +``` + +Em seguida, dentro de seu componente: + +```jsx +function Button() { + const matchMutate = useMatchMutate() + return +} +``` + + + Observe que este exemplo requer que o cache provider seja uma instância de Map. + + +### Cache Persistente Baseado em LocalStorage + +Você pode querer sincronizar seu cache com `localStorage`. Aqui está um exemplo de implementação: + +```jsx +function localStorageProvider() { + // Ao inicializar, restauramos os dados de `localStorage` em um mapa. + const map = new Map(JSON.parse(localStorage.getItem('app-cache') || '[]')) + + // Antes de descarregar o aplicativo, gravamos todos os dados em `localStorage`. + window.addEventListener('beforeunload', () => { + const appCache = JSON.stringify(Array.from(map.entries())) + localStorage.setItem('app-cache', appCache) + }) + + // Ainda usamos o mapa para gravação e leitura para desempenho. + return map +} +``` + +Em seguida, use-o como provider: + +```jsx + + + +``` + + + Como melhoria, você também pode usar o cache de memória como um buffer e gravar em `localStorage` periodicamente. Você também pode implementar um cache em camadas semelhante ao IndexedDB ou WebSQL. + + +### Redefinir Cache Entre Casos de Teste + +Ao testar seu aplicativo, talvez você queira redefinir o cache SWR entre os casos de teste. Você pode simplesmente envolver seu aplicativo com um cache provider vazio. Aqui está um exemplo com Jest: + +```jsx +describe('test suite', async () => { + it('test case', async () => { + render( + new Map() }}> + + + ) + }) +}) +``` + +### Acesso ao Cache + +Alerta: você não deve gravar diretamente no cache, isso pode causar um comportamento indefinido. + +```jsx +const { cache } = useSWRConfig() + +cache.get(key) // Obtém os dados atuais para uma chave. +cache.clear() // ⚠️ Limpa todo o cache. O SWR será revalidado após a re-renderização. +``` + +You can use [`mutate`](/docs/mutation) to modify the cache. diff --git a/pages/docs/advanced/cache.ru.mdx b/pages/docs/advanced/cache.ru.mdx index 41047834..b26615dc 100644 --- a/pages/docs/advanced/cache.ru.mdx +++ b/pages/docs/advanced/cache.ru.mdx @@ -7,8 +7,8 @@ import Callout from 'nextra-theme-docs/callout' - В большинстве случаев вы не должны напрямую _писать_ в кеш, поскольку это может вызвать - неопределенное поведение SWR. Если вам нужно вручную изменить ключ, рассмотрите возможность + В большинстве случаев вы не должны напрямую _писать_ в кеш, поскольку это может вызвать + неопределенное поведение SWR. Если вам нужно вручную изменить ключ, рассмотрите возможность использования API SWR.
См. также: [Мутация](/docs/mutation), [Сброс кеша между тестами](#сброс-кеша-между-тестами).
@@ -55,7 +55,7 @@ function App() { другие реализации поставщика кеша для вашего конкретного случая использования. - В приведённом выше примере, когда компонент `` повторно монтируется, провайдер также будет + В приведённом выше примере, когда компонент `` повторно монтируется, провайдер также будет повторно создан. Провайдеры кеша должны быть размещены выше в дереве компонентов или вне рендеринга. @@ -69,7 +69,7 @@ import { Cache } from 'components/diagrams/cache' верхнего уровня, он возвращается к провайдеру кэша по умолчанию, который является пустым `Map`. - Если используется провайдер кеша, глобальный `mutate` **не** будет работать для хуков SWR в пределе + Если используется провайдер кеша, глобальный `mutate` **не** будет работать для хуков SWR в пределе этого ``. Пожалуйста, используйте [это](#доступ-к-текущему-провайдеру-кеша) взамен. @@ -182,8 +182,8 @@ function localStorageProvider() { ``` - В качестве улучшения вы также можете использовать кеш памяти в качестве буфера и периодически - записывать в `localStorage`. Вы также можете реализовать аналогичный многоуровневый кеш + В качестве улучшения вы также можете использовать кеш памяти в качестве буфера и периодически + записывать в `localStorage`. Вы также можете реализовать аналогичный многоуровневый кеш с помощью IndexedDB или WebSQL. @@ -214,3 +214,5 @@ const { cache } = useSWRConfig() cache.get(key) // Получить текущие данные для ключа. cache.clear() // ⚠️ Очистить весь кеш. SWR проведёт ревалидацию при повторном рендеринге. ``` + +You can use [`mutate`](/docs/mutation) to modify the cache. diff --git a/pages/docs/advanced/cache.zh-CN.mdx b/pages/docs/advanced/cache.zh-CN.mdx index 992ba4aa..8a9f0680 100644 --- a/pages/docs/advanced/cache.zh-CN.mdx +++ b/pages/docs/advanced/cache.zh-CN.mdx @@ -86,7 +86,7 @@ function Avatar() { 当多个 `` 组件嵌套时,可以扩展缓存 provider。 -`provider` 函数的第一个参数是上层 `` 的缓存 provider(如果没有父级 ``,则为默认缓存),你可以使用它来扩展缓存 provider: +`provider` 函数的第一个参数是上层 `` 的缓存 provider(如果没有父级 ``,则为默认缓存),你可以使用它来扩展缓存 provider: ```jsx newCache }}> @@ -197,3 +197,5 @@ const { cache } = useSWRConfig() cache.get(key) // 获取 key 的当前数据。 cache.clear() // ⚠️ 清除所有缓存。SWR 将在重新渲染时重新请求。 ``` + +You can use [`mutate`](/docs/mutation) to modify the cache. diff --git a/pages/docs/mutation.en-US.md b/pages/docs/mutation.en-US.md index a888623b..3c457b04 100644 --- a/pages/docs/mutation.en-US.md +++ b/pages/docs/mutation.en-US.md @@ -161,6 +161,57 @@ try { } ``` +## Mutate Multiple Items + +`mutate` accepts a filter function, which accepts `key` as the argument and returns which keys to revalidate. The filter function is applied to all the existing cache keys. + +```jsx +import { mutate } from 'swr' +// Or from the hook if you customized the cache provider: +// { mutate } = useSWRConfig() + +mutate( + key => typeof key === 'string' && key.startsWith('/api/item?id='), + undefined, + { revalidate: true } +) +``` + +This also works with any key type like an array. The mutation matches all keys, of which the first element is `'item'`. + +```jsx +useSWR(['item', 123], ...) +useSWR(['item', 124], ...) +useSWR(['item', 125], ...) + +mutate( + key => Array.isArray(key) && key[0] === 'item', + undefined, + { revalidate: false } +) +``` + +You can use the filter function to clear all cache data, which is useful when logging out. + + +```js +mutate( + () => true, + undefined, + { revalidate: false } +) +``` + +But it is unclear what it does, so you can name it `clearCache`. + +```js +const clearCache = () => mutate( + () => true, + undefined, + { revalidate: false } +) +``` + ## Bound Mutate The SWR object returned by `useSWR` also contains a `mutate()` function that is pre-bound to the SWR's key. diff --git a/pages/docs/mutation.es-ES.md b/pages/docs/mutation.es-ES.md index ec93a20b..1907b47a 100644 --- a/pages/docs/mutation.es-ES.md +++ b/pages/docs/mutation.es-ES.md @@ -159,6 +159,57 @@ try { } ``` +## Mutate Multiple Items + +`mutate` accepts a filter function, which accepts `key` as the argument and returns which keys to revalidate. The filter function is applied to all the existing cache keys. + +```jsx +import { mutate } from 'swr' +// Or from the hook if you customized the cache provider: +// { mutate } = useSWRConfig() + +mutate( + key => typeof key === 'string' && key.startsWith('/api/item?id='), + undefined, + { revalidate: true } +) +``` + +This also works with any key type like an array. The mutation matches all keys, of which the first element is `'item'`. + +```jsx +useSWR(['item', 123], ...) +useSWR(['item', 124], ...) +useSWR(['item', 125], ...) + +mutate( + key => Array.isArray(key) && key[0] === 'item', + undefined, + { revalidate: false } +) +``` + +You can use the filter function to clear all cache data, which is useful when logging out. + + +```js +mutate( + () => true, + undefined, + { revalidate: false } +) +``` + +But it is unclear what it does, so you can name it `clearCache`. + +```js +const clearCache = () => mutate( + () => true, + undefined, + { revalidate: false } +) +``` + ## Bound Mutate El objeto SWR devuelto por `useSWR` también contiene una función `mutate()` que está atada a la key del SWR. diff --git a/pages/docs/mutation.ja.md b/pages/docs/mutation.ja.md index 1684afdd..c1fd9a4a 100644 --- a/pages/docs/mutation.ja.md +++ b/pages/docs/mutation.ja.md @@ -160,6 +160,57 @@ try { } ``` +## 複数のアイテムをミューテートする + +`mutate` は `key` を引数として受け取りどのキーを再検証するかどうかを返すフィルタリング関数を受け取ります。フィルタリング関数は全てのキャッシュキーに対して適用されます。 + +```jsx +import { mutate } from 'swr' +// Or from the hook if you customized the cache provider: +// { mutate } = useSWRConfig() + +mutate( + key => typeof key === 'string' && key.startsWith('/api/item?id='), + undefined, + { revalidate: true } +) +``` + +This also works with any key type like an array. The mutation matches all keys, of which the first element is `'item'`. + +```jsx +useSWR(['item', 123], ...) +useSWR(['item', 124], ...) +useSWR(['item', 125], ...) + +mutate( + key => Array.isArray(key) && key[0] === 'item', + undefined, + { revalidate: false } +) +``` + +You can use the filter function to clear all cache data, which is useful when logging out. + + +```js +mutate( + () => true, + undefined, + { revalidate: false } +) +``` + +But it is unclear what it does, so you can name it `clearCache`. + +```js +const clearCache = () => mutate( + () => true, + undefined, + { revalidate: false } +) +``` + ## バウンドミューテート `useSWR` によって返される SWR オブジェクトには、SWR のキーに事前にバインドされている `mutate()` 関数も含まれています。 diff --git a/pages/docs/mutation.ko.md b/pages/docs/mutation.ko.md index bc67a4ad..948e8e5a 100644 --- a/pages/docs/mutation.ko.md +++ b/pages/docs/mutation.ko.md @@ -161,6 +161,57 @@ try { } ``` +## Mutate Multiple Items + +`mutate` accepts a filter function, which accepts `key` as the argument and returns which keys to revalidate. The filter function is applied to all the existing cache keys. + +```jsx +import { mutate } from 'swr' +// Or from the hook if you customized the cache provider: +// { mutate } = useSWRConfig() + +mutate( + key => typeof key === 'string' && key.startsWith('/api/item?id='), + undefined, + { revalidate: true } +) +``` + +This also works with any key type like an array. The mutation matches all keys, of which the first element is `'item'`. + +```jsx +useSWR(['item', 123], ...) +useSWR(['item', 124], ...) +useSWR(['item', 125], ...) + +mutate( + key => Array.isArray(key) && key[0] === 'item', + undefined, + { revalidate: false } +) +``` + +You can use the filter function to clear all cache data, which is useful when logging out. + + +```js +mutate( + () => true, + undefined, + { revalidate: false } +) +``` + +But it is unclear what it does, so you can name it `clearCache`. + +```js +const clearCache = () => mutate( + () => true, + undefined, + { revalidate: false } +) +``` + ## 바인딩 된 뮤테이트 `useSWR`에 의해 반환된 SWR 객체는 SWR의 키로 미리 바인딩 된 `mutate()` 함수도 포함합니다. diff --git a/pages/docs/mutation.pt-BR.md b/pages/docs/mutation.pt-BR.md index 7b7b202a..a6f52dd6 100644 --- a/pages/docs/mutation.pt-BR.md +++ b/pages/docs/mutation.pt-BR.md @@ -159,6 +159,57 @@ try { } ``` +## Mutate Multiple Items + +`mutate` accepts a filter function, which accepts `key` as the argument and returns which keys to revalidate. The filter function is applied to all the existing cache keys. + +```jsx +import { mutate } from 'swr' +// Or from the hook if you customized the cache provider: +// { mutate } = useSWRConfig() + +mutate( + key => typeof key === 'string' && key.startsWith('/api/item?id='), + undefined, + { revalidate: true } +) +``` + +This also works with any key type like an array. The mutation matches all keys, of which the first element is `'item'`. + +```jsx +useSWR(['item', 123], ...) +useSWR(['item', 124], ...) +useSWR(['item', 125], ...) + +mutate( + key => Array.isArray(key) && key[0] === 'item', + undefined, + { revalidate: false } +) +``` + +You can use the filter function to clear all cache data, which is useful when logging out. + + +```js +mutate( + () => true, + undefined, + { revalidate: false } +) +``` + +But it is unclear what it does, so you can name it `clearCache`. + +```js +const clearCache = () => mutate( + () => true, + undefined, + { revalidate: false } +) +``` + ## Mutação Vinculada O objeto SWR retornado por `useSWR` também contém uma função `mutate()` que é vinculada ao chave do SWR. diff --git a/pages/docs/mutation.ru.md b/pages/docs/mutation.ru.md index 15265924..f7fe6df8 100644 --- a/pages/docs/mutation.ru.md +++ b/pages/docs/mutation.ru.md @@ -156,6 +156,57 @@ try { } ``` +## Mutate Multiple Items + +`mutate` accepts a filter function, which accepts `key` as the argument and returns which keys to revalidate. The filter function is applied to all the existing cache keys. + +```jsx +import { mutate } from 'swr' +// Or from the hook if you customized the cache provider: +// { mutate } = useSWRConfig() + +mutate( + key => typeof key === 'string' && key.startsWith('/api/item?id='), + undefined, + { revalidate: true } +) +``` + +This also works with any key type like an array. The mutation matches all keys, of which the first element is `'item'`. + +```jsx +useSWR(['item', 123], ...) +useSWR(['item', 124], ...) +useSWR(['item', 125], ...) + +mutate( + key => Array.isArray(key) && key[0] === 'item', + undefined, + { revalidate: false } +) +``` + +You can use the filter function to clear all cache data, which is useful when logging out. + + +```js +mutate( + () => true, + undefined, + { revalidate: false } +) +``` + +But it is unclear what it does, so you can name it `clearCache`. + +```js +const clearCache = () => mutate( + () => true, + undefined, + { revalidate: false } +) +``` + ## Связывание мутации Объект SWR, возвращаемый `useSWR`, также содержит функцию `mutate()`, которая предварительно привязана к ключу SWR. diff --git a/pages/docs/mutation.zh-CN.md b/pages/docs/mutation.zh-CN.md index 028c6905..aa2c6ba7 100644 --- a/pages/docs/mutation.zh-CN.md +++ b/pages/docs/mutation.zh-CN.md @@ -151,6 +151,57 @@ try { } ``` +## Mutate Multiple Items + +`mutate` accepts a filter function, which accepts `key` as the argument and returns which keys to revalidate. The filter function is applied to all the existing cache keys. + +```jsx +import { mutate } from 'swr' +// Or from the hook if you customized the cache provider: +// { mutate } = useSWRConfig() + +mutate( + key => typeof key === 'string' && key.startsWith('/api/item?id='), + undefined, + { revalidate: true } +) +``` + +This also works with any key type like an array. The mutation matches all keys, of which the first element is `'item'`. + +```jsx +useSWR(['item', 123], ...) +useSWR(['item', 124], ...) +useSWR(['item', 125], ...) + +mutate( + key => Array.isArray(key) && key[0] === 'item', + undefined, + { revalidate: false } +) +``` + +You can use the filter function to clear all cache data, which is useful when logging out. + + +```js +mutate( + () => true, + undefined, + { revalidate: false } +) +``` + +But it is unclear what it does, so you can name it `clearCache`. + +```js +const clearCache = () => mutate( + () => true, + undefined, + { revalidate: false } +) +``` + ## 绑定的 Mutate 函数 `useSWR` 返回的 SWR 对象还包含一个 `mutate()` 函数,该函数预先绑定到 SWR 的 key。 From b2c5ad690d95f3d95a77edd6484663dcf00d9a70 Mon Sep 17 00:00:00 2001 From: Toru Kobayashi Date: Thu, 25 Aug 2022 00:33:50 +0900 Subject: [PATCH 3/3] remove the usage of cache.clear() and use mutate instead --- pages/docs/advanced/cache.en-US.mdx | 17 ++++++++++++----- pages/docs/advanced/cache.ja.mdx | 23 ++++++++++++++++++----- pages/docs/advanced/cache.ko.mdx | 23 ++++++++++++++++++----- pages/docs/advanced/cache.pt-BR.mdx | 23 ++++++++++++++++++----- pages/docs/advanced/cache.ru.mdx | 23 ++++++++++++++++++----- pages/docs/advanced/cache.zh-CN.mdx | 17 ++++++++++++----- 6 files changed, 96 insertions(+), 30 deletions(-) diff --git a/pages/docs/advanced/cache.en-US.mdx b/pages/docs/advanced/cache.en-US.mdx index 84e536c2..f6bf0013 100644 --- a/pages/docs/advanced/cache.en-US.mdx +++ b/pages/docs/advanced/cache.en-US.mdx @@ -187,15 +187,22 @@ describe('test suite', async () => { }) ``` -### Access to the Cache +### Modify the Cache Data -Alert: you should not write to the cache directly, it might cause undefined behavior. + + You should not write to the cache directly, it might cause undefined behavior. + + +You can use [`mutate`](/docs/mutation) to modify the cache. For example, you can clear all cache data like the following. ```jsx const { cache } = useSWRConfig() -cache.get(key) // Get the current data for a key. -cache.clear() // ⚠️ Clear all the cache. SWR will revalidate upon re-render. +mutate( + key => true, // which cache keys are updated + undefined, // update cache data to `undefined` + { revalidate: false } // do not revalidate +) ``` -You can use [`mutate`](/docs/mutation) to modify the cache. +More information can be found [here](/docs/arguments#multiple-arguments). diff --git a/pages/docs/advanced/cache.ja.mdx b/pages/docs/advanced/cache.ja.mdx index edd0adfe..10971415 100644 --- a/pages/docs/advanced/cache.ja.mdx +++ b/pages/docs/advanced/cache.ja.mdx @@ -187,15 +187,28 @@ describe('test suite', async () => { }) ``` -### キャッシュへアクセスする - -警告:キャッシュに直接書き込むことはするべきではありません。予期しない動作が発生する可能性があります。 +### キャッシュを更新する ```jsx const { cache } = useSWRConfig() cache.get(key) // キーの現在のデータを取得します。 -cache.clear() // ⚠️ すべてのキャッシュをクリアします。 SWRは、再レンダリング時に再検証します。 ``` -[`mutate`](/docs/mutation) をキャッシュを更新するために利用できます。 + + キャッシュに直接書き込むことはするべきではありません。予期しない動作が発生する可能性があります。 + + +[`mutate`](/docs/mutation) をキャッシュを更新するために利用できます。例えば、下記のようにすることで全てのキャッシュデータをクリアできます。 + +```jsx +const { cache } = useSWRConfig() + +mutate( + key => true, // どのキャッシュキーを更新するか + undefined, // キャッシュデータを `undefined` に更新する + { revalidate: false } // 再検証しない +) +``` + +更なる情報は [こちら](/docs/arguments#multiple-arguments) から確認できます。 \ No newline at end of file diff --git a/pages/docs/advanced/cache.ko.mdx b/pages/docs/advanced/cache.ko.mdx index 769d5dc7..7058c17e 100644 --- a/pages/docs/advanced/cache.ko.mdx +++ b/pages/docs/advanced/cache.ko.mdx @@ -187,15 +187,28 @@ describe('test suite', async () => { }) ``` -### 캐시에 접근하기 - -알림: 캐시를 직접 쓰면 안 됩니다. 정의되지 않은 동작을 유발할 수도 있습니다. +### Modify the Cache Data ```jsx const { cache } = useSWRConfig() cache.get(key) // 키에 대한 현재 데이터 가져오기. -cache.clear() // ⚠️ 모든 캐시를 삭제하기. SWR은 다시 렌더링할 때 재검증합니다. ``` -You can use [`mutate`](/docs/mutation) to modify the cache. + + 캐시를 직접 쓰면 안 됩니다. 정의되지 않은 동작을 유발할 수도 있습니다. + + +You can use [`mutate`](/docs/mutation) to modify the cache. For example, you can clear all cache data like the following. + +```jsx +const { cache } = useSWRConfig() + +mutate( + key => true, // which cache keys are updated + undefined, // update cache data to `undefined` + { revalidate: false } // do not revalidate +) +``` + +More information can be found [here](/docs/arguments#multiple-arguments). diff --git a/pages/docs/advanced/cache.pt-BR.mdx b/pages/docs/advanced/cache.pt-BR.mdx index 2e6dfe14..29b4e5a5 100644 --- a/pages/docs/advanced/cache.pt-BR.mdx +++ b/pages/docs/advanced/cache.pt-BR.mdx @@ -190,15 +190,28 @@ describe('test suite', async () => { }) ``` -### Acesso ao Cache - -Alerta: você não deve gravar diretamente no cache, isso pode causar um comportamento indefinido. +### Modify the Cache Data ```jsx const { cache } = useSWRConfig() cache.get(key) // Obtém os dados atuais para uma chave. -cache.clear() // ⚠️ Limpa todo o cache. O SWR será revalidado após a re-renderização. ``` -You can use [`mutate`](/docs/mutation) to modify the cache. + + você não deve gravar diretamente no cache, isso pode causar um comportamento indefinido. + + +You can use [`mutate`](/docs/mutation) to modify the cache. For example, you can clear all cache data like the following. + +```jsx +const { cache } = useSWRConfig() + +mutate( + key => true, // which cache keys are updated + undefined, // update cache data to `undefined` + { revalidate: false } // do not revalidate +) +``` + +More information can be found [here](/docs/arguments#multiple-arguments). diff --git a/pages/docs/advanced/cache.ru.mdx b/pages/docs/advanced/cache.ru.mdx index b26615dc..4a6265fa 100644 --- a/pages/docs/advanced/cache.ru.mdx +++ b/pages/docs/advanced/cache.ru.mdx @@ -204,15 +204,28 @@ describe('тестирование', async () => { }) ``` -### Доступ к кешу - -Предупреждение: вы не должны писать в кеш напрямую, это может привести к неопределенному поведению. +### Modify the Cache Data ```jsx const { cache } = useSWRConfig() cache.get(key) // Получить текущие данные для ключа. -cache.clear() // ⚠️ Очистить весь кеш. SWR проведёт ревалидацию при повторном рендеринге. ``` -You can use [`mutate`](/docs/mutation) to modify the cache. + + вы не должны писать в кеш напрямую, это может привести к неопределенному поведению. + + +You can use [`mutate`](/docs/mutation) to modify the cache. For example, you can clear all cache data like the following. + +```jsx +const { cache } = useSWRConfig() + +mutate( + key => true, // which cache keys are updated + undefined, // update cache data to `undefined` + { revalidate: false } // do not revalidate +) +``` + +More information can be found [here](/docs/arguments#multiple-arguments). diff --git a/pages/docs/advanced/cache.zh-CN.mdx b/pages/docs/advanced/cache.zh-CN.mdx index 8a9f0680..2ec72ca1 100644 --- a/pages/docs/advanced/cache.zh-CN.mdx +++ b/pages/docs/advanced/cache.zh-CN.mdx @@ -187,15 +187,22 @@ describe('test suite', async () => { }) ``` -### 访问缓存 +### Modify the Cache Data -警告:你不应该直接写入缓存,那样可能会导致不可预知的行为。 + + 你不应该直接写入缓存,那样可能会导致不可预知的行为。 + + +You can use [`mutate`](/docs/mutation) to modify the cache. For example, you can clear all cache data like the following. ```jsx const { cache } = useSWRConfig() -cache.get(key) // 获取 key 的当前数据。 -cache.clear() // ⚠️ 清除所有缓存。SWR 将在重新渲染时重新请求。 +mutate( + key => true, // which cache keys are updated + undefined, // update cache data to `undefined` + { revalidate: false } // do not revalidate +) ``` -You can use [`mutate`](/docs/mutation) to modify the cache. +More information can be found [here](/docs/arguments#multiple-arguments).