Not sure if this is an issue with react-apollo or apollo-client.
1) Create graphql() component with fetchPolicy: 'network-only'
2) Render the component once - data is fetched from server
3) Print out this.props.data
4) Update the underlying query data
5) Render the component again - this.props.data is stale
When using fetchPolicy: 'network-only', Component receives the previously cached value.
When using fetchPolicy: 'network-only' should only return fresh results from server.
Thanks @davidye, this sounds like a bug. Could you provide a reproduction with https://github.com/apollographql/react-apollo-error-template? That would help us figure out what's going on.
I am also seeing the same issue, fetchPolicy: 'network-only', Component receives the previously cached value. versions [email protected] [email protected]. I will try to reproduce it.
Thanks @irfanlone that would be great! Let me know if you need any help with it 馃檪
@helfer, Here is the PR reproducing the issue, https://github.com/apollographql/react-apollo-error-template/pull/2. Let me know if it makes sense. Thanks for looking into it. 馃檪
Thanks @irfanlone. Based on your reproduction it looks like this runs two separate queries. What I'm not sure yet is how the code path is different from the one taken in this test here: https://github.com/apollographql/apollo-client/blob/master/test/client.ts#L1282
@irfanlone this is embarrassing, but I figured out what's wrong: The error was actually in our docs, which did not specify the right way to pass the option. In react-apollo you have to pass those options that apply to Apollo Client wrapped inside the options param:
export default graphql(
gql`{
food {
id
name
}
}`,
{
options: { fetchPolicy: 'network-only' },
}
)(Food)
I've fixed it in the docs with this commit: https://github.com/apollographql/react-docs/commit/dd23b58303b6c8415d307b1c48e5ffbec2d45cfc
@davidye I think you most likely had the same problem, so I'll close the issue here. If this doesn't fix your issue, please re-open it.
@helfer, I am sorry I actually didn't give you the right reproduction, I was already including fetchPolicy wrapped under options in my code. Right now I can't reproduce the bug on react-apollo-error-template repo but will update if i can reproduce it. Thanks.
We're facing similar problem. Second render of component is rendering from cache.
graphql(query, {
options: ({id, progress}) => ({
variables: {id, progress},
fetchPolicy: 'network-only'
})
})(MyComponent)
@helfer I'll try to create repo with reproduction of this bug. Could you meanwhile reopen this issue?
I just made some changes to apollo error template to reproduce this bug.
I'm expecting, that last member of list will change on 'refresh' button click, but it's not. Loading data from cache (even fetchPolicy: 'network-only') :/
When I'm adding pollInterval: 1000, then everything is as expected, every second time last person in the list is changing.
After looking one more time on my example I feel, that the problem is that apollo is doing queries only when graphql() created component is mounting not every time when it's parent tries to render the Component. Any ideas how to solve this?
@helfer @stubailo
@chompomonim this may be something that has to be changed in react-apollo. It's possible that react-apollo actually looked at the old forceFetch option, but doesn't look at the fetchPolicy.
Same behavior here,
I can see 2 'APOLLO_QUERY_INIT' actions in reduxDevTools
First one with fetchPolicy = 'network-only'
Then an other one with the same id (so it overwrites the first one) with fetchPolicy = 'cache-first'
may comes from here :
https://github.com/apollographql/apollo-client/blob/master/src/core/QueryManager.ts#L431
@Aetherall do you know how to fix this?
I have the same issue: apollo is doing queries only when graphql() created component!
Please check if options is passed as functions. I was facing issue with
"options": {"fetchPolicy": "network-only"}.
When i changed it to following it works fine.
"options": () => ({"fetchPolicy": "network-only"})
@davidsims9t My workaround was to use "cache-and-network",
and to treat the data only when ( props.data.loading === false )
I would try @jinxac 's solution first
This issue has been automatically labled because it has not had recent activity. If you have not received a response from anyone, please mention the repository maintainer (most likely @jbaxleyiii). It will be closed if no further activity occurs. Thank you for your contributions to React Apollo!
I was facing the same issue, here, but realised that I had a recompose branch on the HOC and failed to set the policy for both branches, just in case someone else happens to miss the obvious like I did... Haha.
Im facing the same error. And neither @jinxac nor @Aetherall 麓s solution worked for me
Same thing here. The second time I query something (with different variables), the content cached from the first query is returned, while the query is sent. For that specific use case, with a network-only, I'm not expecting to receive the cached version of a same query with different variables.
Also seeing this, no work-arounds seem to help.
I am having this same issue as well. I tried @jinxac and @Aetherall's solutions and they didn't work for me. [email protected] [email protected]
I'm encountering this problem as well. I am trying to use network-only on the server side to ensure pages are always fresh with the latest data, but instead I'm getting stale responses. Only the first response after a server restart includes fresh data.
I tried using @jinxac's suggested workaround, but that didn't work for me either.
It looks like the react-apollo package is explicitly changing "network-only" fetchPolicy values to "cache-first". See here. Why?
Having the same issue with [email protected].
The issue is quite annoying as Im using a withApollo to check if a user is already in the database or not.
console.log('checking if new')
const isNew = await this.props.client.query({
query: IsNewClient,
variables: {
nationalNumber: this.props.eid.eid.nationalNumber,
},
options: {
fetchPolicy: 'network-only'
}
});
Both console logs are written but no request appears in the network tab of chrome dev tools.
I'm having the same issue using [email protected]. I'm a little bit behind so I'm going to try to update to latest version and see what happens.
@tleunen just for the record, I was having the same issue you have and based on my experience your problem could be different. Since you are using "the same query" but with different parameters, that drives to apollo to think you are working with 2 (or more) different queries.
Lets say you create a component and attach to it a query like this:
query MyTodo($first:Int) {
allTodos(first:2) {
nodes {
id
title
}
}
}
And then, when you run the app and under a given logic/state changes/you name it, you run this other query:
query MyTodo($first:Int) {
allTodos(first:5) {
nodes {
id
title
}
}
}
Apollo handles both queries as different queries so, it fires the request to the server but when the data comes back, it say something like "ok, this data is not attached to any query handled on the store (because at the very beginning the component was attached to "other" query), I don't need to notify any component" and that's why your request is sent but your component is not updated.
At least that was my case, I hope it helps you.
EDIT:
After updating the reference to [email protected] it works now on my side. I see a request to the server every time I need as desired.
Having the same issue also. Apollo client returns the cached data even when fetchPolicy is set to network-only in the request.
Still not working
Same issue here.
Same here but I am using vue-apollo
Same issue here.
I did some digging and found out that the fetchPolicy overwrite comes from this commit. @jbaxleyiii do you know why this was originally committed? What is the bug that this fix addresses?
I'm having the same issue.
"apollo": "^0.2.2",
"apollo-client": "^1.9.3",
I'm also hitting this problem! After looking into the source code it looks like if you pass an extra ssr: false option, things work:
{
fetchPolicy: "network-only",
ssr: false, //temporary fix to make the "network-only" option actually work
}
Hope this alleviates some pain for people until a real solution is arrived at.
The issue appears to stem from these lines:
https://github.com/apollographql/react-apollo/blob/1b28d92cf1a09fe28c40cbad91b31a0208313663/src/graphql.tsx#L416-L421
@helfer is there any reason that is not just a
if (!opts.ssr) return false;
?
Seems like that would fix this issue. Not sure if something else would break.
Cheers!
Same issue here
same issue :(
ssr hack did not help
react-apollo: 2.0.1
apollo-client: 2.0.3
apollo-cache: 1.0.1
apollo-cache-inmemory: 1.1.1
my use case: after a mutation an item should be removed from a list
I even tried to manually remove it in the update callback still the item appears
fetchPolicy: network-only
if I navigate away then navigate back the list is correct
same issue
ssr option did not help
+1 same here
This works for me when using withApollo (note that fetchPolicy should not be placed within an options object):
const res = await this.props.client.query({
query: LOGGED_IN_USER,
fetchPolicy: 'network-only'
});
Passing in a unique id for the variables on each update to your request will ensure it does not use the cache.
Any update on this guys ?
What is not clear for me is the reason the "cache-skipping" is being prevented in SSR. Can anyone explain that? For it would be very useful to justify any workaround.
still not working, it's been dragging on for at least 10 months now, do you even care anymore?
Is this project dead?
Not working for me either, really needs a fix.
The ugly pattern mentioned by @fc does work fyi for anyone who is up against a deadline. Sad that we have to revert to bs like that to get accurate query results, but alas here we are.
Could this be related to a larger bug within apollo-client?
I've got multiple Meteor apps using apollo.
One uses Vuejs - fetchPolicy network-only flag works! - I refetch a query, similar pattern - ezclap.
One uses Blaze - fetchPolicy network-only flag has the same bug mentioned here - :(
Possible Similar Issues
One uses React - the fetchPolicy network-only flag returns stale data. - feelsbadman.
If you dig around the apollo-client repo enough there's possible evidence of this issue dating back to around the same time this fail thread came to be. Oddly enough the only meaningful outcome of this thread was a proposal to disable the cache altogether within apollo-client, for reasons totally unrelated to the issues people are facing here.
This issue is pretty infuriating and I bet a huge turn off for many people forming opinions about using apollo and taking it seriously. It would be nice to see some movement on here.
@citylims we were able to uncover a way to not use this hack. This may or may not apply to your situation. This is on apollo-client 1.9.x. We noticed when we removed variables, apollo-client would not see that the variable was removed and would return a cached value. But, if we set the variable that was supposed to be removed to undefined, it would work. If you are removing a variable and seeing cached results, just change it to undefined.
Actually my impression is Apollo use the combination of variables (names and values) to define the query id, and if you use one query the first time with lets say "1" as value for "parameter1" and later you call the "same" query with "2" as value for "parameter1", Apollo creates a second totally different query and does not refresh the components attached to the "first" query.
At leas that was happening to me at the very beginning and I took me a couple of hours to figure it out.
@ElNinjaGaiden did you solve your problem ?
@mario-jerkovic Is solved my problem long time ago by updating all the packages versions
I did this (es7 decorator)
@graphql(getTopTeams, {
options: {
fetchPolicy: 'network-only',
ssr: false, // Add this in an options object
},
})
@graphql(getTeamRanking, {
options: ({ teamId }) => ({
fetchPolicy: 'network-only',
ssr: false, // Add this in an options function
variables: {
id: teamId,
},
}),
})
And it works ! Thanks @tnrich !!
I'm on "react-apollo": "^2.0.4"
Still running into this issue and ssr fix helped. Feeling dirty now though :)
"react-apollo": "^2.1.2",
"apollo-client-preset": "^1.0.8",
"apollo-link": "^1.2.1",
"apollo-link-batch-http": "^1.2.1",
"apollo-link-context": "^1.0.7",
"apollo-link-state": "^0.4.1",
The ssr fix doesn't work in <Query/> component.
I'm on react-native and on the latest react apollo 2.1.x using <Query /> component and experience the same issue. I verified the bug by looking at the network tab and noticed that upon re-render of the component in question, the Query component renders but no new network requests were made. So apparently react apollo ignores the policy I set and still uses cache directly.
This is the same issue as 'no-cache' where if I set this option it will not return anything, as if the request hasn't been made at all...
I was trying with
let res = await this.props.client.query({
query: MY_QUERY,
variables: {
user: this.state.user.id
},
options: { fetchPolicy: 'network-only' }
});
What solves the problem for me was take the fetchPolicy out of the options:
let res = await this.props.client.query({
query: MY_QUERY,
variables: {
user: this.state.user.id
},
fetchPolicy: 'network-only'
});
with this, the 'network-only' worked as expected
:-)
馃憤 Happening using the <Query/> component. When the query component re-renders, it serves stale data (could be 10 calls ago, or one call ago, depending on what variables were passed in originally), until its loading = false, which then returns the correct data.
v2.1.4 experiencing this issue with the <Query/> component, but even when loading = false https://github.com/apollographql/react-apollo/issues/556#issuecomment-386749500 the data is still returned from the cache, then, after a few calls it fetches the network
Same problem with v2.1.4
If you want to kinda hack this, you can add a fake param to your graphql call (add a unique id to every call), this will essentially bust your cache because none of the calls will be the same. Only works if you own the graphql endpoint your connecting to though.
Just discovered the same issue and none of the hacks helped in our case. Seems quite critical, doesn't it?
@jbaxleyiii @helfer
Our temporary workaround (like @pmwisdom's solution): add a query (cacheBuster(uniqueID: String): Boolean!) to our schema that we pass unique IDs to. Previously the fetch profile query would hit the cache despite a network-only cache policy. Now using the cacheBuster all requests go straight to the network
query FetchProfile($profileId: String!, $uniqueId: String) {
profile(profileID: $profileId) {
// ...
}
cacheBuster(uniqueID: $uniqueId)
}
@helfer Can you give us an update on this please?
Reporting that this is still broken. My VUE (ssr) setup goes as follows
const apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
ssrMode: true,
defaultOptions: {
query: {
fetchPolicy: 'no-cache',
},
watchQuery: {
fetchPolicy: 'no-cache',
},
},
});
export function createApolloProvider () {
return new VueApollo({
defaultClient: apolloClient,
});
}
This will still return values from the cache. If I change the ssrMode to true, everything works as expected
Btw: This is what the Apollo Docs say:
Since you only want to fetch each query result once, pass the
ssrMode: trueoption to the Apollo Client constructor to avoid repeated force-fetching.
Which might explain this a little
what about adding options.ssr === false
On 2.1.4 I can confirm that as @jaimebiernaski says, going against what the docs claim fetchPolicy: "network-only" seems to only have an affect when used _outside_ the options.
I.e:
// Re-uses cache (obviously)
graphql(query)
// Also re-uses cache (wrongly)
graphql(query, {options: {fetchPolicy: "network-only"}})
// Hits network every time, DOES NOT re-use cache, (super wrongly!)
graphql(query, {fetchPolicy: "network-only"})
:( any updates on this?
Any updates! This seems pretty critical.
+1
The only workaround listed above that worked for me, on my SSR app was to pass fetchPolicy: 'cache-and-network',
However I've removed that in favour of passing a query like this
query {
cacheBuster
theRest {
}
}
and the backend returns a guid in the cacheBuster field.
It's nasty but this bug is a nearly a year and a half old now
Can we please get an update on this? We are also experiencing this issue! 馃悰
Note that for us we were not storing id in cache, not sure if that helps people but worked for us!
Same issue here! I'm one of you now.
@mhuggins you reckon you could fork this project with a fix in it? :)
@hwillson I see you linked to this issue. Is this issue being worked now or are there plans to work this?
@joshsmith Hopefully very soon. Getting this issue resolved is definitely a high priority, along with addressing many of the outstanding issues / PR's in this repo. We're just about to kick start React Apollo work relating to React Suspense, and we'll be doing a lot of repo cleanup at the same time.
In some cases, we need to use network-only. For now, I add add one variable of timestamp to force query execute every time it renders. e.g.
options: ({ userId }) => ({
fetchPolicy: !userId ? 'cache-only' : 'network-only',
variables: { timestamp: new Date().getTime().toString() }
});
I had the same issues as what is described here, and in my case it turned out to be an issue with the variables being passed always referencing the same object. I was doing a query like ...
let res = await this.props.client.query({
query: MY_QUERY,
variables: {
filters: this.state.arrayOfFilters,
},
options: { fetchPolicy: 'network-only' }
});
arrayOfFilters was being mutated in the state, but never replaced. I was only ever adding or removing from the array, but never replacing the whole thing.
Adding a slice(0) to clone the array solved this issue in my case.
i.e.
let res = await this.props.client.query({
query: MY_QUERY,
variables: {
filters: this.state.arrayOfFilters.slice(0),
},
options: { fetchPolicy: 'network-only' }
});
I am wondering if some of those with an issue are actually hitting something similar.
Found it. I'm using this bug as a workaround over cache-and-network as it's broken too 馃帀
OMG how much workarounds!!! When this expected to work properly?
We had a similar issue with network-only showing the cached data on iOS but not on Android.
It turns out the API endpoint had a value set on the cache-control attribute of the request headers which Android was ignoring but iOS wasn't, hence the stale data.
Replacing it to Cache-Control: no-cache solved the issue on both platforms.
Using:
"apollo-cache-inmemory": "1.2.5",
"apollo-cache-persist": "0.1.1",
"apollo-client": "2.4.5",
"apollo-link": "1.2.3",
"apollo-link-rest": "0.6.0",
"apollo-link-state": "0.4.1",
"react-apollo": "2.2.4",
Maybe someone had a similar issue so just leaving this info here in case it helps.
I had same problem and i figured what code is problem. I commented about it in related PR (#2003). (Oops, it's my mistake. please ignore wrong informed comment)
timestamp solution is looks reasonable. this will makes each query as unique.
I'm still experiencing this issue in my app using the Query component. This seems like a high priority issue, and it's been open since March of 2017 without any real acknowledgement or plans to fix. I've put together a hacky workaround, like many other people in this thread, but we need a real resolution.
Can anyone here share a small, runnable (and modern) reproduction that clearly demonstrates this happening? If so, I'll look into resolving it ASAP. Thanks!
@hwillson Here's a rough reproduction of the issue. If open your console and watch the values that are returned by the query, you'll see cached values being returned by a network-only Query before it eventually settles on the network value.
https://github.com/pcorey/network-only-reproduction
It's a pretty rough reproduction, so let me know if you have trouble with the repo...
Thanks!
Thanks @pcorey! I'll dig into this further.
Relating to the original post, just a reminder for those who want to always return fresh results from the network (avoiding the cache completely), you can use the no-cache fetch policy.
@hwillson - any updates on this issue? This came up as I was planning tasks for the new year.
Thanks @pcorey! I'll dig into this further.
Relating to the original post, just a reminder for those who want to always return fresh results from the network (avoiding the cache completely), you can use the
no-cachefetch policy.
Using "react-apollo": "2.0.4" and defining my query like this:
graphql(SomeQuery, {
options: {
fetchPolicy: 'no-cache',
},
props: ({ data: { loading } }) => ({
loading
}),
}),
the component that uses this query still gets stale data (from the cache). Looking at my network tab in chrome, i would expect this query to run each time the component is mounted. But it is not. When using fetchPolicy: 'network-only', it works. How's that?
Same problem here, fetchPolicy="network-only" still uses cached data..
@duwerq No it shouldn't. It should work with fetch policy "network-only" and I am working on it to get this fixed.
@jochienabuurs I can't speak for @2.0.4 but for @^2.1.8 that request should be:
graphql(SomeQuery, { options: () => ({ fetchPolicy: 'network-only', }), props: ({ data: { loading } }) => ({ loading }), }),
@danilobuerger sorry mean to say network-only. options should be a function inside the same object as props
@joe-askattest I had issues with client.query also. I solved it by chanaging:
const { data: { getUser } } = await client.query({
query: gql(queries.getUser)
}, {
options: {
fetchPolicy: 'network-only'
}
});
to
const { data: { getUser } } = await client.query({
query: gql(queries.getUser),
fetchPolicy: 'network-only'
});
When you call client.query({}), the options object in the picture below represents what's passed when the request is made. It looks for options.fetchPolicy instead of options.options.fetchPolicy

Yours would be
let res = await this.props.client.query({
query: MY_QUERY,
variables: {
filters: this.state.arrayOfFilters,
},
fetchPolicy: 'network-only'
});
@hwillson @danilobuerger Any updates on this? This is still an issue using the Query component. Is there anything I can do to help get this resolved? Better reproduction? Anything?
@pcorey There is an open PR waiting to be merged. https://github.com/apollographql/apollo-client/pull/4352 Nothing else needs to be done.
@danilobuerger :tada: I missed that. Thanks for the help!
Can we merge this plz? 馃槕
Referring to two comments before bud thanks.
This was released with 2.5, yeah? If so, I'll try it out in my projects soon. Thanks for all the help and hard work @hwillson and @danilobuerger!
fetchPolicy="network-only" still broken in the query component. (@2.5.1)
... unless im miss understanding what network-only means
are there any work arounds?
@wrod7 You could try doing something like this under defaultOptions
const client = new ApolloClient({
link: createHttpLink({
uri: `//${apiDomain}/graphql`,
fetch: customFetch,
}),
cache,
link: ApolloLink.from([
stateLink,
createHttpLink({ uri: `//${apiDomain}/graphql`, fetch: customFetch }),
]),
cache,
defaultOptions: {
watchQuery: {
fetchPolicy: 'network-only',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'network-only',
errorPolicy: 'all',
},
},
});
Disregard! I was on an old version of apollo-client. Bumping apollo-boost to 0.3.1 brought my apollo-client version to 2.5.1, and everything seems to be working:
Showing...
ShowHide.js:19 Re-rendering query:
ShowHide.js:41 data received from Query: undefined {}
ShowHide.js:41 data received from Query: undefined {}
ShowHide.js:41 data received from Query: 0.6603918391040067 {random: {鈥}
:tada:
can you share you query component? are you using 'network-only' ? @pcorey
the default options on the apollo client didnt work for me
@wrod7 The query is in the reproduction repo. Check it out.. It seems to work as I'd expect with [email protected] and [email protected].
still happening to me on 2.5.1

<Query<MeQuery, MeVariables> query={MeDocument} fetchPolicy='network-only'>
{({ data, loading, error }) => {
if (loading) return <div>loading</div>
if (error || !data || (data && !data.me)) return <Redirect to='/login' />
console.log(data)
return (
...
)
}}
</Query>
Hi guys, I hope you can help me with this, I'm not sure about this behavior and it might be related to this bug.
I try [email protected] and [email protected] in the reproduction repo and the query launches after an update as expected 馃帀
Then I add [email protected] and do some modifications to the code in the repo
ShowHide.js
export default class extends React.Component {
render() {
console.log("Re-rendering query:");
return (
<div>
<BrowserRouter>
<Route to="/" render={props => <Content {...props} />} />
<br />
<Link to="/test">Test</Link> <br />
<Link to="/dashboard">Dashboard</Link> <br />
<Link to="/home">Home</Link> <br />
<Link to="/list">List</Link> <br />
</BrowserRouter>
</div>
)
}
}
Content.js
class Content extends Component {
render() {
const { data } = this.props;
console.log(
"data received from Query:",
_.get(data, "random.value"),
data
);
return (
<div>
<h1>Open your console!</h1>
<p>
The Query component eventually settled on the above value, which comes
from the network. Click "Hide" to remove the Query component from the
virtual DOM.
</p>
<p>{_.get(data, "random.value")}</p>
{/* <p>Math.random: {Math.random()}</p> */}
<Switch>
<Route path="/test" render={() => <div>test</div>} />
<Route path="/dashboard" render={() => <div>dashboard</div>} />
<Route path="/home" render={() => <div>home</div>} />
<Route path="/list" render={() => <div>list</div>} />
</Switch>
</div>
)
}
}
export default graphql(gql`
{
random {
id
value
}
}`, {
options: {
fetchPolicy: 'network-only'
}
})(Content);
And as you can see here, the component re-renders, but the query doesn't fire again

I've managed to overcome this issue by passing a timestamp to variables
await apolloClient.query({
query: getStatesCitiesQuery,
variables: {
antiCache: +(new Date()), // timestamp HACK
state,
city,
},
});
antiCache field will force apollo to make request again and can be any name as it is ignored.
I thought that maybe my graphql server returns some Caching headers but it does not.
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Timezone, Authorization, Platform
Access-Control-Allow-Methods: DELETE, GET, HEAD, POST, PUT, OPTIONS, TRACE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 1556
Content-Type: application/json
Date: Thu, 07 Mar 2019 00:12:59 GMT
Server: nginx/1.14.1
X-Powered-By: Express
honesly I am not sure what the source of this issue is.
Update
I've managed to resolve my issue without this hack by explicitly calling refetch().
My issue was that I was doing setState() when I wanted to refetch but the state was resulting with the same variables so apollo did not do query. With explicit call of refetch() apollo does indeed make another request from the server.
@mieszko4 where are you calling refetch? can you show an example?
Sure.
I use react-native to implement virtual scroll (in <List> using <FlatList>.
So when I scroll down my from changes but when I want to refresh (pull down or coming back to this screen) I need to either call refetch to force rerunning query - if I haven't scrolled yet and my from is the same or setState - if I have scrolled and my from differs.
class ListContainer extends Component {
cachedClasses = []
hasReachedEnd = false
loadingMore = false
state = {
from: moment(),
}
onLoadMore = () => {
const { from } = this.state;
if (!this.hasReachedEnd) {
this.loadingMore = true;
this.setState({
from: from.clone()
.add(7, 'days')
.add(1, 'day'), // another date on subsequent request
});
}
}
render() {
const { from } = this.state;
return (
<Query
query={ListOfClassesQuery}
fetchPolicy="network-only"
notifyOnNetworkStatusChange
variables={{
from: from.format(dateApiFormat), //DATE ONLY
until: from.clone().add(7, 'days').format(dateApiFormat), // DATE ONLY
}}
>
{({
loading, data, error, refetch,
}) => {
if (error) {
return <ErrorMessage>{error}</ErrorMessage>;
}
if (!loading) {
this.loadingMore = false;
if (data.allClasses.edges.length === 0) {
this.hasReachedEnd = true;
} else {
this.cachedClasses = [...this.cachedClasses, ...data.allClasses.edges];
}
}
return (
<List
loading={loading}
loadingMore={this.loadingMore}
refetch={() => { // refreshes the list - called when pulling down or coming to this screen
this.cachedClasses = [];
this.hasReachedEnd = false;
const now = moment();
// THIS FOLLOWING WAS CRITICAL TO ME ---->
const willVariableChange = from.format(dateApiFormat) !== now.format(dateApiFormat);
if (willVariableChange) {
// apollo will refresh data on setState only if variables change
this.setState({
from: now,
});
} else {
// otherwise wee need to force the refresh
// I do not wanted to use setState and refetch at the same time
// because it would then run query twice on some occasions
refetch();
}
}}
allClasses={this.cachedClasses}
onLoadMore={this.onLoadMore}
/>
);
}}
</Query>
);
}
}
Have the same issue using
"apollo-boost": "0.3.1",
"apollo-client": "2.5.1",
I was having exactly the same issue. Using no-cache instead of network-only worked for me.
Neither no-cacho or network-only works for me
@joe-askattest I had issues with client.query also. I solved it by chanaging:
const { data: { getUser } } = await client.query({ query: gql(queries.getUser) }, { options: { fetchPolicy: 'network-only' } });to
const { data: { getUser } } = await client.query({ query: gql(queries.getUser), fetchPolicy: 'network-only' });When you call
client.query({}), the options object in the picture below represents what's passed when the request is made. It looks foroptions.fetchPolicyinstead ofoptions.options.fetchPolicy
Yours would be
let res = await this.props.client.query({ query: MY_QUERY, variables: { filters: this.state.arrayOfFilters, }, fetchPolicy: 'network-only' });Just worked to me
This issue has definitely gotten a bit unwieldy. Some people are reporting this issue as fixed, others as not fixed, others are reporting new issues, etc. I'm going to close this issue, but please consider opening a new issue if you're still encountering any problems. Thanks!
It's still broken!
Still broken, and graphql's aggressive caching in general is the source of tons of bugs. Unnecessary premature optimization when you're just trying to get a simple cyclic state refresher working.
All my errors have gone when I put errorPolicy: "all"
@Aetherall
If you already have the data in cache, it yields false->true->false. How did you solve this issue?
@mieszko4 antiCache solution fixed it for me. Definitely a hack. But it works.
with new version of apollo, using hooks, it works fine for me!
Tried it with hooks and I'm still getting the cached data when the fetchPolicy is set to "network-only" I realize "no-cache" isn't efficient (new fetch per request) but turning the cache off definitely turned it off:
const {
loading,
error,
data
} = useQuery(LCRF_SUBCATEGORIES, {
variables: { input: { orgId: unit.orgId, isUnitManaged: true, type: "BUDGET" } },
fetchPolicy: "no-cache", // network-only introduces a weird defect where permissions are being cached: 107847
notifyOnNetworkStatusChange: true,
onError: handleGqlNetworkError,
onCompleted: data => {
if (data && Object.keys(data).length > 0) {
updateLcrfSubcategoriesCopy(
data.lcrfSubcategories.sort((row1, row2) => (row1.subcategorySortOrder > row2.subcategorySortOrder ? 1 : -1))
);
} else {
console.error('LCRF_SUBCATEGORIES query returned an empty data set');
}
}
});
With
"@apollo/react-hooks": "3.0.0",
I make a useQuery request in one component, and then another makes a useQuery request, whichever resolves last then becomes the value of the other component. They are different queries!
my client is configured for "network-only", adding "no-cache" option to useQuery fixed the issue.
@Aetherall
If you already have the data in cache, it yields false->true->false. How did you solve this issue?
Hey, were you able to get this issue resolved?
I am facing this issue in Query Component. ssr doesn't work, no-cache doesn't work. I cant add that timestamp as backend isn't in my control.
Facing issue in v2.5.8 and I have also tried updating to v3.1.3
Has this been fixed for Query Component?
Setting a pollInterval does send a new network request. But changing variables doesn't.
How we end up fixing this is by passing refetch back and after state has updated we call the refetch to forcefully send a network call and as the input has already been updated it sends updated query params in the network call.
Not the best solution but thats how we end up solving it without cache buster. Other solutions discussed above didn't work and i didn't try useQuery(looking from the answers seemed like people ran into issues in that as well).
This works for me
const {
data,
loading
} = useQuery(QUERY, {
fetchPolicy: 'network-only',
variables: { requestVariables },
});
with
"apollo-client": "^2.6.4"
Most helpful comment
It's still broken!