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

onSuccess is only triggered once? #2640

Closed
joshkel opened this issue May 25, 2023 · 2 comments
Closed

onSuccess is only triggered once? #2640

joshkel opened this issue May 25, 2023 · 2 comments
Labels
wontfix This will not be worked on

Comments

@joshkel
Copy link
Contributor

joshkel commented May 25, 2023

Bug report

Description / Observed Behavior

Our application uses onSuccess to trigger certain desired behavior. However, in testing, it appears that onSuccess is only triggered if that specific useSWR call is responsible for the success - if the data was already loaded from another useSWR call, it's not triggered.

Expected Behavior

onSuccess is triggered whenever data is successfully available, whether that successful request came from this instance or another.

Repro Steps / Code Example

https://codesandbox.io/s/swr-on-success-uuigol?file=/src/App.tsx

Additional Context

SWR version: 2.1.1

@promer94 promer94 added the wontfix This will not be worked on label Jun 7, 2023
@promer94
Copy link
Collaborator

promer94 commented Jun 7, 2023

Thanks for reporting and reproduction !

This is currently a expected behavior since SWR will deduplicate the requests so only one request will be executed and trigger the onSuccess callback once. #1580

You could use useEffect as alternative.

const { data } = useSWR('api', fetcher)
React.useEffect(() => {
    if (data)
      //do something
    }
}, [data])

@promer94 promer94 closed this as completed Jun 7, 2023
@Marcosld
Copy link

Thanks for reporting and reproduction !

This is currently a expected behavior since SWR will deduplicate the requests so only one request will be executed and trigger the onSuccess callback once. #1580

You could use useEffect as alternative.

const { data } = useSWR('api', fetcher)
React.useEffect(() => {
    if (data)
      //do something
    }
}, [data])

Is it guaranteed that the data object reference will be the same between renders so that hook doesn't get executed until there's a new request (for example when using immutable swr hooks)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
wontfix This will not be worked on
Projects
None yet
Development

No branches or pull requests

3 participants