Skip to content

SWR state has undocumented and unexpected values on key change #4112

@TmanTman

Description

@TmanTman

Bug report

Description / Observed Behavior

Consider the following values during a key change:

const { data, isLoading } = useSWRImmutable(someKey)

If "someKey" changes, the "data" variable can go undefined before "isLoading" goes to true. This is the state progression:

someKey data isLoading Notes
'a' defined false
'b' undefined false unexpected
'b' undefined true
'b' defined false

This behaviour is not expected, and not documented on SWR under "key change + previous data" docs

A use cases that breaks here is, for example, if a useEffect looks at these variables and if someKey leads to undefined results, makes update to state

Expected Behavior

The following state progression:

someKey data isLoading
'a' defined false
'b' undefined true
'b' defined false

Repro Steps / Code Example

Here is a link to a StackBlitz. The console shows this state.

Additional Context

SWR version: Previous versions + Latest

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions