Skip to content

Commit

Permalink
(react) - Update initial state to not require abort on mount (#2227)
Browse files Browse the repository at this point in the history
* (react) - Update initial state to not require abort on mount

Previously, the `useSyncExternalStore` reimplementation regressed
on us constructing the correct initial state on mount, and instead
relied on an abort on mount, which is confusing to users.
Instead, we can simply revert to what we've done prior to the
change and ensure that the initial state is accurate.

* Add changeset with clarification
  • Loading branch information
kitten authored Jan 31, 2022
1 parent 481bf43 commit b79986a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/funny-pugs-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'urql': patch
---

Update `useQuery` implementation to avoid an aborted render on initial mount. We abort a render-on-update once when the state needs to be updated according to the `OperationResult` source we need to listen to and execute. However, we can avoid this on the initial mount as we've done in a prior version. This fix **does not** change any of the current behaviour, but simply avoids the confusing state transition on mount.
43 changes: 24 additions & 19 deletions packages/react-urql/src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,30 @@ export function useQuery<Data = any, Variables = object>(
const request = useRequest<Data, Variables>(args.query, args.variables);
const cache = getCacheForClient(client);

const currDeps: unknown[] = [
client,
request,
args.pause,
args.requestPolicy,
args.context,
];

const [meta, setMeta] = useState<{
source: Source<OperationResult<Data, Variables>> | null;
prevValue: UseQueryState<Data, Variables>;
deps: Array<any>;
deps: unknown[];
suspense: boolean;
}>({
source: null,
}>(() => ({
source: args.pause
? null
: client.executeQuery(request, {
requestPolicy: args.requestPolicy,
...args.context,
}),
prevValue: notFetching,
deps: [],
deps: currDeps,
suspense: isSuspense(client, args.context),
});
}));

const { source, deps, suspense } = meta;

Expand Down Expand Up @@ -167,23 +180,15 @@ export function useQuery<Data = any, Variables = object>(
)
));

const currDeps = [
client,
request,
args.pause,
args.requestPolicy,
args.context,
];

if (hasDepsChanged(deps, currDeps) && !args.pause) {
const fetchSource = client.executeQuery(request, {
requestPolicy: args.requestPolicy,
...args.context,
});

setMeta({
prevValue: result,
source: args.pause ? null : fetchSource,
source: args.pause
? null
: client.executeQuery(request, {
requestPolicy: args.requestPolicy,
...args.context,
}),
deps: currDeps,
suspense: isSuspense(client, args.context),
});
Expand Down

0 comments on commit b79986a

Please sign in to comment.