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

Fetcher no longer accepts multiple arguments in v2 #326

Merged
merged 6 commits into from
Aug 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
9 changes: 7 additions & 2 deletions pages/docs/arguments.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,15 @@ even if `token` changes, SWR will still use the same key and return the wrong da
Instead, you can use an **array** as the `key` parameter, which contains multiple arguments of `fetcher`:

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))
```

The function `fetchWithToken` still accepts the same 2 arguments, but the cache key will also be associated with `token` now.
The `fetcher` function accepts the `key` parameter as is, and the cache key will also be associated with the entire `key` argument. In the above example, `url` and `token` are both tight to the cache key.

<Callout emoji="⚠️">
In the previous versions (< 2.0.0), The `fetcher` function will receive the spreaded arguments from original `key` when the `key` argument is array type. E.g., key `[url, token]` will become 2 arguments `(url, token)` for `fetcher` function.
</Callout>


## Passing Objects

Expand Down
8 changes: 6 additions & 2 deletions pages/docs/arguments.es-ES.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,14 @@ Esto es **incorrecto**. Dado que el identificador (también la key del caché) d
En su lugar, puedes utilizar un **array** como parámetro `key`, que contiene múltiples argumentos de `fetcher`:

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))
```

La función `fetchWithToken` sigue aceptando los mismo 2 argumentos, pero ahora la key del caché también estará asociada al `token`.
The `fetcher` function accepts the `key` parameter as is, and the cache key will also be associated with the entire `key` argument. In the above example, `url` and `token` are both tight to the cache key.

<Callout emoji="⚠️">
In older versions (< 2), The `fetcher` function accepts the `key` parameter as arguments separately
</Callout>

## Pasar objetos

Expand Down
8 changes: 6 additions & 2 deletions pages/docs/arguments.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ useSWR('/api/user', url => fetchWithToken(url, token))
代わりに、`fetcher` の複数の引数を含む**配列**を `key` パラメーターとして使用できます。

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))
```

この関数 `fetchWithToken` は引き続き同じ二つの引数を受け取りますが、キャッシュキーも `token` と関連付けられます。
`fetcher` 関数は `key` パラメータをそのまま受け取り、キャッシュキーもまた `key` の引数全てと関連づけられます。上記の例では `url` と `token` の組み合わせがキャッシュキーとなります。

<Callout emoji="⚠️">
In older versions (< 2), The `fetcher` function accepts the `key` parameter as arguments separately
</Callout>

## オブジェクトの受け渡し

Expand Down
8 changes: 6 additions & 2 deletions pages/docs/arguments.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ useSWR('/api/user', url => fetchWithToken(url, token))
대신에 `fetcher`의 다중 인자를 포함하는 **배열**을 `key` 파라미터로 사용할 수 있습니다.

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))
```

`fetchWithToken` 함수는 여전히 동일한 두 개의 인자를 받지만, 캐시 키는 이제 `token`과 연결되었습니다.
The `fetcher` function accepts the `key` parameter as is, and the cache key will also be associated with the entire `key` argument. In the above example, `url` and `token` are both tight to the cache key.

<Callout emoji="⚠️">
In older versions (< 2), The `fetcher` function accepts the `key` parameter as arguments separately
</Callout>

## 객체 전달

Expand Down
116 changes: 60 additions & 56 deletions pages/docs/arguments.pt-BR.md
Original file line number Diff line number Diff line change
@@ -1,56 +1,60 @@
# Argumentos

Por padrão, `key` será passado para `fetcher` como argumento. Então as 3 expressões a seguir são equivalentes:

```js
useSWR('/api/user', () => fetcher('/api/user'))
useSWR('/api/user', url => fetcher(url))
useSWR('/api/user', fetcher)
```

## Múltiplos Argumentos

Em alguns cenários, é útil passar vários argumentos (pode ser qualquer valor ou objeto) para a função `fetcher`.
Por exemplo, uma requisição de fetch autorizada:

