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

Fix useQuery race condition for initial query. #525

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Chriztiaan
Copy link
Contributor

@Chriztiaan Chriztiaan commented Mar 10, 2025

Using the following snippet (originally reported here) that applies a filter in a useEffect to a query to make the result set smaller:

function GetUsers() {
  const [userFilter, setUserFilter] = useState<string>()
  let query = db.selectFrom("User").selectAll()

  if (userFilter) {
    query = query.where("id", "=", userFilter)
  }

  const { data } = useQuery(query)
  console.log("GetUsers result", userFilter, data.length)

  useEffect(() => {
    setUserFilter("500")
  }, [])

  return <Text>Data length: {data.length}</Text>
}

The first query that was fired without the filter from the if finishes last meaning query order and result order ends up not being the same. Giving the following output:

GetUsers result 500 0
GetUsers result 500 0
GetUsers result 500 1
GetUsers result 500 10000 <-- XXX

Where the user would expect 1 since it would be the result for the last query fired.

This code change aborts the initial query if a new one was fired, so we now get the following output:

GetUsers result 500 0
GetUsers result 500 0
GetUsers result 500 1

Changeset has been tested on the reported issue.

Copy link

changeset-bot bot commented Mar 10, 2025

🦋 Changeset detected

Latest commit: dfaec13

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@powersync/react Patch
@powersync/react-native Patch
@powersync/tanstack-react-query Patch
@powersync/diagnostics-app Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@Chriztiaan Chriztiaan marked this pull request as ready for review March 11, 2025 06:22
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 this pull request may close these issues.

1 participant