Just upgraded to Apollo 2.0, using react-apollo 2.0.0 -- it now appears that the graphql props option for a query is passed a data argument that can have loading set to false but no data.
That is, given a query, say:
query X($id: ID!) {
myItem(id: $id) {
id
field
}
}
and a graphql call:
graphql(query, {
props({ data: { loading, error, myItem } }) {
console.log('loading =', loading);
console.log('error =', error);
console.log('myItem =', myItem);
return { ... }
}
})(MyComponent)
We're seeing the output:
loading = true
error = undefined
myItem = undefined
loading = false
error = undefined
myItem = undefined
loading = false
error = undefined
myItem = {<data>}
That is, there is an interim state between loading having been set to false but myItem yet available on the data argument.
Is this expected, as it appears to differ from the behavior of Apollo 1.0. And if so, what is the reliable way to check that data was loaded and _is ready for use_ in the component?
We're now using (loading || !myItem) to check whether something is loading.
I can confirm this issue exists.


Offending code:
graphql(
gql`
query localise($locale: LocaleType!, $resourceIds: [String]) {
l10nSlugs(locale: $locale, resourceIds: $resourceIds) {
id
resourceId
slug
}
}
`,
{
name,
options: ({ locale }) => ({
variables: {
locale,
resourceIds
},
}),
props: props => ({
l10n: {
/**
* Whether or not the graphql resource is loading.
*/
loading: props[name].loading,
/**
* Conveniently offer the locale.
*/
locale: props.ownProps.locale,
/**
* And the BCP47 normalise version.
*/
bcp47Locale: normaliseBCP47Tag(props.ownProps.locale),
/**
* Localise a slug with insertions.
* @param {string} resourceId Resource ID of the slug to localise.
* @param {string} slug Default slug in case loading.
* @param {Array<string> | Object: []} insertions Dynamic content for the slugs.
* @returns {string} Localised slug.
*/
localise: (resourceId: string, slug: string, insertions: [string] | Object = []): string => {
if (!props[name].loading && !props[name].error) {
^^^^^^^^^^ Checked here...
for (let s of props[name].l10nSlugs) {
^^^^^^^^^^^ BAM!
if (s.resourceId === resourceId) {
return insert(s.slug, insertions)
}
}
}
return insert(slug, insertions)
},
/**
* Locale aware ordinals (e.g. 1st, 2番目)
* @param {Number} ord The numerical ord to convert.
* @returns {string} The locale-specific ordinal
*/
ord2str: (ord: Number): string => props.ownProps.l10nShared(`${ord}ord`),
/**
* Get whether or not the current locale arranges the name Last, First.
* @returns {boolean} True if the locale requires a Last, First name arrangement.
*/
nameLastFirst: (): boolean => NameLastFirstLocales.includes(props.ownProps.locale),
/**
* Gets teh minimum number of characters allowed in the locale's name part.
* @returns {number} The minimum number of characters in the current locale.
*/
minCharsInNamePart: (): number => MinCharsInNamePart[props.ownProps.locale]
}
})
}
)
Yeah, got the same error when trying to pass my company project to the last version, was previously in 1.4.16.
Is anyone looking into this? This is a serious bug that is killing quite a bit of my code, now.
Can confirm this happens now after i updated today to [email protected] and [email protected]
UPD:
some investigation/debugging led to this line in apollo-client package, giving null in the result,


@adamdonahue I'll take a look at this! Still working through issues after launch + took a week off last week! Thanks all for the issue report!
Btw, i've resolved that on my side by setting fetchPolicy to cache-and-network, no more errors after that. So seems like the error is there only with network-only
@javascriptlove Actually, the issue exists with the default setting, too.
Any workaround that doesn't require adding a check on data for all loading queries ?
@adamdonahue Can you please provide a stripped down reproduction for us to test? I've tried to reproduce with our test app Githunt, but haven't been able to.
I just tested with the 1.0.3 of apollo-client, and everything's work for me. Thanks a lot @jbaxleyiii.
This has been confirmed as fixed with 1.0.3 in apollo-client! Thank you all for the reporting and helping to diagnose and fix this one!
Confirmed fixed in 2.0.1.
EDIT:
Fixed on my end by just adding an id to every query level. However, still unsure why some id's returned the data but some did not...might have bad data on my end. Will continue to debug.
hi @jbaxleyiii, @peggyrayzis i am using graphcool service to host my data and all my queries work in their playground when I pass in the given ids. However, on the client side, some queries will correctly return the data and some will not return any data even if loading: false. I am on apollo-client 2.0.4

after some digging around, the data is coming in correctly into newData.results. However, isMissing resolves to true from this line isMissing = !newData.complete ? !newData.complete : false; because newData.complete comes in as false. This then ultimately resolves into this line that then takes the data from lastResult which is undefined and then resultFromStore.data returns undefined. Is there something wrong in my query that makes complete resolve to false? Not exactly sure what is happening here and would like some input if possible. Thanks!

still have this issue with version '2.0.4' here 😢 . Sometimes it will work with safari but it constantly failed with chrome.
@crokobit what do you mean by working in safari and failing in chrome? Are you talking about the data.loading: false but not seeing the expected data?
I'm on 2.0.4 and the render function on a component is called 3 times, 2 of which have loading = false and data = null and the last one has the data.

