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

onError callback not reflecting component state changes #508

Closed
diogofscmariano opened this issue Jul 8, 2020 · 1 comment · Fixed by #521
Closed

onError callback not reflecting component state changes #508

diogofscmariano opened this issue Jul 8, 2020 · 1 comment · Fixed by #521

Comments

@diogofscmariano
Copy link

diogofscmariano commented Jul 8, 2020

Bug report

onError callback not reflecting component state changes

Description / Observed Behavior

In a component using useState and useSwr, the state is not correctly propagated to the onError callback

Expected Behavior

The useState should be correctly accessible (read/write) inside the useSwr callbacks

Repro Steps / Code Example

const [onRefresh, setOnRefresh] = useState(false)
const [snackbarOpen, setSnackbarOpen] = useState(false)
const [errorOpen, setErrorOpen] = useState(false)

console.log(onRefresh, snackbarOpen, errorOpen)

const onSuccessCallback = useCallback(() => {
  setOnRefresh(true)
}, [])
const onErrorCallback = useCallback(() => {
  console.log(onRefresh)
  onRefresh ? setSnackbarOpen(true) : setErrorOpen(true)
}, [onRefresh])

const { data: availableSolutions, error } = useSWR<Solution[]>(
  "api/solutions", getAvailableSolutions, {
    refreshInterval: 2000,
    onSuccess: onSuccessCallback,
    onError: onErrorCallback,
  }
)

The objective here is to conditionally show a different component if the error is in the first call or in the refresh mechanism, but in this case, the onRefresh is always false (initial state value) and does not get updated.
In the example i'm running, the first console.log shows the onRefresh as true, but inside the callbacks its value is always false.

@Lam9090
Copy link
Contributor

Lam9090 commented Jul 9, 2020

Yeah, the callback called by the useSWR always the callback created in the initial render of your component,it's the problem of the stale closure.

image

You can use useRef as a workaround

const onRefresh = useRef(false);
const onSuccessCallback = useCallback(() => {
  onRefresh.current = true
}, [])
const onErrorCallback = useCallback(() => {
   onRefresh.current ? setSnackbarOpen(true) : setErrorOpen(true)
}, [onRefresh])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants