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: Ensuring that useQuery's isFetching becomes true after query changes #331

Merged
merged 4 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quick-cows-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@powersync/react': patch
---

Ensuring that `useQuery`'s `isFetching` becomes true immediately after the query changes.
19 changes: 16 additions & 3 deletions packages/react/src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,20 +66,33 @@ export const useQuery = <T = any>(
const memoizedOptions = React.useMemo(() => options, [JSON.stringify(options)]);
const abortController = React.useRef(new AbortController());

const previousQueryRef = React.useRef({ sqlStatement, memoizedParams });

// Indicates that the query will be re-fetched due to a change in the query.
// Used when `isFetching` hasn't been set to true yet due to React execution.
const shouldFetch = React.useMemo(
() =>
previousQueryRef.current.sqlStatement !== sqlStatement ||
JSON.stringify(previousQueryRef.current.memoizedParams) != JSON.stringify(memoizedParams),
[powerSync, sqlStatement, memoizedParams, isFetching]
);

const handleResult = (result: T[]) => {
setData(result);
setIsLoading(false);
setIsFetching(false);
setData(result);
setError(undefined);
previousQueryRef.current = { sqlStatement, memoizedParams };
};

const handleError = (e: Error) => {
setData([]);
setIsLoading(false);
setIsFetching(false);
setData([]);
const wrappedError = new Error('PowerSync failed to fetch data: ' + e.message);
wrappedError.cause = e;
setError(wrappedError);
previousQueryRef.current = { sqlStatement, memoizedParams };
};

const fetchData = async () => {
Expand Down Expand Up @@ -139,5 +152,5 @@ export const useQuery = <T = any>(
};
}, [powerSync, sqlStatement, memoizedParams, memoizedOptions, tables]);

return { isLoading, isFetching, data, error, refresh: fetchData };
Chriztiaan marked this conversation as resolved.
Show resolved Hide resolved
return { isLoading, isFetching: isFetching || shouldFetch, data, error, refresh: fetchData };
};
Loading
Loading