From 59f4fc32c72568fa76fed1da787c03f1ee384c06 Mon Sep 17 00:00:00 2001 From: Giovanni Gualiato Date: Sat, 26 Jul 2025 00:39:31 +0100 Subject: [PATCH 1/3] docs: add onSuccess callback details to API documentation --- pages/docs/advanced/understanding.en-US.mdx | 73 +++++++++++++++++++++ pages/docs/api.en-US.mdx | 2 +- 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/pages/docs/advanced/understanding.en-US.mdx b/pages/docs/advanced/understanding.en-US.mdx index 440ab82e..4f5ecdab 100644 --- a/pages/docs/advanced/understanding.en-US.mdx +++ b/pages/docs/advanced/understanding.en-US.mdx @@ -123,3 +123,76 @@ You can find the full code for this example here: https://codesandbox.io/s/swr-k ## Dependency Collection for performance [#dependency-collection-for-performance] SWR only triggers re-rendering when the states used in the component have been updated. If you only use `data` in the component, SWR ignores the updates of other properties like `isValidating`, and `isLoading`. This reduces rendering counts a lot. More information can be found [here](/docs/advanced/performance#dependency-collection). + +## onSuccess Callback [#on-success-callback] + +Sometimes you may want to run some side effects right after the data is fetched successfully. You can use the `onSuccess` callback option to do that. + +```jsx +const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data, key, config) => { + // Track successful API calls + analytics.track('API Success', { + endpoint: key, + timestamp: new Date(), + data: data + }); + } +}); +``` + +SWR will call the `onSuccess` callback with the fetched data, the key, and the config object. This is useful for analytics, logging, or any other side effects you want to perform after a successful fetch. + +### `onSuccess` with deduplication + +One of the features of SWR is deduplication, which means that if the same key is being used in multiple places at the same time, SWR will only fetch the data once and share it among those components. + +Only the first `onSuccess` callback defined will be called for the first successful fetch, even if `onSuccess` is defined in multiple places. + +Example: + +```jsx +const FirstComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will be called + console.log('First component success:', data); + } + }); + return
{data?.name}
; +}; + +const SecondComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will NOT be called + console.log('Second component success:', data); + } + }); + return
{data?.email}
; +}; + +const App = () => ( + <> + + + +); +``` + +The example above will only log the success message from the first component when the data is fetched successfully, even though both components have their own `onSuccess` callbacks. This is because SWR deduplicates requests for the same key. + +For this reason, you should avoid using `onSuccess` to set local state in the `onSuccess` callback, as it may lead to unexpected behavior when multiple components are using the same key. + +Also, the `onSuccess` callback is not called when the data is loaded from the cache, only when it is fetched from the network. If you need to run side effects for cached data, consider using the `useEffect` hook in combination with SWR's data. + +```jsx +const { data } = useSWR('/api/user', fetcher); + +useEffect(() => { + if (data) { + // Run side effects for cached data + console.log('Cached data:', data); + } +}, [data]); +``` diff --git a/pages/docs/api.en-US.mdx b/pages/docs/api.en-US.mdx index f521ca9c..c6acda67 100644 --- a/pages/docs/api.en-US.mdx +++ b/pages/docs/api.en-US.mdx @@ -47,7 +47,7 @@ More information can be found [here](/docs/advanced/understanding). - `fallbackData`: initial data to be returned (note: This is per-hook) - `keepPreviousData = false`: return the previous key's data until the new data has been loaded [(details)](/docs/advanced/understanding#return-previous-data-for-better-ux) - `onLoadingSlow(key, config)`: callback function when a request takes too long to load (see `loadingTimeout`) -- `onSuccess(data, key, config)`: callback function when a request finishes successfully +- `onSuccess(data, key, config)`: callback function when a request finishes successfully [(details)](/docs/advanced/understanding#on-success-callback) - `onError(err, key, config)`: callback function when a request returns an error - `onErrorRetry(err, key, config, revalidate, revalidateOps)`: handler for error retry - `onDiscarded(key)`: callback function when a request is ignored due to race conditions From e9532a8b4f389c22026f29d5a836c9d0c29fd375 Mon Sep 17 00:00:00 2001 From: Giovanni Gualiato Date: Sat, 26 Jul 2025 00:55:08 +0100 Subject: [PATCH 2/3] docs: add details to onSuccess callback in API documentation across multiple languages --- pages/docs/api.es-ES.mdx | 2 +- pages/docs/api.fr-FR.mdx | 2 +- pages/docs/api.ja.mdx | 2 +- pages/docs/api.ko.mdx | 2 +- pages/docs/api.pt-BR.mdx | 4 ++-- pages/docs/api.ru.mdx | 2 +- pages/docs/api.zh-CN.mdx | 4 ++-- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/pages/docs/api.es-ES.mdx b/pages/docs/api.es-ES.mdx index 70eaf1b7..4a91a11a 100644 --- a/pages/docs/api.es-ES.mdx +++ b/pages/docs/api.es-ES.mdx @@ -47,7 +47,7 @@ Puede encontrar más información [aquí](/docs/advanced/understanding). - `fallbackData`: datos iniciales a devolver (nota: Esto es por un hook) - `keepPreviousData = false`: devuelve la data anterior de la key hasta que se hayan cargado los nuevos datos [(detalles)](/docs/advanced/understanding#return-previous-data-for-better-ux) - `onLoadingSlow(key, config)`: función callback cuando una petición tarda demasiado en cargase (véase: `loadingTimeout`) -- `onSuccess(data, key, config)`: función callback cuando una petición termina con éxito +- `onSuccess(data, key, config)`: función callback cuando una petición termina con éxito [(details)](/docs/advanced/understanding#on-success-callback) - `onError(err, key, config)`: función callback cuando una petición devuelve un error - `onErrorRetry(err, key, config, revalidate, revalidateOps)`: manejador para el reintento de error - `onDiscarded(key)`: funciòn callback cuando una solicitud es ignorada debido a condiciones de carrera(race conditions) diff --git a/pages/docs/api.fr-FR.mdx b/pages/docs/api.fr-FR.mdx index de1ed28b..dd16c3f8 100644 --- a/pages/docs/api.fr-FR.mdx +++ b/pages/docs/api.fr-FR.mdx @@ -46,7 +46,7 @@ Plus d'informations [ici](/docs/advanced/understanding). - `fallbackData`: données initiales à renvoyer (note : ceci est per-hook) - `keepPreviousData = false`: renvoyer les données de la clé précédente jusqu'à ce que les nouvelles données soient chargées [(détails)](/docs/advanced/understanding#return-previous-data-for-better-ux) - `onLoadingSlow(key, config)`: fonction de rappel lorsqu'une requête prend trop de temps à charger (voir `loadingTimeout`) -- `onSuccess(data, key, config)`: fonction de rappel lorsqu'une requête se termine avec succès +- `onSuccess(data, key, config)`: fonction de rappel lorsqu'une requête se termine avec succès [(details)](/docs/advanced/understanding#on-success-callback) - `onError(err, key, config)`: fonction de rappel lorsqu'une requête renvoie une erreur - `onErrorRetry(err, key, config, revalidate, revalidateOps)`: gestionnaire des nouvelles tentatives d'erreur - `onDiscarded(key)`: fonction de rappel lorsqu'une requête est ignorée en raison de conditions de course diff --git a/pages/docs/api.ja.mdx b/pages/docs/api.ja.mdx index ae9fe84e..b0e4127f 100644 --- a/pages/docs/api.ja.mdx +++ b/pages/docs/api.ja.mdx @@ -46,7 +46,7 @@ const { data, error, isLoading, isValidating, mutate } = useSWR(key, fetcher, op - `fallbackData`: 返される初期データ(注:フックごとに) - `keepPreviousData = false`: 新しいキーに対するデータがロードされるまで以前のキーのデータを返すかどうか [(詳細)](/docs/advanced/understanding#return-previous-data-for-better-ux) - `onLoadingSlow(key, config)`: リクエストの読み込みに時間がかかりすぎる場合のコールバック関数(`loadingTimeout` を参照してください) -- `onSuccess(data, key, config)`: リクエストが正常に終了したときのコールバック関数 +- `onSuccess(data, key, config)`: リクエストが正常に終了したときのコールバック関数 [(details)](/docs/advanced/understanding#on-success-callback) - `onError(err, key, config)`: リクエストがエラーを返したときのコールバック関数 - `onErrorRetry(err, key, config, revalidate, revalidateOps)`: エラー再試行のハンドラー - `onDiscarded(key)`: レースコンディションによりリクエストが無視されたときのコールバック関数 diff --git a/pages/docs/api.ko.mdx b/pages/docs/api.ko.mdx index 191ac53a..b8f0f032 100644 --- a/pages/docs/api.ko.mdx +++ b/pages/docs/api.ko.mdx @@ -46,7 +46,7 @@ const { data, error, isLoading, isValidating, mutate } = useSWR(key, fetcher, op - `fallbackData`: 반환될 초기 데이터(노트: hook 별로 존재) - `keepPreviousData = false`: 새 데이터가 로드될 때까지 이전 키의 데이터를 반환 [(상세내용)](/docs/advanced/understanding#return-previous-data-for-better-ux) - `onLoadingSlow(key, config)`: 요청을 로드하는 데 너무 오래 걸리는 경우의 콜백 함수(`loadingTimeout`을 보세요) -- `onSuccess(data, key, config)`: 요청이 성공적으로 종료되었을 경우의 콜백 함수 +- `onSuccess(data, key, config)`: 요청이 성공적으로 종료되었을 경우의 콜백 함수 [(details)](/docs/advanced/understanding#on-success-callback) - `onError(err, key, config)`: 요청이 에러를 반환했을 경우의 콜백 함수 - `onErrorRetry(err, key, config, revalidate, revalidateOps)`: 에러 재시도 핸들러 - `onDiscarded(key)`: 경합 상태(race condition)로 인해 요청이 무시될 경우 실행되는 콜백 함수 diff --git a/pages/docs/api.pt-BR.mdx b/pages/docs/api.pt-BR.mdx index 35df7944..b29235fd 100644 --- a/pages/docs/api.pt-BR.mdx +++ b/pages/docs/api.pt-BR.mdx @@ -46,13 +46,13 @@ More information can be found [here](/docs/advanced/understanding). - `fallbackData`: dados iniciais para ser retornado (nota: isto é por-hook) - `keepPreviousData = false`: return the previous key's data until the new data has been loaded [(detalhes)](/docs/advanced/understanding#return-previous-data-for-better-ux) - `onLoadingSlow(key, config)`: função callback quando um pedido demora muito tempo a carregar (veja `loadingTimeout`) -- `onSuccess(data, key, config)`: função callback quando um pedido é bem-sucedido +- `onSuccess(data, key, config)`: função callback quando um pedido é bem-sucedido [(detalhes)](/docs/advanced/understanding#on-success-callback) - `onError(err, key, config)`: função callback quando um pedido retorna um erro - `onErrorRetry(err, key, config, revalidate, revalidateOps)`: função callback quando um pedido retorna um erro - `onDiscarded(key)`: callback function when a request is ignored due to race conditions - `compare(a, b)`: função de comparação para detectar quando o dado retornado está diferente, para evitar rerenderizações desnecessárias. Por padrão, [stable-hash](https://github.com/shuding/stable-hash) é usado. - `isPaused()`: função para detectar quando o revalidador está pausado, e deve ignorar os dados e erros quando retorna `true`. Por padrão, retorna `false`. -- `use`: array de middleware functions [(details)](/docs/middleware) +- `use`: array de middleware functions [(detalhes)](/docs/middleware) diff --git a/pages/docs/api.ru.mdx b/pages/docs/api.ru.mdx index 087f912f..b2a7c058 100644 --- a/pages/docs/api.ru.mdx +++ b/pages/docs/api.ru.mdx @@ -46,7 +46,7 @@ const { data, error, isLoading, isValidating, mutate } = useSWR(key, fetcher, op - `fallbackData`: исходные данные, которые должны быть возвращены (примечание: это для каждого хука) - `keepPreviousData = false`: возвращать данные предыдущего ключа, пока не будут загружены новые данные [(подробнее)](/docs/advanced/understanding#возврат-предыдущих-данных-для-лучшего-ux) - `onLoadingSlow(key, config)`: колбэк-функция, когда запрос загружается слишком долго (см. `loadingTimeout`) -- `onSuccess(data, key, config)`: колбэк-функция при успешном завершении запроса +- `onSuccess(data, key, config)`: колбэк-функция при успешном завершении запроса [(details)](/docs/advanced/understanding#on-success-callback) - `onError(err, key, config)`: колбэк-функция, когда запрос возвращает ошибку - `onErrorRetry(err, key, config, revalidate, revalidateOps)`: обработчик повторной попытки при ошибке - `onDiscarded(key)`: колбэк-функция, когда запрос игнорируется из-за состояния гонки diff --git a/pages/docs/api.zh-CN.mdx b/pages/docs/api.zh-CN.mdx index 0ea485b9..2b6b6b54 100644 --- a/pages/docs/api.zh-CN.mdx +++ b/pages/docs/api.zh-CN.mdx @@ -16,7 +16,7 @@ const { data, error, isLoading, isValidating, mutate } = useSWR(key, fetcher, op - `data`: 通过 `fetcher` 用给定的 key 获取的数据(如未完全加载,返回 undefined) - `error`: `fetcher` 抛出的错误(或者是 undefined) -- `isLoading`: 是否有一个正在进行中的请求且当前没有“已加载的数据“。预设数据及之前的数据不会被视为“已加载的数据“ +- `isLoading`: 是否有一个正在进行中的请求且当前没有“已加载的数据“。预设数据及之前的数据不会被视为“已加载的数据“ - `isValidating`: 是否有请求或重新验证加载 - `mutate(data?, options?)`: 更改缓存数据的函数 [(详情)](/docs/mutation) @@ -46,7 +46,7 @@ const { data, error, isLoading, isValidating, mutate } = useSWR(key, fetcher, op - `fallbackData`: 此 hook 需要返回的初始数据 - `keepPreviousData = false`: 在新数据加载完成之前使用 key 上一次缓存过的数据 [(详情)](/docs/advanced/understanding#return-previous-data-for-better-ux) - `onLoadingSlow(key, config)`: 请求加载时间过长时的回调函数(参考 `loadingTimeout`) -- `onSuccess(data, key, config)`: 请求成功完成时的回调函数 +- `onSuccess(data, key, config)`: 请求成功完成时的回调函数 [(details)](/docs/advanced/understanding#on-success-callback) - `onError(err, key, config)`: 请求返回错误时的回调函数 - `onErrorRetry(err, key, config, revalidate, revalidateOps)`: 错误重试的处理函数 - `onDiscarded(key)`: 请求由于竞态条件而被忽略时的回调函数 From ba8574b91515d4fa4a20ea1b9fbbd295c37f3e8b Mon Sep 17 00:00:00 2001 From: Giovanni Gualiato Date: Sat, 26 Jul 2025 01:17:02 +0100 Subject: [PATCH 3/3] docs: add onSuccess callback section to understanding documentation in multiple languages --- pages/docs/advanced/understanding.es-ES.mdx | 73 ++++++++++++++++++++ pages/docs/advanced/understanding.fr-FR.mdx | 73 ++++++++++++++++++++ pages/docs/advanced/understanding.ja.mdx | 73 ++++++++++++++++++++ pages/docs/advanced/understanding.ko.mdx | 73 ++++++++++++++++++++ pages/docs/advanced/understanding.pt-BR.mdx | 73 ++++++++++++++++++++ pages/docs/advanced/understanding.ru.mdx | 73 ++++++++++++++++++++ pages/docs/advanced/understanding.zh-CN.mdx | 74 ++++++++++++++++++++- 7 files changed, 511 insertions(+), 1 deletion(-) diff --git a/pages/docs/advanced/understanding.es-ES.mdx b/pages/docs/advanced/understanding.es-ES.mdx index 440ab82e..4f5ecdab 100644 --- a/pages/docs/advanced/understanding.es-ES.mdx +++ b/pages/docs/advanced/understanding.es-ES.mdx @@ -123,3 +123,76 @@ You can find the full code for this example here: https://codesandbox.io/s/swr-k ## Dependency Collection for performance [#dependency-collection-for-performance] SWR only triggers re-rendering when the states used in the component have been updated. If you only use `data` in the component, SWR ignores the updates of other properties like `isValidating`, and `isLoading`. This reduces rendering counts a lot. More information can be found [here](/docs/advanced/performance#dependency-collection). + +## onSuccess Callback [#on-success-callback] + +Sometimes you may want to run some side effects right after the data is fetched successfully. You can use the `onSuccess` callback option to do that. + +```jsx +const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data, key, config) => { + // Track successful API calls + analytics.track('API Success', { + endpoint: key, + timestamp: new Date(), + data: data + }); + } +}); +``` + +SWR will call the `onSuccess` callback with the fetched data, the key, and the config object. This is useful for analytics, logging, or any other side effects you want to perform after a successful fetch. + +### `onSuccess` with deduplication + +One of the features of SWR is deduplication, which means that if the same key is being used in multiple places at the same time, SWR will only fetch the data once and share it among those components. + +Only the first `onSuccess` callback defined will be called for the first successful fetch, even if `onSuccess` is defined in multiple places. + +Example: + +```jsx +const FirstComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will be called + console.log('First component success:', data); + } + }); + return
{data?.name}
; +}; + +const SecondComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will NOT be called + console.log('Second component success:', data); + } + }); + return
{data?.email}
; +}; + +const App = () => ( + <> + + + +); +``` + +The example above will only log the success message from the first component when the data is fetched successfully, even though both components have their own `onSuccess` callbacks. This is because SWR deduplicates requests for the same key. + +For this reason, you should avoid using `onSuccess` to set local state in the `onSuccess` callback, as it may lead to unexpected behavior when multiple components are using the same key. + +Also, the `onSuccess` callback is not called when the data is loaded from the cache, only when it is fetched from the network. If you need to run side effects for cached data, consider using the `useEffect` hook in combination with SWR's data. + +```jsx +const { data } = useSWR('/api/user', fetcher); + +useEffect(() => { + if (data) { + // Run side effects for cached data + console.log('Cached data:', data); + } +}, [data]); +``` diff --git a/pages/docs/advanced/understanding.fr-FR.mdx b/pages/docs/advanced/understanding.fr-FR.mdx index a604c826..714483fe 100644 --- a/pages/docs/advanced/understanding.fr-FR.mdx +++ b/pages/docs/advanced/understanding.fr-FR.mdx @@ -122,3 +122,76 @@ Vous pouvez trouver l'exemple [ici](https://codesandbox.io/s/swr-keeppreviousdat ## Collection de dépendances pour les performances [#dependency-collection-for-performance] SWR ne déclenche le re-rendering que lorsque les états utilisés dans le composant ont été mis à jour. Si vous n'utilisez que `data` dans le composant, SWR ignore les mises à jour des autres propriétés comme `isValidating` et `isLoading`. Cela réduit considérablement le nombre de rendus. Vous pouvez trouver plus d'informations [ici](/docs/advanced/performance#dependency-collection). + +## onSuccess Callback [#on-success-callback] + +Sometimes you may want to run some side effects right after the data is fetched successfully. You can use the `onSuccess` callback option to do that. + +```jsx +const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data, key, config) => { + // Track successful API calls + analytics.track('API Success', { + endpoint: key, + timestamp: new Date(), + data: data + }); + } +}); +``` + +SWR will call the `onSuccess` callback with the fetched data, the key, and the config object. This is useful for analytics, logging, or any other side effects you want to perform after a successful fetch. + +### `onSuccess` with deduplication + +One of the features of SWR is deduplication, which means that if the same key is being used in multiple places at the same time, SWR will only fetch the data once and share it among those components. + +Only the first `onSuccess` callback defined will be called for the first successful fetch, even if `onSuccess` is defined in multiple places. + +Example: + +```jsx +const FirstComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will be called + console.log('First component success:', data); + } + }); + return
{data?.name}
; +}; + +const SecondComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will NOT be called + console.log('Second component success:', data); + } + }); + return
{data?.email}
; +}; + +const App = () => ( + <> + + + +); +``` + +The example above will only log the success message from the first component when the data is fetched successfully, even though both components have their own `onSuccess` callbacks. This is because SWR deduplicates requests for the same key. + +For this reason, you should avoid using `onSuccess` to set local state in the `onSuccess` callback, as it may lead to unexpected behavior when multiple components are using the same key. + +Also, the `onSuccess` callback is not called when the data is loaded from the cache, only when it is fetched from the network. If you need to run side effects for cached data, consider using the `useEffect` hook in combination with SWR's data. + +```jsx +const { data } = useSWR('/api/user', fetcher); + +useEffect(() => { + if (data) { + // Run side effects for cached data + console.log('Cached data:', data); + } +}, [data]); +``` diff --git a/pages/docs/advanced/understanding.ja.mdx b/pages/docs/advanced/understanding.ja.mdx index 77c53fcc..dab4ed1d 100644 --- a/pages/docs/advanced/understanding.ja.mdx +++ b/pages/docs/advanced/understanding.ja.mdx @@ -123,3 +123,76 @@ function Search() { ## パフォーマンスのための依存収集 [#dependency-collection-for-performance] SWR はコンポーネントで使われているデータが更新された場合のみ再レンダリングします。コンポーネントの中で `data` しか使っていない場合、SWR は `isValidating` や `isLoading` のプロパティの更新を無視します。これはレンダリングの回数を減らします。詳細については [こちら](/docs/advanced/performance#dependency-collection)。 + +## onSuccess Callback [#on-success-callback] + +Sometimes you may want to run some side effects right after the data is fetched successfully. You can use the `onSuccess` callback option to do that. + +```jsx +const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data, key, config) => { + // Track successful API calls + analytics.track('API Success', { + endpoint: key, + timestamp: new Date(), + data: data + }); + } +}); +``` + +SWR will call the `onSuccess` callback with the fetched data, the key, and the config object. This is useful for analytics, logging, or any other side effects you want to perform after a successful fetch. + +### `onSuccess` with deduplication + +One of the features of SWR is deduplication, which means that if the same key is being used in multiple places at the same time, SWR will only fetch the data once and share it among those components. + +Only the first `onSuccess` callback defined will be called for the first successful fetch, even if `onSuccess` is defined in multiple places. + +Example: + +```jsx +const FirstComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will be called + console.log('First component success:', data); + } + }); + return
{data?.name}
; +}; + +const SecondComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will NOT be called + console.log('Second component success:', data); + } + }); + return
{data?.email}
; +}; + +const App = () => ( + <> + + + +); +``` + +The example above will only log the success message from the first component when the data is fetched successfully, even though both components have their own `onSuccess` callbacks. This is because SWR deduplicates requests for the same key. + +For this reason, you should avoid using `onSuccess` to set local state in the `onSuccess` callback, as it may lead to unexpected behavior when multiple components are using the same key. + +Also, the `onSuccess` callback is not called when the data is loaded from the cache, only when it is fetched from the network. If you need to run side effects for cached data, consider using the `useEffect` hook in combination with SWR's data. + +```jsx +const { data } = useSWR('/api/user', fetcher); + +useEffect(() => { + if (data) { + // Run side effects for cached data + console.log('Cached data:', data); + } +}, [data]); +``` diff --git a/pages/docs/advanced/understanding.ko.mdx b/pages/docs/advanced/understanding.ko.mdx index ee83c5d5..f4b0099e 100644 --- a/pages/docs/advanced/understanding.ko.mdx +++ b/pages/docs/advanced/understanding.ko.mdx @@ -125,3 +125,76 @@ function Search() { ## 성능을 위한 의존성 수집 [#dependency-collection-for-performance] SWR은 컴포넌트에서 사용된 상태가 업데이트될 때만 리렌더링을 트리거합니다. 즉, 컴포넌트에서 `data`만 사용한다면, SWR은 `isValidating`이나 `isLoading` 같은 다른 속성의 변경을 무시합니다. 이를 통해 렌더링 횟수를 크게 줄일 수 있습니다. 더 자세한 내용은 [여기](/docs/advanced/performance#dependency-collection)에서 확인할 수 있습니다. + +## onSuccess Callback [#on-success-callback] + +Sometimes you may want to run some side effects right after the data is fetched successfully. You can use the `onSuccess` callback option to do that. + +```jsx +const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data, key, config) => { + // Track successful API calls + analytics.track('API Success', { + endpoint: key, + timestamp: new Date(), + data: data + }); + } +}); +``` + +SWR will call the `onSuccess` callback with the fetched data, the key, and the config object. This is useful for analytics, logging, or any other side effects you want to perform after a successful fetch. + +### `onSuccess` with deduplication + +One of the features of SWR is deduplication, which means that if the same key is being used in multiple places at the same time, SWR will only fetch the data once and share it among those components. + +Only the first `onSuccess` callback defined will be called for the first successful fetch, even if `onSuccess` is defined in multiple places. + +Example: + +```jsx +const FirstComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will be called + console.log('First component success:', data); + } + }); + return
{data?.name}
; +}; + +const SecondComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will NOT be called + console.log('Second component success:', data); + } + }); + return
{data?.email}
; +}; + +const App = () => ( + <> + + + +); +``` + +The example above will only log the success message from the first component when the data is fetched successfully, even though both components have their own `onSuccess` callbacks. This is because SWR deduplicates requests for the same key. + +For this reason, you should avoid using `onSuccess` to set local state in the `onSuccess` callback, as it may lead to unexpected behavior when multiple components are using the same key. + +Also, the `onSuccess` callback is not called when the data is loaded from the cache, only when it is fetched from the network. If you need to run side effects for cached data, consider using the `useEffect` hook in combination with SWR's data. + +```jsx +const { data } = useSWR('/api/user', fetcher); + +useEffect(() => { + if (data) { + // Run side effects for cached data + console.log('Cached data:', data); + } +}, [data]); +``` diff --git a/pages/docs/advanced/understanding.pt-BR.mdx b/pages/docs/advanced/understanding.pt-BR.mdx index cfd1663a..6095ab3e 100644 --- a/pages/docs/advanced/understanding.pt-BR.mdx +++ b/pages/docs/advanced/understanding.pt-BR.mdx @@ -123,3 +123,76 @@ Você pode achar o código completo para esse exemplo aqui: (https://codesandbox ## Coleção de Dependência para performance [#dependency-collection-for-performance] SWR apenas aciona a nova renderização quando os estados usados no componente forem atualizados. Se você apenas usar `data` no componente, o SWR irá ignorar as atualizações das outras propriedades como `isValidating` e `isLoading`. Isso reduz bastante o número de renderizações. Mais informações podem ser encontradas [aqui](/docs/advanced/performance#dependency-collection). + +## onSuccess Callback [#on-success-callback] + +Algumas vezes você pode querer rodar algum side-effect logo após seus dados serem requisitados com sucesso. Você pode usar a opçãp de callback `onSuccess` para fazer isso. + +```jsx +const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data, key, config) => { + // Registra uma chamada de API com sucesso + analytics.track('API Sucesso', { + endpoint: key, + timestamp: new Date(), + data: data + }); + } +}); +``` + +SWR vai chamar o callback `onSuccess` com o dado retornado, a chave, e o objeto de configuração. Isso é bastante útil para analytics, logging, ou qualquer outro side effect que você queira rodar depois de uma requisição bem-sucedida. + +### `onSuccess` com deduplicação + +Uma das features do SWR é a deduplicação, que significa que se a mesma chave estiver sendo usada em multiplos lugares ao mesmo tempo, o SWR vai fazer apenas uma requisisção e compartilhar o dado retornado entre os componentes. + +Somente a primeira função de callback `onSuccess` definida vai ser chamada para a primeira requisição feita com sucesso, mesmo se `onSuccess` estiver definido em multiplos lugares. + +Exemplo: + +```jsx +const FirstComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // esse callback onSuccess será chamado + console.log('Primeiro component successo:', data); + } + }); + return
{data?.name}
; +}; + +const SecondComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // esse callback onSuccess NÃO será chamado + console.log('Segundo componente successo:', data); + } + }); + return
{data?.email}
; +}; + +const App = () => ( + <> + + + +); +``` + +O exemplo acima vai logar apenas a mensagem de sucesso do primeiro componente quando os dados forem retornados com sucesso, mesmo que ambos os componentes tenham seus próprios callbacks `onSuccess`. Isso acontece porque o SWR deduplica as requisições para a mesma chave. + +Por essa razão, você deve evitar user `onSuccess` para atualizar estado local, já que isso pode levar a comportamentes inexperados quando multiplos componente estiverem usando a mesma chave. + +Também, o callback `onSuccess` não é chamado quando o dados for carregado do cache, somente quando for retordado da rede. Se você precisa rodar qualquer side effect para dados cacheados, considere usar o hook `useEffect` em combinação com os dados do SWR. + +```jsx +const { data } = useSWR('/api/user', fetcher); + +useEffect(() => { + if (data) { + // Executar side effects para dados cacheados + console.log('Cached data:', data); + } +}, [data]); +``` diff --git a/pages/docs/advanced/understanding.ru.mdx b/pages/docs/advanced/understanding.ru.mdx index 76e54393..2b7d33d9 100644 --- a/pages/docs/advanced/understanding.ru.mdx +++ b/pages/docs/advanced/understanding.ru.mdx @@ -123,3 +123,76 @@ function Search() { ## Коллекция зависимостей для повышения производительности [#dependency-collection-for-performance] SWR запускает повторный рендеринг только тогда, когда состояния, используемые в компоненте, были обновлены. Если вы используете только `data` в компоненте, SWR игнорирует обновления других свойств, таких как `isValidating` и `isLoading`. Это значительно снижает количество рендеринга. Дополнительную информацию можно найти [здесь](/docs/advanced/performance#dependency-collection). + +## onSuccess Callback [#on-success-callback] + +Sometimes you may want to run some side effects right after the data is fetched successfully. You can use the `onSuccess` callback option to do that. + +```jsx +const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data, key, config) => { + // Track successful API calls + analytics.track('API Success', { + endpoint: key, + timestamp: new Date(), + data: data + }); + } +}); +``` + +SWR will call the `onSuccess` callback with the fetched data, the key, and the config object. This is useful for analytics, logging, or any other side effects you want to perform after a successful fetch. + +### `onSuccess` with deduplication + +One of the features of SWR is deduplication, which means that if the same key is being used in multiple places at the same time, SWR will only fetch the data once and share it among those components. + +Only the first `onSuccess` callback defined will be called for the first successful fetch, even if `onSuccess` is defined in multiple places. + +Example: + +```jsx +const FirstComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will be called + console.log('First component success:', data); + } + }); + return
{data?.name}
; +}; + +const SecondComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will NOT be called + console.log('Second component success:', data); + } + }); + return
{data?.email}
; +}; + +const App = () => ( + <> + + + +); +``` + +The example above will only log the success message from the first component when the data is fetched successfully, even though both components have their own `onSuccess` callbacks. This is because SWR deduplicates requests for the same key. + +For this reason, you should avoid using `onSuccess` to set local state in the `onSuccess` callback, as it may lead to unexpected behavior when multiple components are using the same key. + +Also, the `onSuccess` callback is not called when the data is loaded from the cache, only when it is fetched from the network. If you need to run side effects for cached data, consider using the `useEffect` hook in combination with SWR's data. + +```jsx +const { data } = useSWR('/api/user', fetcher); + +useEffect(() => { + if (data) { + // Run side effects for cached data + console.log('Cached data:', data); + } +}, [data]); +``` diff --git a/pages/docs/advanced/understanding.zh-CN.mdx b/pages/docs/advanced/understanding.zh-CN.mdx index 641f7ef0..8fb88b5d 100644 --- a/pages/docs/advanced/understanding.zh-CN.mdx +++ b/pages/docs/advanced/understanding.zh-CN.mdx @@ -82,7 +82,6 @@ function Stock() { 点击 [这里](https://codesandbox.io/s/swr-isloading-jtopow) 查看完整代码示例。 - ## 返回之前的数据以获得更好的用户体验 [#return-previous-data-for-better-ux] 在用户连续操作的情况下进行数据请求时,例如输入时实时搜索,保留之前的数据可以极大提升用户体验,`keepPreviousData` 选项可以用于启用该行为。下例是一个简单的用户搜索界面: @@ -125,3 +124,76 @@ function Search() { ## 性能依赖关系收集 [#dependency-collection-for-performance] SWR 只会在组件中所使用的状态被更新时,触发重新渲染。如果只在组件中使用 `data`,SWR 将忽略其他属性(如 `isValidating` 和 `isLoading`)的更新。这大大减少了渲染次数。点击 [这里](/docs/advanced/performance#dependency-collection) 查看更多信息。 + +## onSuccess Callback [#on-success-callback] + +Sometimes you may want to run some side effects right after the data is fetched successfully. You can use the `onSuccess` callback option to do that. + +```jsx +const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data, key, config) => { + // Track successful API calls + analytics.track('API Success', { + endpoint: key, + timestamp: new Date(), + data: data + }); + } +}); +``` + +SWR will call the `onSuccess` callback with the fetched data, the key, and the config object. This is useful for analytics, logging, or any other side effects you want to perform after a successful fetch. + +### `onSuccess` with deduplication + +One of the features of SWR is deduplication, which means that if the same key is being used in multiple places at the same time, SWR will only fetch the data once and share it among those components. + +Only the first `onSuccess` callback defined will be called for the first successful fetch, even if `onSuccess` is defined in multiple places. + +Example: + +```jsx +const FirstComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will be called + console.log('First component success:', data); + } + }); + return
{data?.name}
; +}; + +const SecondComponent = () => { + const { data } = useSWR('/api/user', fetcher, { + onSuccess: (data) => { + // this on success will NOT be called + console.log('Second component success:', data); + } + }); + return
{data?.email}
; +}; + +const App = () => ( + <> + + + +); +``` + +The example above will only log the success message from the first component when the data is fetched successfully, even though both components have their own `onSuccess` callbacks. This is because SWR deduplicates requests for the same key. + +For this reason, you should avoid using `onSuccess` to set local state in the `onSuccess` callback, as it may lead to unexpected behavior when multiple components are using the same key. + +Also, the `onSuccess` callback is not called when the data is loaded from the cache, only when it is fetched from the network. If you need to run side effects for cached data, consider using the `useEffect` hook in combination with SWR's data. + +```jsx +const { data } = useSWR('/api/user', fetcher); + +useEffect(() => { + if (data) { + // Run side effects for cached data + console.log('Cached data:', data); + } +}, [data]); +```