Skip to content

Commit 9745279

Browse files
committed
feat: allow to use 'cache-and-network' fetch policy with suspense
Closes #13
1 parent 3f82ecc commit 9745279

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/index.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,19 @@ export function useQuery(
3333
const previousApolloContextOptions = useRef();
3434
const previousRestOptions = useRef();
3535
const observableQuery = useRef();
36+
const shouldRefetch = useRef();
3637

3738
useEffect(
3839
() => {
3940
const subscription = observableQuery.current.subscribe(nextResult => {
4041
setResult(nextResult);
4142
});
4243

44+
if (shouldRefetch.current) {
45+
shouldRefetch.current = false;
46+
observableQuery.current.refetch();
47+
}
48+
4349
return () => {
4450
subscription.unsubscribe();
4551
};
@@ -70,19 +76,33 @@ export function useQuery(
7076
previousVariables.current = variables;
7177
previousApolloContextOptions.current = apolloContextOptions;
7278
previousRestOptions.current = restOptions;
79+
shouldRefetch.current = false;
80+
81+
const { fetchPolicy } = restOptions;
82+
// We can't use `cache-and-network` fetch policy directly because it causes
83+
// an infinite loop so we emulate it by using the default `cache-first`
84+
// policy and then optionally forcing a refetch. Please look at
85+
// https://github.com/trojanowski/react-apollo-hooks/issues/13 for details.
86+
const emulateCacheAndNetworkPolicy =
87+
suspend && fetchPolicy === 'cache-and-network';
88+
7389
const watchedQuery = client.watchQuery({
7490
query,
7591
variables,
7692
...restOptions,
93+
fetchPolicy: emulateCacheAndNetworkPolicy ? 'cache-first' : fetchPolicy,
7794
});
7895
observableQuery.current = watchedQuery;
7996
const currentResult = watchedQuery.currentResult();
8097
if (currentResult.partial && suspend) {
8198
// throw a promise - use the react suspense to wait until the data is
8299
// available
83100
throw watchedQuery.result();
101+
} else if (emulateCacheAndNetworkPolicy) {
102+
shouldRefetch.current = true;
84103
}
85104
setResult(currentResult);
105+
86106
return { ...helpers, ...currentResult };
87107
}
88108

@@ -99,7 +119,11 @@ function ensureSupportedFetchPolicy(fetchPolicy, suspend) {
99119
if (!suspend) {
100120
return;
101121
}
102-
if (fetchPolicy && fetchPolicy !== 'cache-first') {
122+
if (
123+
fetchPolicy &&
124+
fetchPolicy !== 'cache-first' &&
125+
fetchPolicy !== 'cache-and-network'
126+
) {
103127
throw new Error(
104128
`Fetch policy ${fetchPolicy} is not supported without 'suspend: false'`
105129
);

0 commit comments

Comments
 (0)