@@ -33,13 +33,19 @@ export function useQuery(
33
33
const previousApolloContextOptions = useRef ( ) ;
34
34
const previousRestOptions = useRef ( ) ;
35
35
const observableQuery = useRef ( ) ;
36
+ const shouldRefetch = useRef ( ) ;
36
37
37
38
useEffect (
38
39
( ) => {
39
40
const subscription = observableQuery . current . subscribe ( nextResult => {
40
41
setResult ( nextResult ) ;
41
42
} ) ;
42
43
44
+ if ( shouldRefetch . current ) {
45
+ shouldRefetch . current = false ;
46
+ observableQuery . current . refetch ( ) ;
47
+ }
48
+
43
49
return ( ) => {
44
50
subscription . unsubscribe ( ) ;
45
51
} ;
@@ -70,19 +76,33 @@ export function useQuery(
70
76
previousVariables . current = variables ;
71
77
previousApolloContextOptions . current = apolloContextOptions ;
72
78
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
+
73
89
const watchedQuery = client . watchQuery ( {
74
90
query,
75
91
variables,
76
92
...restOptions ,
93
+ fetchPolicy : emulateCacheAndNetworkPolicy ? 'cache-first' : fetchPolicy ,
77
94
} ) ;
78
95
observableQuery . current = watchedQuery ;
79
96
const currentResult = watchedQuery . currentResult ( ) ;
80
97
if ( currentResult . partial && suspend ) {
81
98
// throw a promise - use the react suspense to wait until the data is
82
99
// available
83
100
throw watchedQuery . result ( ) ;
101
+ } else if ( emulateCacheAndNetworkPolicy ) {
102
+ shouldRefetch . current = true ;
84
103
}
85
104
setResult ( currentResult ) ;
105
+
86
106
return { ...helpers , ...currentResult } ;
87
107
}
88
108
@@ -99,7 +119,11 @@ function ensureSupportedFetchPolicy(fetchPolicy, suspend) {
99
119
if ( ! suspend ) {
100
120
return ;
101
121
}
102
- if ( fetchPolicy && fetchPolicy !== 'cache-first' ) {
122
+ if (
123
+ fetchPolicy &&
124
+ fetchPolicy !== 'cache-first' &&
125
+ fetchPolicy !== 'cache-and-network'
126
+ ) {
103
127
throw new Error (
104
128
`Fetch policy ${ fetchPolicy } is not supported without 'suspend: false'`
105
129
) ;
0 commit comments