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

Mutating state via onChange causes cursor jump to end of input #994

Closed
danielstocks opened this issue Feb 22, 2021 · 1 comment · Fixed by #1003
Closed

Mutating state via onChange causes cursor jump to end of input #994

danielstocks opened this issue Feb 22, 2021 · 1 comment · Fixed by #1003

Comments

@danielstocks
Copy link

danielstocks commented Feb 22, 2021

Bug report

Description / Observed Behavior

I'm attempting to use the following code as suggested by @sergiodxa to mutate state while typing in a text input.

The mouse cursor does not maintain its position within the text input field (if placed anywhere except at the end) while mutating the state.

Controlling an input only with React.useState works as intended.

Expected Behavior

Cursor should maintain it's current position within the text input.

Repro Steps / Code Example

import useSWR from "swr";

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function App() {
  const { data, mutate } = useSWR(
    "https://jsonplaceholder.typicode.com/todos/1",
    fetcher,
  );

  function handleChange(event) {
    mutate(
      {
        ...data,
        title: event.currentTarget.value
      },
      false
    );
  }

  if (!data) return <div>loading</div>;

  return (
    <div>
      <input value={data.title} onChange={handleChange} />
    </div>
  );
}

https://codesandbox.io/s/upbeat-thompson-qqeof?file=/src/App.js

Additional Context

SWR version: 0.4.2

This bug seems to have been introduced in version 0.3.9. I'm suspecting (without any scientific proof 🧑‍🔬) that it was introduced either by #777 or #735.

In version 0.3.8 and older it works as expected.

@koba04
Copy link
Collaborator

koba04 commented Feb 25, 2021

I've confirmed the behavior and it happens when we update a text value in onChange asynchronously.
It happens with useState, and the following is a minimum reproduction.
https://codesandbox.io/s/distracted-elion-htxt9?file=/src/App.js

As @danielstocks pointed out, this seems to be caused by #735 because it uses await 0 to dedupe synchronous mutation calls.
If SWR supports the case to call the mutate function synchronously in an input handler, we might have to re-consider the approach #735 introduces.

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