```js
useSWR('/api/user', url => fetchWithToken(url, token))
```

Isso é **incorreto**. Porque o identificador (também a cache key) do dado é `'/api/user'`,
mesmo se `token` mudar, SWR ainda usará a mesma chave e retornará o dado errado.

Ao invés disso, você pode usar um array como o parâmetro `key`, que contém vários argumentos para a função `fetcher`.

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
```

A função `fetcherWithToken` ainda aceita os mesmos 2 argumentos, mas a cache key será associada com `token` agora.

## Passando Objetos

import Callout from 'nextra-theme-docs/callout'

<Callout>
Desde a versão 1.1.0, chaves de objeto serão serializadas por baixo dos panos automaticamente.
</Callout>

Digamos que você tenha outra função que busca dados com um escopo de usuário: `fetchWithUser(api, user)`. Você pode fazer o seguinte:

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)

// ...e então passá-lo como argumento para outro hook useSWR
const { data: orders } = useSWR(user ? ['/api/orders', user] : null, fetchWithUser)
```

Você pode passar diretamente um objeto como chave, e `fetcher` receberá esse objeto também:

```js
const { data: orders } = useSWR({ url: '/api/orders', args: user }, fetcher)
```

<Callout emoji="⚠️">
Em versões antigas (< 1.1.0), SWR compara os argumentos **superficialmente** em cada renderização e aciona a revalidação se algum deles foi alterado.
</Callout>
# Argumentos

Por padrão, `key` será passado para `fetcher` como argumento. Então as 3 expressões a seguir são equivalentes:

```js
useSWR('/api/user', () => fetcher('/api/user'))
useSWR('/api/user', url => fetcher(url))
useSWR('/api/user', fetcher)
```

## Múltiplos Argumentos

Em alguns cenários, é útil passar vários argumentos (pode ser qualquer valor ou objeto) para a função `fetcher`.
Por exemplo, uma requisição de fetch autorizada:

```js
useSWR('/api/user', url => fetchWithToken(url, token))
```

Isso é **incorreto**. Porque o identificador (também a cache key) do dado é `'/api/user'`,
mesmo se `token` mudar, SWR ainda usará a mesma chave e retornará o dado errado.

Ao invés disso, você pode usar um array como o parâmetro `key`, que contém vários argumentos para a função `fetcher`.

```js
const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))
```

The `fetcher` function accepts the `key` parameter as is, and the cache key will also be associated with the entire `key` argument. In the above example, `url` and `token` are both tight to the cache key.

<Callout emoji="⚠️">
In older versions (< 2), The `fetcher` function accepts the `key` parameter as arguments separately
</Callout>

## Passando Objetos

import Callout from 'nextra-theme-docs/callout'

<Callout>
Desde a versão 1.1.0, chaves de objeto serão serializadas por baixo dos panos automaticamente.
</Callout>

Digamos que você tenha outra função que busca dados com um escopo de usuário: `fetchWithUser(api, user)`. Você pode fazer o seguinte:

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)

// ...e então passá-lo como argumento para outro hook useSWR
const { data: orders } = useSWR(user ? ['/api/orders', user] : null, fetchWithUser)
```

Você pode passar diretamente um objeto como chave, e `fetcher` receberá esse objeto também:

```js
const { data: orders } = useSWR({ url: '/api/orders', args: user }, fetcher)
```

<Callout emoji="⚠️">
Em versões antigas (< 1.1.0), SWR compara os argumentos **superficialmente** em cada renderização e aciona a revalidação se algum deles foi alterado.
</Callout>
8 changes: 6 additions & 2 deletions pages/docs/arguments.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,14 @@ useSWR('/api/user', url => fetchWithToken(url, token))
Вместо этого вы можете использовать **массив** в качестве параметра `key`, который содержит несколько аргументов `fetcher`:

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))
```

