Skip to content

Commit de3eec0

Browse files
committed
fix: fix query invalidation issue
Fixes an edge case where queries are not invalidated, when Ghosts changed "under the hood".
1 parent 17d867c commit de3eec0

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

packages/react-ghostmaker/src/makeGhost.test.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@ import {
1414
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
1515
import { invalidateGhosts } from "./invalidate";
1616
import { makeGhost } from "./makeGhost";
17+
import { cleanupTargetHashes } from "./useGhostChain";
1718

1819
beforeEach(() => {
1920
vitest.useFakeTimers();
21+
cleanupTargetHashes();
2022
});
2123

2224
afterEach(() => {

packages/react-ghostmaker/src/useGhostChain.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import is, { assert } from "@sindresorhus/is";
2-
import { useEffect, useEffectEvent, useMemo, useRef } from "react";
2+
import { useEffect, useEffectEvent, useMemo } from "react";
33
import {
44
transformFnProp,
55
type GhostChain,
@@ -100,6 +100,8 @@ const useGhostChainItem = <T>(
100100
return query.data.result;
101101
};
102102

103+
const targetHashes = new Map<string, number>();
104+
103105
const useTargetAutoInvalidate = (target: object, queryKey: QueryKey) => {
104106
const queryClient = useQueryClient();
105107

@@ -109,15 +111,13 @@ const useTargetAutoInvalidate = (target: object, queryKey: QueryKey) => {
109111
});
110112

111113
const targetHash = hashObject(target);
112-
const prevTargetHash = useRef(targetHash);
113114
const joinedQueryKey = queryKey.join(".");
114-
const prevQueryId = useRef(joinedQueryKey);
115+
const prevTargetHash = targetHashes.get(joinedQueryKey);
115116

116117
const needsRefresh =
117-
prevQueryId.current === joinedQueryKey &&
118-
prevTargetHash.current !== targetHash;
119-
prevTargetHash.current = targetHash;
120-
prevQueryId.current = joinedQueryKey;
118+
prevTargetHash !== undefined && prevTargetHash !== targetHash;
119+
120+
targetHashes.set(joinedQueryKey, targetHash);
121121

122122
const onTargetChangeEvent = useEffectEvent(() => {
123123
if (needsRefresh) {
@@ -129,3 +129,8 @@ const useTargetAutoInvalidate = (target: object, queryKey: QueryKey) => {
129129
onTargetChangeEvent();
130130
}, [needsRefresh]);
131131
};
132+
133+
/** @internal */
134+
export const cleanupTargetHashes = () => {
135+
targetHashes.clear();
136+
};

0 commit comments

Comments
 (0)