swr: Race condition where `data` or `error` return `1` when key is `null`

Bug report

Description / Observed Behavior

On very rare occasions, if I return null in the key function of useSWR, my data and / or error field return 1.

At first I thought it might be due to me calling mutate incorrectly somewhere. But it’s happening for different calls (get user, get artists), so I no longer think that’s the acse.

Plus, if the key returns null, shouldn’t the data and error always be undefined?

I did manage to wrap these calls and logged that error was 1 while key was null. But refreshing the page got rid of that bug.

Expected Behavior

Don’t return 1 for data or error if the key returns null.

Repro Steps / Code Example

I don’t have a reproduction currently, I’m still working on that. I’m still trying to reproduce this in my own app.

So as it stands, I know that this issue might not be actionable. Hopefully this isn’t a bug on the SWR side and I’ll find it. However, I find it puzzling that SWR itself is returning these values.

Can any of the maintainers think of a potential reason this could be happening? Maybe an incorrect falsy check, or something like that, which results in SWR returning 1?

Additional Context

SWR version: 0.5.6

This started happening after I upgraded from 0.3.2 to 0.5.6, so I’m going to see if downgrading again solves it.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 4
  • Comments: 23 (8 by maintainers)

Most upvoted comments

Thanks @nandorojo! I updated the sandbox a bit to make it work: https://codesandbox.io/s/angry-snowflake-r6pj5?file=/pages/index.js. I think we have to mutate to force trigger revalidating for existing hooks.

Plus, if I accidentally auto-import the global mutate from SWR instead of my own custom one, it could be hard to catch.

That’s a very good point, we definitely want to find a way to avoid that.

normally users shouldn’t care about key serialization at all

I agree; I don’t have any desire to do my own serialization. But it would be nice to mutate all keys where last(keyArray) === 'user', for instance.

SWR will serialize all the non-string keys internally before passing them to the custom cache provider. We are thinking about exposing that serialization util as APIs as well in #1337, but normally users shouldn’t care about key serialization at all.