Skip to content

Commit

Permalink
docs: optimisticData can accept a function in v2 (#333)
Browse files Browse the repository at this point in the history
  • Loading branch information
koba04 committed Aug 24, 2022
1 parent 631726d commit 5647dac
Show file tree
Hide file tree
Showing 7 changed files with 175 additions and 7 deletions.
26 changes: 25 additions & 1 deletion pages/docs/mutation.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mutate(key, data, options)

## Options

- `optimisticData`: data to immediately update the client cache, usually used in optimistic UI.
- `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`: should the cache revalidate once the asynchronous update resolves.
- `populateCache`: should the result of the remote mutation be written to the cache.
- `populateCache`: 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.
Expand Down Expand Up @@ -80,6 +80,30 @@ function Profile () {

> The **`updateFn`** should be a promise or asynchronous function to handle the remote mutation, it should return updated data.
You can also pass a function to `optimisticData`.

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

function Profile () {
const { mutate } = useSWRConfig()
const { data } = useSWR('/api/user', fetcher)

return (
<div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
mutate('/api/user', updateUserName(newName), {
optimisticData: user => ({ ...data, name: newName }),
rollbackOnError: true
});
}}>Uppercase my name!</button>
</div>
)
}
```

## Mutate Based on Current Data

Sometimes, you want to update a part of your data based on the current data.
Expand Down
26 changes: 25 additions & 1 deletion pages/docs/mutation.es-ES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mutate(key, data, options)

## Options

- `optimisticData`: data to immediately update the client cache, usually used in optimistic UI.
- `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`: should the cache revalidate once the asynchronous update resolves.
- `populateCache`: 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`: should the cache rollback if the remote mutation errors.
Expand Down Expand Up @@ -77,6 +77,30 @@ function Profile () {

> The **`updateFn`** should be a promise or asynchronous function to handle the remote mutation, it should return updated data.
You can also pass a function to `optimisticData`.

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

function Profile () {
const { mutate } = useSWRConfig()
const { data } = useSWR('/api/user', fetcher)

return (
<div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
mutate('/api/user', updateUserName(newName), {
optimisticData: user => ({ ...data, name: newName }),
rollbackOnError: true
});
}}>Uppercase my name!</button>
</div>
)
}
```

## Mutar basándose en los datos actuales

A veces, se desea actualizar una parte de los datos en función de los datos actuales.
Expand Down
26 changes: 25 additions & 1 deletion pages/docs/mutation.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mutate(key, data, options)

## オプション

- `optimisticData`: クライアントキャッシュを直ちに更新するデータで、通常は 楽観的な UI で使用されます。
- `optimisticData`: クライアントキャッシュを直ちに更新するデータ、または現在の値を受け取り更新するデータを返す関数で、通常は 楽観的な UI で使用されます。
- `revalidate`: 非同期更新が解決した後、キャッシュを再検証するかどうか。
- `populateCache`: リモートミューテーションの結果をキャッシュに書き込むかどうか。関数も受け取ります。関数はミューテーションの結果と現在の値を引数として受けとり、ミューテーションの結果を返します。
- `rollbackOnError`: リモートミューテーションでエラーが発生した場合、キャッシュをロールバックするかどうか。
Expand Down Expand Up @@ -79,6 +79,30 @@ function Profile () {

> **`updateFn`** は、リモートミューテーションを処理するための promise 関数か非同期関数でなければならず、更新されたデータを返す必要があります。
`optimisticData` に関数を渡すこともできます。

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

function Profile () {
const { mutate } = useSWRConfig()
const { data } = useSWR('/api/user', fetcher)

return (
<div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
mutate('/api/user', updateUserName(newName), {
optimisticData: user => ({ ...data, name: newName }),
rollbackOnError: true
});
}}>Uppercase my name!</button>
</div>
)
}
```

## 現在のデータにもとづいたミューテート

現在のデータにもとづいて、データの一部を更新したい場合があります。
Expand Down
26 changes: 25 additions & 1 deletion pages/docs/mutation.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mutate(key, data, options)

## Options

