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

Mutate by callback will cause IME composition bug #667

Closed
kazukinagata opened this issue Sep 28, 2020 · 3 comments
Closed

Mutate by callback will cause IME composition bug #667

kazukinagata opened this issue Sep 28, 2020 · 3 comments

Comments

@kazukinagata
Copy link

kazukinagata commented Sep 28, 2020

Bug report

Description / Observed Behavior

I'm using mutate() with passing synchronous callback like below.
Inputing English is fine, but if I input Japanese IME, e.target.value get a bunch of duplicate characters.

function MyApp() {
  {data, mutate} = useSWR<{title: string}>('key', fetcher)
  
  const handleChange(e) => {
    e.persist()
    mutate((prev => ({...prev, title: e.target.value})), false)
  }

  return <input value={data.title} onChange={handleChange} />
}

Expected Behavior

When I input 'n' first, then 'a', the title will expected to be 'な' (Japanese).
However actual result is unstable, it may be like 'なな', 'nな', 'な' etc.

Additional Context

SWR version. @0.3.5

This bug may related to facebook/react#3926, caused by asynchronous onChange handler with IME input.

When I dig the source code, it seems that even if I pass a synchronous callback, that function is executed internally with await. https://github.com/vercel/swr/blob/master/src/use-swr.ts#L143

If I patch like below, I get a result as expected. However according to the #619, this seems to cause another bug.

data = _data(cache.get(key))
if (typeof data.then === 'function') {
  data = await data
}
@sergiodxa
Copy link
Contributor

I recommend you to use keep a local copy of the state for the input in your component and use mutate when you want to actually save it. Remember SWR could revalidate your key in different scenarios, using it directly as the value of your input could cause an unexpected rollback if SWR revalidate the data.

@kazukinagata
Copy link
Author

@sergiodxa Thank you for your comment. I read some blog posts like this https://paco.sh/blog/shared-hook-state-with-swr that shows how to share state using useSWR instead of useState.

I was happy that useSWR is an totally alternative to useState or redux, but isn't it recommended to use useSWR as an alternative to them?

@kazukinagata
Copy link
Author

@sergiodxa As a result of research, I'm gonna try to managing local state by formik. Thank you!

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

No branches or pull requests

2 participants