What are those extra 2 renderers for?
@j4mesjung yes~
@jbaxleyiii @peggyrayzis This issue still occurs for me.
I am using react native and
Interestingly enough, the issue only arises when I introduce 'id' as a field in my query. If I do not specify 'id' in my query, then everything works as expected.
Render flow goes like this:
Hope this helps!
I'm seeing this too. If it helps, I know the data is already in the store and the request returns the correct data. It seems to happen when I render multiple components with queries at the same time?
@denkristoffer do you have any reproduce repo? I can't reproduce this in my branch: https://github.com/xcv58/react-apollo-error-template/tree/2591adeeb9401fb90dcb28ed84c44d53ed58285a
I have this issue as well, it is a very simple query but it just never return any data when loading is false and error is undefined.
"apollo-client": "2.0.4"
"react-apollo": "2.0.4"
However it returns very quickly when using graphiql
------------------ update ---------------------
Fixed it by adding id to every type in the query, like literally every type mentioned in affected query, otherwise it will not work...
I have the same problem after running a mutation which returns updated data.
Can confirm I am having the same problem, used to work when id is attached to every queries, but now it doesn't. Seems to be triggered by a mutation that adds something.
I have the same problem as well. ([email protected])
This is a serious bug and this issue should be re-opened.
I got this issue as well, but was able to fix it. In my case it was mostly because the error messages aren't totally clear. I had a mutation which did not return all properties of the entity, this in turn caused the list of entities I was mapping over to be undefined. When I retrieved the last property (albeit being 'null') the data was correctly injected into props.
This 'gotcha' could probably be either documented more clearly on the mutation / updating the store pages, or indicated more clearly when there is an error in the console. It seems counter-intuitive when the idea of a graph setup is to retrieve only the properties which are important to you, and not overfetch, when it in turn gives an error in Apollo.
^ got this same issue, and this workaround worked for me as well (have the mutation return the same complete object subfragment as the original query). Totally unintuitive with graphQL and difficult to manage because different queries in our app return slightly different subfragments. Also no error or warning here, so I just ended up getting data.foo === undefined and data.loading === false which was a pain to try and debug.
I've just experienced this issue as well, but only when I test my app on chrome with network throttling, so it may appear when the network is slower or something...?
This is breaking a lot of things for us. Any known workaround?
@grydstedt The best workarounds I've found:
ids in the graphql objects whenever you request them. (This helps apollo-client resolve cache better)In no way am I suggesting these are good workarounds. But they are workarounds nonetheless.
@nadeesha adding id fixed it for us, still annoying tho... Thank for the workaround.
I am just running into this issue and I don't have the ability to add id to every field. Any ideas for an alternate fix? I am using apollo-boost. Thanks
Getting this issue as well...the query seems to run fine with loading: false, but the data just remains null even though in network request I can see the query has returned data.
The only workaround that "solved" the problem for me was setting fetchPolicy: 'no-cache'.
I hope this will help.
The error is not in react-apollo, but in apollo-client. I'm using it with angular 4 (apollo-client version 2.2.8) and got the same error. The only workaround was to set fetchPolicy: 'no-cache' just like said @pitou
This issue disappeared for me after migrating from apollo-client-preset to apollo-boost and [email protected]
still have the issue, why it was closed? It comes when we try to fetch a query twice in the same time.
I do have the same error using apollo-client 2.2.8 and apollo-cache-inmemory 1.1.12.
UPDATE: I'm seeing this strange state again. it occurs after I update the cache using data from an optimisticResponse. I'm thinking that maybe it is caused when you update the same query in the cache simultaneously. Maybe it creates a race condition of some sort.
I also just saw this with [email protected] and [email protected] (and earlier versions). I'm not able to reproduce it reliably though. Any chance we could re-open this @jbaxleyiii?
I experience this issue with react-apollo 2.1.3 and apollo-boost 0.1.4
Still having this issue with latest versions, can we re-open this issue?
Second that, this bug has costed us at least 10 person-days for our little project, which has a total of ~200 person days spent on it...
Experiencing this issue with [email protected] and [email protected]
I have the same problem -- I give my component new props, loading is false but the data variable of the render prop function is empty. However, when rendering the first time, it works.
My query is the following:
query FeedQuery($first: Int, $offset: Int, $filters: [FilterInput]) {
datasheets(first: $first, offset: $offset, filters: $filters) {
id
productType
articleId
excelPath
weight
}
}
Interestingly, when I exlude the $filters variable, it works. $filters is a list of an input type (FilterInput) which consists of simple scalars. Do array fields need special care?
The query component looks like this:
<Query query={FEED_QUERY}
variables={{first: this.props.first, offset: this.props.offset, filters: this.props.filters}}
>
{({loading, error, data}) => {
if (loading) {return "Loading"}
if (error) {return "Error"}
if (data.datasheets.length === 0){return "No result"}
return (
<List>
{
data.datasheets.map(article =>
<ListItem key={article.id}>
<ArticleCard article={article}/>
</ListItem>
)}
</List>
)
}}
</Query>
My versions are
@adrianschneider94 Can you test this with my patch from #2003? You can test by replacing react-apollo with @steelbrain/react-apollo in your project temporarily
@steelbrain Thanks! The only problem left is that it hangs sometimes in the loading state depite the server returned data. I can‘t really see a pattern but I also don‘t know if the problem is even related.
With all the workarounds suggested here, this behaviour is still a bug (48 comments). It is now the main source of pain in process of migration from 1.0 to 2.0.
@jbaxleyiii Are you going to do something with it?
UPD: I have this issue only while { fetchPolicy: 'no-cache' }.
In this state react-apollo is hardly useable - I can't manage to make a simple query work. I also tried with React-Apollo 1.4 - but no luck.
I switched now to URQL where this issue doesn't exist.
@adrianschneider94 seems related to https://github.com/apollographql/react-apollo/pull/2003#issuecomment-393984128, can't wait for that PR to get merged in...
@felixk42 I already tried @steelbrains workaround. It makes it better, but the query randomly stucks in the loading state.
We are also being effected by this bug.
I really hope that either https://github.com/apollographql/react-apollo/pull/2003 or some other fix gets merged soon. Thanks @steelbrain for your work on this.
The situation is as described above in https://github.com/apollographql/react-apollo/issues/1314#issuecomment-352960802 with React on the web.
loading is true, data is not present.loading is false data is present.loading is false, data is absent. React component crashes as a result.We implemented the two workarounds:
id to everything requested. This works for the query.As https://github.com/apollographql/react-apollo/issues/1314#issuecomment-370406018 suggests, our expectation was that with GraphQL we should be able to under fetch and things should work as expected. Now we are certainly over fetching with the fragment dragging around a lot of unneeded data into different components. We have essentially created a static client side "endpoint" that needs to be used everywhere a certain type is requested, on pain of crashing the app potentially in some other place. This sort of defeats the object here even for simple situations.
If id is so essential to the operation of the cache, it should be added by the client itself without exception.
We'd really appreciate a fix sooner rather than later. Thanks a lot.
@jbaxleyiii
Can we please get this opened again? Would be great to see this solved. Happy to test any code to solve it.
Any update on this?
Adding the field id in every query from every type solve the problema to me :)
any update on this?
I also get this with [email protected] and [email protected]. The console displays a warning but console.log(loading, error, result) gives me false undefined undefined. The error in question is myfield is of type NilClass - MyType expected.
Any update on this? Also having same problem using the latest versions available.
~I switched the fetchPolicy from no-cache to network-only and it works back again for me.~ Ok, it's still pulling from the cache with network-only.
I'd say it's critical bug that introduces a lot of regression in projects. It's here for more than a year I've created tons of code relying on that already and hit the wall now.
My stack is currently:
A lot of my stack doesn't apply to this issue however, when I debug my react-native application with the use of the React Native Debugger and it's inbuilt inspector:

I have access, inside my appsync object, to ROOT_MUTATION and ROOT_QUERY. For context, getRequests and openRequest are the __typename's of the queries/mutations.
If I clear my cache and then query the HOC, getRequests with, this.props.getRequests it will have no data/getRequests object.
HOWEVER, if I query it with the Query element it will add a ROOT_QUERY.getRequests to the appsync object, thus allowing me to forever query it with the previously mentioned HOC.
This means that if I can find a way to add the query to ROOT_QUERY when I call the HOC, if not already present, I can get data.
Has anyone else run into this use case?
Hope I helped anyone else, im not to sure how use case it is with Appsync though
We are also encountering this issue and are also exploring various hacky workarounds. Right now there is a theory that this issue is being caused in part by a very large response object.
@bijection @kevinburke @antimatter15
Edit: the size doesn't actually seem to matter, it ended up being, as others above had said, about having ID on a type. If the type doesn't have an ID you can get this behavior where things are fetched but Apollo doesn't error and says that loading has finished.
In our current project this error only appears if we load 3 components with the same query but different input variables simultaniously.
still have this issue with version '2.0.4' here 😢 . Sometimes it will work with safari but it constantly failed with chrome.
Same for me.. sometimes it works in safari but constantly fails with chrome..
In our current project this error only appears if we load 3 components with the same query but different input variables simultaniously.
same for me 😢
Reopened based on #1314.
Issues are more likely to get attention if you PR a breaking test.
Can confirm, spent a lot of time figuring this one out. Adding the ID fields seemed to solve the problem for now.
We are encountering this issue at the moment.
We created a new query that would bring ID onto the root level of the response, unfortunately it did not solve the issue.
Are using latest versions of apollo
Not using boost
Have ID on root level of response
Query is successful, (data can be seen in console), isLoading is false, data is undefined.
This is happening to us on React Native app. Happens on both ios and android.
What does your query look like now? I needed ID on _every_ level of the response to make it work.
This is affecting us, as well.
Query successful.
Data returned correctly for query when looking at network tab in dev tools.
isLoading=false;
error=undefined;
data={};
Worth mentioning we are using network-only
Same here, we are losing data from Apollo cache on some fetches with no error message. Sometimes it helps to add id to types on queries if this type of data already fetched by application and id was requested on previous fetches. Looks like not documented feature/bug.
I have prioritized this for review by the core team.
My solution for now (which works quite ok) is to not rely at all on "loading" field, but only to check presence of real data. In most of cases it's obviously simple.
Good side-effect is having more smooth data refreshing while loading screen is not flickering around.
Same here: After a mutation the query data set is empty while loading is false. Added _id and typename to all levels of the mutation and the query.
The only workaround for me was to set fetchPolicy: 'no-cache'
I don't know if someone else can confirm this, but I could see this behavior in my project with apollo-cache-inmemory >= 1.1.12 regardless the version of react-apollo, apollo-client & co. As soon as I downgrade to 1.1.11 I no longer have this problem.
In my case the data object never ends up being populated, which is not exactly what other people reported here... so ... not sure this will help.
After remove the defaultOptions from ApolloClient constructor, the error disappeared. Hope it helps to locate the problem.
@zcfan What are the options you are passing to the constructor when the problem does not occur?
@valoricDe Sorry I made a stupid mistake in last comment. After remove defaultOptions error disappeared.
Same problem with apollo-client 2.3.5
Loading works for each fetch policy EXCEPT no-cache.
When no-cache is set, loading is False even if data is still loading.
Alright guys, we are developers. It can' be that we are not able to fix this. So let's spread some light:
In my team we are doing a mutation somewhere in our app which changes a field defined in a query somewhere differently in our app.
The effect occurs on my machine in the else case of QueryManager.prototype.getCurrentQueryResult. There it tries to read the new data from the InMemory cache via this.dataStore.getCache().read(...) which results in {}.
In the depths of getCache().read it goes down until StoreReader.prototype.diffQueryAgainstStore which fetches the correct result and saves it to execResult. There it says does:
if (previousResult) {
if (isEqual(previousResult, execResult.result)) {
execResult.result = previousResult;
}
}
Why do you need to set the result to something which is equal to itself? strango
But it does return the correct result. So it must be something on the way back from the store.
in our case, we weren't using caching at all (using internet-only) and were still running into this issue. I _think_ this is an issue unrelated to caching.
we switched to a different graphql client as it wasn't worth the headache.
To add to my last post: We are updating the field id via a mutation. But are requesting the fields id and name. So in QueryManager.prototype.getCurrentQueryResult we run into the catch case "Can't find field name on object {
"id": "58d2498a4b04157110c923",
"__typename": "Channel"
}."
Which returns return { data: undefined, partial: true };. In ObservableQuery.prototype.currentResult we then convert undefined to {} et voila we have an empty response.
Looks like it relates to: https://github.com/apollographql/apollo-client/issues/3267 and https://github.com/apollographql/react-apollo/pull/2003
Although, as we occured problem with apollo.loading False, even if data was still loading (no-cache) we found solution (ugly, but still).
On query inside result(data) arrow function, we check data.loading. It seems like this parameter is not related to apollo.loading and works fine . (So we just created variable loading true on mounted page and set false when data is loaded, it might help someone).
But still - it's more a hack then solution.
As we have already enough hacky solutions in this thread I would advise against posting further hacks and instead contentrate on the problems I reveiled in https://github.com/apollographql/react-apollo/issues/1314#issuecomment-466401693 and https://github.com/apollographql/react-apollo/issues/1314#issuecomment-466410031
This is happening to us as well, in a totally isolated page with no mutations and no other queries. Our structure is retrieving a structure roughly as follows
query Project($uuid: ID!) {
project(uuid: $uuid) {
milestones(first: 40) {
edges {
node {
id
uuid
owner
...more properties...
parent {
id
uuid
owner
...more properties...
}
}
}
}
}
In this case the parent attribute is the same type as the node it's on (a Milestone), and that node may or may not be returned from the server already.
Having ID's on everything does not help. When setting fetchPolicy=no-cache we get a different strange behavior, the query is executed 3 times. The first time we have no data (this bug), the second time we have data, woohoo! And the third time we again see this issue
Removing the parent attribute immediately solves the problem.
Our extremely hacky workaround is to use fetchPolicy=no-cache with a wrapper that tracks if it was successfully executed once, as follows:
const NewProjectView = props => {
let renderedNoIssue = undefined;
return (
props.match.params.uuid !== '' ? (
<Query query={query} variables={{ uuid: props.match.params.uuid }} fetchPolicy='no-cache'>
{({ loading, error, data }) => {
console.log(props.match.params.uuid);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
if(Object.keys(data).length === 0) {
if(renderedNoIssue === undefined) {
// This will create a weird state... do it anyway i guess
return <View project={data.project} stagedProperty={{}} />;
}
} else {
renderedNoIssue = <View project={data.project} stagedProperty={{}} />;
}
return renderedNoIssue;
}}
</Query>
) : (
<div />
)
);
}
@willtrking could you have a look if node_modules/apollo-client/core/QueryManager.js: 610 swallows a exception when executing the queries?
@valoricDe
Looks like a couple things are happening, I'll first address the triple-loading bug when setting fetchPolicy=no-cache and then keep looking
With fetchPolicy=no-cache the partial flag from QueryManager.prototype.getCurrentQueryResult is never set when the query isn't done, leading ObservableQuery.prototype.getCurrentResult to not set the loading flag, and somewhere down the line the data field (which is set to undefined in getCurrentQueryResult) is being set to an object.
See these lines under ObservableQuery.prototype.getCurrentResult
var queryLoading = !queryStoreValue ||
queryStoreValue.networkStatus === NetworkStatus.loading;
var loading = (this.options.fetchPolicy === 'network-only' && queryLoading) ||
(partial && this.options.fetchPolicy !== 'cache-only');
Changing this to
var queryLoading = !queryStoreValue ||
queryStoreValue.networkStatus === NetworkStatus.loading;
var loading = ((this.options.fetchPolicy === 'network-only' || this.options.fetchPolicy === 'no-cache') && queryLoading) ||
(partial && this.options.fetchPolicy !== 'cache-only');
Fixes that issue immediately. I'll come back a bit later with some results from testing WITHOUT fetchPolicy=no-cache
EDIT: I'll submit a PR to apollo-client to hopefully fix this
@valoricDe
QueryManager.prototype.getCurrentQueryResult is indeed swallowing an exception. In my case it's an Invariant Violation: Can't find field parent on object exception. Looks like because SOME of objects returned DO NOT have a parent field (as they do not have a parent) while SOME do, Apollo thinks we're missing fields.
Continuing to dig.
EDIT: In my case it seems like for some reason my GraphQL response is not behaving according to spec (https://facebook.github.io/graphql/June2018/#sec-Value-Completion). I will get my response up to spec and then see if the issue persists.
For me, that would mean the "solution" to this bug would be to not swallow the exception.
EDIT EDIT:
I can confirm that returning nulls instead of omitting fields has fixed the issue for me (for now)
I have that issue too on the latest version of apollo-client. Removing fetchPolicy: 'no-cache' from query options fixes the problem. I have reverted apollo-client version to 2.4.13 and it seems to be working properly.
Also having this issue
I'm not sure there's an issue within apollo-client because I use a loggerLink and it reports that the query did resolve with the expected data.
Could this possibly be related to the componentWillReceiveProps method in the Query component?
Not sure what the cause was but this method was behaving very inconsistently for me in my own components. Since it's being deprecated I updated them to use getDerivedStateFromProps and componentDidUpdate (as is recommended in the official react guide) and that fixed things.
EDIT: I should make clear that this did not fix the react-apollo issue. I still have that. I'm just implying that the bug may be related to the Query component's use of componentWillReceiveProps.
UPDATE
I've narrowed down the location of the bug. It appears to be in the cache.
In DataStore.markQueryResult (this file) I receive the data I expect, and then it places the data in the cache:
this.cache.write({
result: result.data,
dataId: 'ROOT_QUERY',
query: document,
variables: variables,
});
However, when the result is assembled further down the line (QueryManager.getCurrentQueryResult here) it's drawn from the cache again, but the cache doesn't find anything:
try {
const data =
this.dataStore.getCache().read<T>({
query,
variables,
previousResult: lastResult ? lastResult.data : undefined,
optimistic,
}) || undefined;
return { data, partial: false };
} catch (e) {
// I end up here. Signalling that there's nothing in the cache
return { data: undefined, partial: true };
}
I'm assuming then that the issue is possibly related to the way the cache is generating keys for results?
Result definitely went in... but result did not come back out...
EDIT:
SOME MORE INFO:
The cause of the exception which causes the cache-miss appears to be in the optimism library at the point of key generation. It does appear to be receiving the correct input variables - i.e. the correct query document and variables - as input, but then the key it generates seems to correspond to a request which I never even sent... at least I don't think I did. Either way, the entry for that request is missing.
For clarity, my request has the following shape:
query {
getAllowedClasses(graphInput: GraphInput, fromNodeKey: String, toNodeType: String)
}
type GraphInput {
nodes: [GraphInputNode]
edges: [GraphInputEdge]
}
type GraphInputNode {
key: String
constraints: [Constraint]
classId: String
}
type Constraint {
type: String
value: String
}
type GraphInputEdge {
sourceKey: String
targetKey: String
}
I also have the same issue with the fetchPolicy: 'no-cache' then the value cycle of the loading property of Query was false -> true -> false in version 2.5.1. I went back to version 2.4.13 as suggested by @adrianos10 (thanks ;) ) and then all worked correctly
Possible solution for everyone here...
Are you updating all of your state immutably? I just updated all of my reducers/methods-making-calls-to-setState and made sure that any operations which touch broken components do a deep clone of the state.
This fixed it for me
This tells me that cache diffs are based on object ids rather than the primitives within them.
Immutable state updates are obviously a good thing.... but they're also expensive and are an 'opt-in' thing in javascript (either with libraries like immutable or by being a smart-alec).
What should change to stop more people falling into this hole? Should the docs warn against non-immutable state updates... or does the cache diffing need to change?
The issue is still there in ver 2.5.3.
The pic shows that the data has been fetched but the component has been re-rendered again.
so, that it causes an empty returning...

Any suggestions?
Encountering a similar error in 2.5.1.
The data coming from the Query-component is {} instead of undefined and then switches to the actual expected payload.

By adding fetchPolicy="cache-and-network" the empty object appears twice:

I have solved it now by taking the loading state into account when accessing the data.
@imakou are you querying for the ID for "list" in you query above? I had the same issue, and what solved it for me was ensuring that I was querying the ID field for all subqueries.
@smkhalsa Similar problem on my side - resolved by adding ID in all query entities even those never touched in cache operations. Thanks.
Same issue with:
"react-apollo": "^2.5.5"
"apollo-client": "^2.5.1"
"apollo-cache-inmemory": "^1.5.1"
"apollo-cache-persist": "^0.1.1"
LE:
It never happens with 'network-only' as fetchPolicy
I've just found out that I don't have the issue anymore if I disable cache persistence (I am using apollo-cache-persist)
I solved putting:
errorPolicy: "all"
I'm sure it won't help all cases where this is happening, but this was happening for me when resolving an object with undefined values instead of null values.
Example:
// works
res.json({
contact: contact || null,
hasPaid: false
});
// doesn't work
res.json({
contact, // contact: undefined
hasPaid: false
});
This was really confusing, spent hours. Suggestions above to query ids of all subfields solved it but is it required by Apollo to work?
Somehow a query in one location caused the other one to re-execute and later ended up with {loading:false, data:{}, error:undefined}
react-apollo 2.5.6 includes new returnPartialData functionality, that will help address this issue. Please see the changelog for more details. Thanks!
@hwillson I vote for reopening this issue.
When the returnPartialData flag is not set, the apollo Query component should imo not return an empty {} when some required data is not found, or?
@valoricDe Setting returnPartialData to true is the solution for this until the next major release of Apollo Client. After that, it will become the default.
@hwillson Thanks for the update on this issue!
Setting returnPartialData to true is the solution for this until the next major release of Apollo Client. After that, it will become the default.
Does that mean that in the next major release, in the example from the changelog, the component which uses GET_MEMBER_WITH_PLANS would resolve immediately with some properties missing _by default_?
If so, that sounds dangerous to me. If the second component is implemented to expect all properties to be available, it would work if it is implemented first. As soon as you add a component that requests less fields, the previous component could break.
Also: Is returning partial data really the fix to the problem described at the top of the issue? To me, a good default would be that loading becomes false as soon as all necessary data for a given query is fetched and that data can be provided to the component – no matter if another component uses a similar query. Handling partial data should be opt-in IMO, as it requires additional null checks, even for properties which are non-nullable in the schema.
Or am I missing something?
I don't see how returnPartialData has anything to do with the original bug. The issue here wasn't that we had extra web requests or anything that returnPartialData addresses. The issue here was (stolen from one of the original comments on this issue):
Render flow goes like this:
loading: true, no data
loading: false, data is available and good
loading: false, no data
Hope this helps!
from your changelog:
Apollo Client will not re-use the partial data that was cached from the first query, when it preps and displays the second component.
It can't find a cache hit for the full second query, so it fires the full query over the network.
With this release, if you set a returnPartialData prop to true on the second component,
the data available to that component will be automatically pre-loaded with the parts of the query that can be found in the cache,
before the full query is fired over the network. This means you can do things like showing partial data in your components,
while the rest of the data is being loaded over the network.
Sorry, but not gonna help for this bug. If anything this feature will just make this bug harder to reproduce. It is a band-aid over the real problem.
Please, if I am completely off-base, let me know.
Would someone here be able to provide a small runnable reproduction that clearly demonstrates this issue? Talking around a concrete example of the problem will definitely help.
I was able to reproduce the issue, but the use case is a bit special. In my case it was related to how cache identifiers are generated. The example is a bit contrived, but maybe it helps to debug the issue.
Have a look at this code sandbox: https://codesandbox.io/s/apollo-error-reproduction-scrcx.
One of the query components always renders an empty object. If you remove one, the other one always succeeds.
If you look at the cache, it becomes clear why this fails:
{
"Article:5d010e4e0bcb900018dd227b": {
"id": "5d010e4e0bcb900018dd227b",
"author": {
"type": "id",
"generated": false,
"id": "Author:Holden Luntz Gallery",
"typename": "Author"
},
"__typename": "Article",
"href": "/article/holden-luntz-gallery-chapter-30-dialogues-great-photographers"
},
"Author:57a4ab99b202a366110001a9": {
"id": "57a4ab99b202a366110001a9",
"profile_handle": null,
"__typename": "Author"
},
"ROOT_QUERY": {
"articles({\"sort\":\"PUBLISHED_AT_ASC\"})": [
{
"type": "id",
"generated": false,
"id": "Article:5d010e4e0bcb900018dd227b",
"typename": "Article"
},
// ...
],
"article({\"id\":\"5d010e4e0bcb900018dd227b\"})": {
"type": "id",
"generated": false,
"id": "Article:5d010e4e0bcb900018dd227b",
"typename": "Article"
}
},
"Author:Holden Luntz Gallery": {
"id": "57a4ab99b202a366110001a9",
"name": "Holden Luntz Gallery",
"__typename": "Author"
}
}
The entry with the identifier Author:57a4ab99b202a366110001a9 is no longer referenced in the cache and therefore the component that needs the data from this entry fails. I'm not sure though what the ideal solution would be as this is due to the normalization.
If you change the returnPartialData at the top, both components render, but one is missing data.
I had this bug a few times in a project where cache identifiers might be different based on what data is fetched. I guess my use should at least cause Apollo to throw with a helpful error message if this is a use case that isn't supported.
I have to say this is a special use case. Maybe someone else has a better example? The comments above might also be interesting.
I found a simple example that may help illustrate the issue.
data will come back as an empty object if trying to fetch a field using the @client directive for a field that does not yet exist in the cache or have its own client resolver. There are no errors just an empty data object.
Removing the directive and trying to fetch a field that does not exist on the server does not cause the same issue however and the query will return the fields that do exist, ignoring the missing field.
The example is here.
https://codesandbox.io/embed/github/kgstew/react-apollo-bug-testing/tree/testing_client_directive/
I've been experiencing a very similar issue when creating a React application with hooks. I have one component nested inside the other and each component has an independent query associated with it; it seems to resolve the outside component but returns an empty object for the inner component. I've test each component as a stand-alone and they both resolve fine when it's just the single query. Any ideas?
@EternalVigil can you create a reduced CodeSandebox example?
@hwillson can we please re-open this issue? It doesn't seem to me that this is solved.
I am experiencing the same issue as well. I have a Dropdown component in the middle of the render of my component, some data has to be fetched for the dropdown options. after selecting an option, the query reads from the cache but the value of the field inside data is undefined.
I'm having the same issue, everything worked fine not until I added routing with react-router-dom and boom everything crashes, queries are only made on the first render, and once props changes query now returns data as empty object {}
Facing a similar issue . Able to see the error message in the apollo-link-error . But error from the Query components render props returns undefined . This is my response from the server .
```
{
"data": null,
"errors": [
{
"isNetworkError": true,
"status": 401,
"statusText": "UNAUTHORIZED",
"data": "Please login"
}
]
}
"react-apollo": "3.0.1",
"apollo-cache-inmemory": "1.6.3",
"apollo-client": "2.6.4",
"apollo-link": "1.2.12",
"apollo-link-batch-http": "^1.2.12",
"apollo-link-context": "1.0.18",
"apollo-link-error": "1.1.11",
"apollo-link-schema": "1.2.3",
@shyamzenefits have you tried upgrading react-apollo? There was an issue with error disappearing which was fixed in v3.1.0
@dylanwulf Thanks for the swift response . Will try upgrading 👍
@dylanwulf Tried upgrading the apollo packages to v3.1.0 , but still facing the same issue . Any Suggestions ?
@shyamzenefits Try upgrading to the latest available version (I think it's 3.1.3 right now). If that doesn't help, create a runnable reproduction (possibly with codesandbox) and post it in a new issue.
I have the same issue, in react data is always undefined despite receiving data from the server .. without the Announcement fragment data works but with the fragment for announcement data is undefined.
I tried it with the Panel fragment only and that results in data not being undefined
but with only the Announcement fragment than the data is undefined.
This is a very strange bug.
happens both while testing in localhost and in the server after deployment.
I do get this warning WARNING: heuristic fragment matching going on! index.js:1437
But no errors on the error
It links to this https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher
but that link is broken
Ninja Edit
Fixed with https://medium.com/commutatus/whats-going-on-with-the-heuristic-fragment-matcher-in-graphql-apollo-client-e721075e92be
but errors could be better.
"react-apollo": "^3.1.3",
"apollo-boost": "^0.4.4",
"apollo-link-ws": "^1.0.14",
"apollo-upload-client": "^11.0.0",
<Query
query={TimelineQuery}
variables={{ page: page}}
fetchPolicy={'network-only'} // skip the cache
>
{({ loading, error, data, refetch }) => {
if (loading || !data) return <Linear />;
console.log(loading, error, data, refetch)
if (data == null) return <Linear />;
return (
<React.Fragment>
<Sauce data={data}/>
</React.Fragment>
);
}}
</Query>
query TimeLine($page: Int) {
currentTimeline(page: $page, perpage: 10) {
pageInfo {
Count
CurrentPage
NumPages
hasNext
hasPrevious
hasOtherPages
nextPageNumber
previousPageNumber
startIndex
endIndex
__typename
}
edges {
node {
subject {
...AnnouncementsInfo
... on PanelType {
id
hidden
createdAt
zipCode
likesCount
liked
followsCount
followed
group {
name
id
__typename
}
categories {
edges {
node {
id
category
__typename
}
__typename
}
__typename
}
comments {
id
createdAt
liked
likesCount
thanked
thanksCount
attachments {
attachment
previewSm
previewMd
__typename
}
__typename
}
__typename
}
__typename
}
__typename
}
__typename
}
__typename
}
}
fragment AnnouncementsInfo on AnnouncementType {
categories {
edges {
node {
id
category
__typename
}
__typename
}
__typename
}
attachments {
attachment
previewSm
previewMd
__typename
}
group {
name
id
__typename
}
genComments {
...genComments
__typename
}
createdAt
modifiedAt
hidden
zipCode
title
id
likesCount
liked
__typename
}
fragment genComments on GenCommentsType {
id
createdAt
liked
likesCount
thanked
thanksCount
attachments {
attachment
previewSm
previewMd
__typename
}
author {
id
username
fullName
institution
position
profilePicSm
__typename
}
__typename
}
{
"data": {
"currentTimeline": {
"pageInfo": {
"Count": 261,
"CurrentPage": 1,
"NumPages": 27,
"hasNext": true,
"hasPrevious": false,
"hasOtherPages": true,
"nextPageNumber": 2,
"previousPageNumber": null,
"startIndex": 1,
"endIndex": 10,
"__typename": "PaginatorInfo"
},
"edges": [
{
"node": {
"subject": {
"id": "UGFuZWxUeXBlOjI1NQ==",
"hidden": false,
"createdAt": "2019-11-14 11:19:52",
"zipCode": "77098",
"likesCount": 0,
"liked": false,
"followsCount": 0,
"followed": false,
"group": null,
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjQ5NQ==",
"category": "Mental health",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"comments": [],
"__typename": "PanelType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjMxNA==",
"category": "General Community",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"attachments": [],
"group": {
"name": "Coco",
"id": "R3JvdXBUeXBlOjY=",
"__typename": "GroupType"
},
"genComments": [],
"createdAt": "2019-11-06 18:24:50",
"modifiedAt": "2019-11-06 18:24:50",
"hidden": false,
"zipCode": "Announcements",
"title": "Testing general",
"id": "QW5ub3VuY2VtZW50VHlwZToyMQ==",
"likesCount": 0,
"liked": false,
"__typename": "AnnouncementType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"id": "UGFuZWxUeXBlOjI1NA==",
"hidden": false,
"createdAt": "2019-11-14 10:58:58",
"zipCode": "Salado",
"likesCount": 0,
"liked": false,
"followsCount": 0,
"followed": false,
"group": null,
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjk0Mw==",
"category": "sa",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"comments": [],
"__typename": "PanelType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjY5MQ==",
"category": "ALF",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"attachments": [],
"group": null,
"genComments": [
{
"id": "R2VuQ29tbWVudHNUeXBlOjE=",
"createdAt": "2019-11-06 18:01:42",
"liked": true,
"likesCount": 1,
"thanked": true,
"thanksCount": 1,
"attachments": [],
"author": {
"id": "VXNlclR5cGU6ODA=",
"username": "KratosMars",
"fullName": "kratos Mars",
"institution": "Programming",
"position": "Dev",
"profilePicSm": "/media/profile_pictures/User_80/1a9ae3c8-0033-4c6f-b7d8-db574e8a100a.jpeg",
"__typename": "UserType"
},
"__typename": "GenCommentsType"
}
],
"createdAt": "2019-08-29 19:20:41",
"modifiedAt": "2019-08-29 19:20:41",
"hidden": false,
"zipCode": "some street address",
"title": "direct link Announcements",
"id": "QW5ub3VuY2VtZW50VHlwZToyMA==",
"likesCount": 0,
"liked": false,
"__typename": "AnnouncementType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"id": "UGFuZWxUeXBlOjI1Mw==",
"hidden": false,
"createdAt": "2019-11-06 14:34:44",
"zipCode": "Baytown",
"likesCount": 0,
"liked": false,
"followsCount": 0,
"followed": false,
"group": null,
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjkxNw==",
"category": "mental health, depression, ptsd",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"comments": [
{
"id": "Q29tbWVudHNUeXBlOjc1MQ==",
"createdAt": "2019-11-13 14:11:40",
"liked": false,
"likesCount": 0,
"thanked": false,
"thanksCount": 0,
"attachments": [],
"__typename": "CommentsType"
}
],
"__typename": "PanelType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjkwNg==",
"category": "test",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"attachments": [],
"group": {
"name": "testing",
"id": "R3JvdXBUeXBlOjE=",
"__typename": "GroupType"
},
"genComments": [],
"createdAt": "2019-06-26 20:41:00",
"modifiedAt": "2019-06-26 20:41:00",
"hidden": false,
"zipCode": "street of tests",
"title": "Testing 2 ann 4 testing g",
"id": "QW5ub3VuY2VtZW50VHlwZToxOQ==",
"likesCount": 1,
"liked": true,
"__typename": "AnnouncementType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"id": "UGFuZWxUeXBlOjI1Mg==",
"hidden": false,
"createdAt": "2019-11-04 22:17:32",
"zipCode": "Baytown",
"likesCount": 0,
"liked": false,
"followsCount": 0,
"followed": false,
"group": null,
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjkxNw==",
"category": "mental health, depression, ptsd",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"comments": [],
"__typename": "PanelType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjkwNg==",
"category": "test",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"attachments": [],
"group": {
"name": "testing",
"id": "R3JvdXBUeXBlOjE=",
"__typename": "GroupType"
},
"genComments": [],
"createdAt": "2019-06-26 20:33:47",
"modifiedAt": "2019-06-26 20:38:30",
"hidden": false,
"zipCode": "Testing street",
"title": "testing group announcement",
"id": "QW5ub3VuY2VtZW50VHlwZToxOA==",
"likesCount": 0,
"liked": false,
"__typename": "AnnouncementType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"id": "UGFuZWxUeXBlOjI1MQ==",
"hidden": false,
"createdAt": "2019-11-01 14:19:29",
"zipCode": "Baytown",
"likesCount": 0,
"liked": false,
"followsCount": 0,
"followed": false,
"group": null,
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjkxNw==",
"category": "mental health, depression, ptsd",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"comments": [],
"__typename": "PanelType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
},
{
"node": {
"subject": {
"categories": {
"edges": [
{
"node": {
"id": "Q2F0ZWdvcnlUeXBlOjM3Mg==",
"category": "Advocacy",
"__typename": "CategoryType"
},
"__typename": "CategoryTypeEdge"
}
],
"__typename": "CategoryTypeConnection"
},
"attachments": [
{
"attachment": "/media/files/Announcement_17/bfed603d-5ade-420d-aab9-4a30b6a7512c.png",
"previewSm": "/media/files/Announcement_17/3df7f057-525d-440d-811c-15b4546c1f36.jpeg",
"previewMd": "/media/files/Announcement_17/a1507d80-79b0-4fd6-9755-fe1467af70e8.jpeg",
"__typename": "GenUploadType"
}
],
"group": null,
"genComments": [],
"createdAt": "2018-12-17 15:40:38",
"modifiedAt": "2018-12-17 15:40:38",
"hidden": false,
"zipCode": "77433",
"title": "test",
"id": "QW5ub3VuY2VtZW50VHlwZToxNw==",
"likesCount": 3,
"liked": true,
"__typename": "AnnouncementType"
},
"__typename": "ActivityType"
},
"__typename": "TimelinePQEdge"
}
],
"__typename": "TimelinePQConnection"
}
}
}
I just tried querying a list of fields with an 'id' param by mistake. Instead of getting an error I just got no data.
Same issue here, using apollo-boost 0.4.7 and @apollo/react-hooks 3.1.3. Basically, my app will end up with loading: false, error: undefined, data: undefined. Has this really not been fixed yet?
Can we reopen this issue? I saw this issue in two apps recently. I couldn't reproduce the bug so far but it's definitely still happening with the latest versions.
FWIW, I've experienced this issue and tracked it down to my query asking for a client schema local field that was no longer available. Removing the reference to that local field fixed the issue.
For example, I'd have a query such as this:
{
query Thread() {
thread {
messages {
context {
... on Event {
id
state
isPast @client
}
}
}
}
}
That isPast @client was recently removed from our client schema. Once I removed that field from the request, my useQuery calls started coming back with data, without needing to make use of returnPartialData.
Hope this helps!
I just stumbled upon the same issue. I can confirm that it only appears with network-only. I'm using the angular client so maybe this is not only react-apollo related?
In my query the roles array objects are undefined event though the response from the server contains the individual role objects...
query getAreaById($id: uuid!) {
area: areas_by_pk(id: $id) {
id
name
roles {
role { // <== this object in the roles array is undefined
id
type
}
}
}
}
Seems like this issue is being revived so I thought I would chime in as well.
Context:
Using Apollo-Client + react-apollo to connect to Shopify's Storefront API
Versions:
react-apollo: 3.1.5
apollo-client: 2.6.8
What I'm querying:
shop {
name
description
products(first: 20) {
pageInfo {
hasNextPage
hasPreviousPage
}
edges {
node {
id
title
options {
id
name
values
}
variants(first: 250) {
pageInfo {
hasNextPage
hasPreviousPage
}
edges {
node {
id
title
selectedOptions {
name
value
}
image {
src
}
price
}
}
}
images(first: 250) {
pageInfo {
hasNextPage
hasPreviousPage
}
edges {
node {
src
}
}
}
}
}
}
}
So far I've been able to get my data to render by doing this:
<Query query={test}>
{(res, loading, error) => {
if (loading || !res.data) return 'loading...'
if (error) return `${error}`
return <React.Fragment>{res.data.shop.name}</React.Fragment>
}}
</Query>
Handling loading and !res.data the same way (since data is undefined by default). However, this is probably not the best way to handle this since res.data could truly be returning undefined.
Hi, i had same issue.
Context:
Using Apollo-Client + react-apollo to connect to django-graphene API.
I try to get jwt token from my back with:
const LOGIN = gql`
mutation TokenAuth($username: String!, $password: String!) {
tokenAuth(username: $username, password: $password) {
token
payload
refreshExpiresIn
}
}
`;
const [updateLogin, { loading, error }] = useMutation(LOGIN);
What i did to solve my problem was use then:
updateLogin({ variables: { username:"admin", password:"admin"}}).then((data) => {
console.log(data)
})
it work for me every time.
Confirmed that adding id for every applicable field will fix this issue.
my query{
users {
data {
name
email
}
}
}
no ID or anything. on react native version 61.5 on ios there is no problem, but on Android, although the URI is https nothing is happening loading becomes true and no error or data.
my query{ users { data { name email } } }no ID or anything. on react native version 61.5 on ios there is no problem, but on Android, although the URI is https nothing is happening loading becomes true and no error or data.
The problem was with t android emulator I switched to a real device and the query came back fine with data
Most helpful comment
I have the same problem as well. ([email protected])
This is a serious bug and this issue should be re-opened.