Функция `fetchWithToken` по-прежнему принимает те же 2 аргумента, но ключ кеша теперь также будет связан с `token`.
The `fetcher` function accepts the `key` parameter as is, and the cache key will also be associated with the entire `key` argument. In the above example, `url` and `token` are both tight to the cache key.

<Callout emoji="⚠️">
In older versions (< 2), The `fetcher` function accepts the `key` parameter as arguments separately
</Callout>

## Передача объектов

Expand Down
8 changes: 6 additions & 2 deletions pages/docs/arguments.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@ useSWR('/api/user', url => fetchWithToken(url, token))
相反,你可以使用一个 **数组** 作为参数 `key`,它包含 `fetcher` 的多个参数:

```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
const { data: user } = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url, token))
```

`fetchWithToken` 函数仍然接受同样的2个参数,但现在缓存 key 也将与 `token` 相关联。
The `fetcher` function accepts the `key` parameter as is, and the cache key will also be associated with the entire `key` argument. In the above example, `url` and `token` are both tight to the cache key.

<Callout emoji="⚠️">
In older versions (< 2), The `fetcher` function accepts the `key` parameter as arguments separately
</Callout>

## 传入对象

Expand Down
4 changes: 2 additions & 2 deletions pages/docs/typescript.en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ useSWR({ a: '1', b: { c: '3', d: 2 } }, key => {})
useSWR(() => { a: '1', b: { c: '3', d: 2 } }, key => {})

// `arg0` will be inferred as string. `arg1` will be inferred as number
useSWR(['user', 8], (arg0, arg1) => {})
useSWR(() => ['user', 8], (arg0, arg1) => {})
useSWR(['user', 8], ([arg0, arg1]) => {})
useSWR(() => ['user', 8], ([arg0, arg1]) => {})
```

You can also explicitly specify the types for `key` and `fetcher`'s arguments.
Expand Down
4 changes: 2 additions & 2 deletions pages/docs/typescript.es-ES.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ useSWR({ a: '1', b: { c: '3', d: 2 } }, key => {})
useSWR(() => { a: '1', b: { c: '3', d: 2 } }, key => {})

// `arg0` will be inferred as string. `arg1` will be inferred as number
useSWR(['user', 8], (arg0, arg1) => {})
useSWR(() => ['user', 8], (arg0, arg1) => {})
useSWR(['user', 8], ([arg0, arg1]) => {})
useSWR(() => ['user', 8], ([arg0, arg1]) => {})
```

You can also explicitly specify the types for `key` and `fetcher`'s arguments.
Expand Down
4 changes: 2 additions & 2 deletions pages/docs/typescript.ja.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ useSWR({ a: '1', b: { c: '3', d: 2 } }, key => {})
useSWR(() => { a: '1', b: { c: '3', d: 2 } }, key => {})

// `arg0` は文字列として推測されます。 `arg1` は数値として推測されます。
useSWR(['user', 8], (arg0, arg1) => {})
useSWR(() => ['user', 8], (arg0, arg1) => {})
useSWR(['user', 8], ([arg0, arg1]) => {})
useSWR(() => ['user', 8], ([arg0, arg1]) => {})
```

`key` と `fetcher` の引数の型を明示的に指定することもできます。
Expand Down
5 changes: 3 additions & 2 deletions pages/docs/typescript.ko.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ useSWR(() => '/api/user', key => {})
useSWR({ a: '1', b: { c: '3', d: 2 } }, key => {})
useSWR(() => { a: '1', b: { c: '3', d: 2 } }, key => {})


// `arg0`은 stirng으로 추론됨. `arg1`은 number로 추론됨
useSWR(['user', 8], (arg0, arg1) => {})
useSWR(() => ['user', 8], (arg0, arg1) => {})
useSWR(['user', 8], ([arg0, arg1]) => {})
useSWR(() => ['user', 8], ([arg0, arg1]) => {})
```

명시적으로 `key`와 `fetcher`의 인자에 대한 타입을 지정할 수도 있습니다.
Expand Down