- `optimisticData`: 클라이언트 캐시를 즉시 업데이트하기 위한 데이터. 일반적으로 낙관적인 UI에서 사용됩니다.
- `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`: 비동기 업데이트가 해소되면 캐시를 갱신합니다.
- `populateCache`: 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`: 원격 뮤테이션 에러 시 캐시를 롤백합니다.
Expand Down Expand Up @@ -79,6 +79,30 @@ function Profile () {

> **`updateFn`**은 원격 뮤테이션을 다루기 위한 promise 또는 비동기 함수여야 합니다. 업데이트한 데이터를 반환해야 합니다.
You can also pass a function to `optimisticData`.

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

function Profile () {
const { mutate } = useSWRConfig()
const { data } = useSWR('/api/user', fetcher)

return (
<div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
mutate('/api/user', updateUserName(newName), {
optimisticData: user => ({ ...data, name: newName }),
rollbackOnError: true
});
}}>Uppercase my name!</button>
</div>
)
}
```

## 현재 데이터를 기반으로 뮤테이트

현재 데이터를 기반으로 데이터의 일부를 업데이트하려는 경우가 있습니다.
Expand Down
26 changes: 25 additions & 1 deletion pages/docs/mutation.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mutate(key, data, options)

## Opções

- `optimisticData`: dados para serem atualizados imediatamente no cache do cliente, comumente usado para UI otimista.
- `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`: se o cache deve revalidar quando a atualização assíncrona resolve.
- `populateCache`: 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`: se o cache deve reverter se a mutação remota falhar.
Expand Down Expand Up @@ -78,6 +78,30 @@ function Profile () {

> **`updateFn`** deve ser uma promise ou uma função assíncrona para lidar com a mutação remota, e deve retornar os dados atualizados.
You can also pass a function to `optimisticData`.

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

function Profile () {
const { mutate } = useSWRConfig()
const { data } = useSWR('/api/user', fetcher)

return (
<div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
mutate('/api/user', updateUserName(newName), {
optimisticData: user => ({ ...data, name: newName }),
rollbackOnError: true
});
}}>Uppercase my name!</button>
</div>
)
}
```

## Mutação Baseada nos Dados Atuais

As vezes, você quer atualizar uma parte de seus dados baseado nos dados atuais.
Expand Down
26 changes: 25 additions & 1 deletion pages/docs/mutation.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mutate(key, data, options)

## Опции

- `optimisticData`: данные для немедленного обновления кеша клиента, обычно используемые в оптимистичном UI.
- `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`: должен ли кеш повторно проверяться после разрешения асинхронного обновления.
- `populateCache`: 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`: следует ли выполнять откат кеша в случае ошибок удаленной мутации.
Expand Down Expand Up @@ -75,6 +75,30 @@ function Profile () {

> **`updateFn`** должена быть промисом или асинхронной функцией для обработки удаленной мутации, она должна возвращать обновленные данные.
You can also pass a function to `optimisticData`.

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

function Profile () {
const { mutate } = useSWRConfig()
const { data } = useSWR('/api/user', fetcher)

return (
<div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
mutate('/api/user', updateUserName(newName), {
optimisticData: user => ({ ...data, name: newName }),
rollbackOnError: true
});
}}>Uppercase my name!</button>
</div>
)
}
```

## Мутировать на основе текущих данных

Иногда вы хотите обновить часть ваших данных на основе текущих данных.
Expand Down
26 changes: 25 additions & 1 deletion pages/docs/mutation.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Options

- `optimisticData`立即更新客户端缓存的数据,通常用于 optimistic UI
- `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`:一旦完成异步更新,缓存是否重新请求。
- `populateCache`: 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`:如果远程更新出错,是否进行缓存回滚。
Expand Down Expand Up @@ -70,6 +70,30 @@ function Profile () {
```
> **`updateFn`** 应该是一个 promise 或异步函数来处理远程更新,它应该返回更新后的数据。
You can also pass a function to `optimisticData`.

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

function Profile () {
const { mutate } = useSWRConfig()
const { data } = useSWR('/api/user', fetcher)

return (
<div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
mutate('/api/user', updateUserName(newName), {
optimisticData: user => ({ ...data, name: newName }),
rollbackOnError: true
});
}}>Uppercase my name!</button>
</div>
)
}
```

## 根据当前数据更改

有时,你想基于当前数据更新部分你的数据。
Expand Down

0 comments on commit 5647dac

Please sign in to comment.