Skip to content

onError callback not reflecting component state changes #508

@diogofscmariano

Description

@diogofscmariano

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions