I have the following code and don't work, I'm struggling to make it work for the last 4 days.
```
const newTodo = {
id: 0,
text: "text",
completed: false,
__typename: "todo"
};
const data = {
todos: [newTodo]
};
cache.writeData({ data });
const GET_TODOS = gql
query todo($id: Int!) {
todos(id: $id) {
id
completed
text
}
}
;
const da = cache.readQuery({ query: GET_TODOS, variables: { id: 0 } });
````
I get the error message:
Uncaught Invariant Violation: Can't find field todos({"id":0}) on object {
"todos": [
{
"type": "id",
"generated": false,
"id": "todo:0",
"typename": "todo"
}
]
}.
at new InvariantError
please advice what i'm doing wrong...
and this query returns the whole object
``
const GET_TODOS = gql
query todo($id: Int!) {
todos {
id
completed
text
}
}
`;
````
It's hard to tell without a reproduction (please read the contributing guide, seriously), but I think you're using cache.writeData in a way that ignores the arguments to the todos field. You should try using cache.writeQuery({ query, data }) instead. The cache.writeData method is a power tool that requires understanding how the cache works, so I don't recommend it if you're just starting out.
Hi Benjaman,
const query = gql`
query GetTodos {
todos @client {
id
text
completed
}
}
`;
const newTodo = {
id: 0,
text: "text",
completed: false,
__typename: "todo"
};
const data = {
todos: [newTodo]
};
cache.writeQuery({ query, data });
const GET_TODOS = gql`
query todos($id: Int!) {
todos(id: $id) {
id
completed
text
}
}
`;
const da = cache.readQuery({ query: GET_TODOS, variables: { id: 0 } });
I got the same error:
Uncaught Invariant Violation: Can't find field todos({"id":0}) on object {
"todos": [
{
"type": "id",
"generated": false,
"id": "todo:0",
"typename": "todo"
}
]
}.
at new InvariantError
This is so frustrating for me as I'm trying to figure out what is wrong for the last 4 days in a row.
You're either going to have to provide a runnable reproduction, or keep investigating on your side. I can't help you if you just make superficial changes that I suggest and then report back immediately. Thanks.
Here's another guess: because you're using the cache directly, rather than going through ApolloClient, you're not getting the benefit of the client automatically adding __typename to your query. Try including __typename in your query explicitly?
const query = gql`
query GetTodos {
todos @client {
__typename
id
text
completed
}
}
`;
Again, I can't be sure this will work, because you're just copy/pasting your code here. If it doesn't work, open a debugger and try stepping through the code, or something. Help me help you!
Also, what version of @apollo/client are you using?
Thank you so much Benjamn,
I put here the most small project ever
git clone https://[email protected]/unutoiul/cache-issue.git
please advice
Here's another guess: because you're using the cache directly, rather than going through
ApolloClient, you're not getting the benefit of the client automatically adding__typenameto your query. Try including__typenamein your query explicitly?const query = gql` query GetTodos { todos @client { __typename id text completed } } `;Again, I can't be sure this will work, because you're just copy/pasting your code here. If it doesn't work, open a debugger and try stepping through the code, or something. Help me help you!
I've tried the same error...
Also, what version of
@apollo/clientare you using?
I'm using import ApolloClient, { InMemoryCache } from "apollo-boost";
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"apollo-boost": "^0.4.7",
"graphql": "^14.6.0",
"react": "^16.12.0",
"react-apollo": "^3.1.3",
"react-dom": "^16.12.0",
"react-scripts": "3.3.0",
"typescript": "^3.7.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Thanks!
Your issue is that you need to write the data using the same variables and field arguments that you're using when you read the data. Instead of two different queries, just use GET_TODOS (because it correctly uses variables and arguments), and make sure that you're passing variables to both writeQuery and readQuery.
By the way, we are launching a major new version of Apollo Client in the next couple of weeks, which has been in development for the last six months. Among other changes, apollo-boost has been deprecated and removed, so I would recommend switching the docs version to 3.0 beta using the menu in the upper left instead of version 2.6. Most of what I've said applies to both versions, but you might want to try the new version before you get too deep into your current project.
Hi,
I've done exactly what you said and pushed the code in master branch...is returning the whole object...is not filtering the data...
if you can git pull origin master and check the code for me again...
What I want is to write an initial object to client/cache and then to run queries against the client/cache.
if you have the solution please push the code back in my branch
Hi all,
I have a similar issue: my stack is clearly showing that the apollo client doesn't check if the query (with the correct params) is cached before trying to get it from cache. Then the cache fails because it doesn't have the info
We can see that the cache contains a complaintActionConnection query with the param "actionTypeFilter":"COMMENT", when using the client to query with the value "OTHER_ACTIONS", it tries to get it from cache even though it is not there...!!??
index.js:1 Invariant Violation: Can't find field complaintActionConnection({"filter":{"actionTypeFilter":"OTHER_ACTIONS","complaintId":"5e33f5f1abfb0a2e440e9f36"},"first":5,"sort":"_ID_DESC"}) on object {
"category": null,
"name": "",
"eid": null,
"issueId": null,
"view": null,
"lat": null,
"lng": null,
"userLocation": null,
"kind": "service",
"city": null,
"complaintActionMany({\"filter\":{\"connectedUser\":\"5e37fb8e44843d3ae4dd205b\"},\"limit\":20})": [],
"entityById({\"_id\":\"5e33f5c7abfb0a2e440e9f31\"})": {
"type": "id",
"generated": false,
"id": "Entity:5e33f5c7abfb0a2e440e9f31",
"typename": "Entity"
},
"complaintConnection({\"filter\":{\"entityId\":\"5e33f5c7abfb0a2e440e9f31\",\"viewer\":\"USER\"},\"first\":12,\"sort\":\"POPULARITY_DESC\"})": {
"type": "id",
"generated": true,
"id": "$ROOT_QUERY.complaintConnection({\"filter\":{\"entityId\":\"5e33f5c7abfb0a2e440e9f31\",\"viewer\":\"USER\"},\"first\":12,\"sort\":\"POPULARITY_DESC\"})",
"typename": "ComplaintConnection"
},
"complaintById({\"_id\":\"5e33f5f1abfb0a2e440e9f36\"})": {
"type": "id",
"generated": false,
"id": "Complaint:5e33f5f1abfb0a2e440e9f36",
"typename": "Complaint"
},
"complaintActionConnection({\"filter\":{\"actionTypeFilter\":\"COMMENT\",\"complaintId\":\"5e33f5f1abfb0a2e440e9f36\"},\"first\":5,\"sort\":\"_ID_DESC\"})": {
"type": "id",
"generated": true,
"id": "$ROOT_QUERY.complaintActionConnection({\"filter\":{\"actionTypeFilter\":\"COMMENT\",\"complaintId\":\"5e33f5f1abfb0a2e440e9f36\"},\"first\":5,\"sort\":\"_ID_DESC\"})",
"typename": "ComplaintActionConnection"
},
"categoryOne({\"filter\":{\"name\":\"everyday_cafe\"}})": {
"type": "id",
"generated": true,
"id": "$ROOT_QUERY.categoryOne({\"filter\":{\"name\":\"everyday_cafe\"}})",
"typename": "Category"
}
}.
at new InvariantError (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:45039:28)
at http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:8746:44
at Array.forEach (<anonymous>)
at StoreReader.push../node_modules/apollo-cache-inmemory/lib/bundle.esm.js.StoreReader.diffQueryAgainstStore (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:8743:32)
at StoreReader.push../node_modules/apollo-cache-inmemory/lib/bundle.esm.js.StoreReader.readQueryFromStore (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:8718:21)
at InMemoryCache.push../node_modules/apollo-cache-inmemory/lib/bundle.esm.js.InMemoryCache.read (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:9385:33)
at InMemoryCache.push../node_modules/apollo-cache/lib/bundle.esm.js.ApolloCache.readQuery (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:9634:21)
at ApolloClient.push../node_modules/apollo-client/bundle.esm.js.ApolloClient.readQuery (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:11744:27)
at CacheManager._handleActionAdded (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47819:31)
at CacheManager.updateAfterIssueActionCreation (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47885:12)
at IssueDetail.afterActionAdded (http://localhost:3000/_next/static/development/pages/issue/detail.js?ts=1580810559978:147663:92)
at http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:11591:121
at tryFunctionOrLogError (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:14378:16)
at http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:11591:99
at InMemoryCache.push../node_modules/apollo-cache-inmemory/lib/bundle.esm.js.InMemoryCache.performTransaction (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:9466:13)
at DataStore.push../node_modules/apollo-client/bundle.esm.js.DataStore.markMutationResult (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:11587:24)
at Object.next (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:10732:60)
at notifySubscription (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47127:18)
at onNotify (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47162:3)
at SubscriptionObserver.next (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47216:7)
at http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:10587:75
at Set.forEach (<anonymous>)
at Object.next (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:10587:27)
at notifySubscription (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47127:18)
at onNotify (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47162:3)
at SubscriptionObserver.next (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47216:7)
at notifySubscription (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47127:18)
at onNotify (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47162:3)
at SubscriptionObserver.next (http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:47216:7)
at http://localhost:3000/_next/static/development/pages/_app.js?ts=1580810559978:12218:26
console.<computed> @ index.js:1
tryFunctionOrLogError @ bundle.esm.js:806
(anonymous) @ bundle.esm.js:1870
push../node_modules/apollo-cache-inmemory/lib/bundle.esm.js.InMemoryCache.performTransaction @ bundle.esm.js:943
push../node_modules/apollo-client/bundle.esm.js.DataStore.markMutationResult @ bundle.esm.js:1866
next @ bundle.esm.js:1011
notifySubscription @ Observable.js:130
onNotify @ Observable.js:165
next @ Observable.js:219
(anonymous) @ bundle.esm.js:866
next @ bundle.esm.js:866
notifySubscription @ Observable.js:130
onNotify @ Observable.js:165
next @ Observable.js:219
notifySubscription @ Observable.js:130
onNotify @ Observable.js:165
next @ Observable.js:219
(anonymous) @ bundle.esm.js:76
Promise.then (async)
(anonymous) @ bundle.esm.js:75
Subscription @ Observable.js:183
subscribe @ Observable.js:262
(anonymous) @ bundle.esm.js:13
Promise.then (async)
(anonymous) @ bundle.esm.js:12
Subscription @ Observable.js:183
subscribe @ Observable.js:262
(anonymous) @ bundle.esm.js:864
Subscription @ Observable.js:183
subscribe @ Observable.js:262
(anonymous) @ bundle.esm.js:1001
(anonymous) @ bundle.esm.js:998
step @ tslib.es6.js:99
(anonymous) @ tslib.es6.js:80
(anonymous) @ tslib.es6.js:73
__awaiter @ tslib.es6.js:69
push../node_modules/apollo-client/bundle.esm.js.QueryManager.mutate @ bundle.esm.js:950
push../node_modules/apollo-client/bundle.esm.js.ApolloClient.mutate @ bundle.esm.js:2016
(anonymous) @ IssueDetail.js:744
callCallback @ react-dom.development.js:149
invokeGuardedCallbackDev @ react-dom.development.js:199
invokeGuardedCallback @ react-dom.development.js:256
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:270
executeDispatch @ react-dom.development.js:561
executeDispatchesInOrder @ react-dom.development.js:583
executeDispatchesAndRelease @ react-dom.development.js:680
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:688
forEachAccumulated @ react-dom.development.js:662
runEventsInBatch @ react-dom.development.js:816
runExtractedEventsInBatch @ react-dom.development.js:824
handleTopLevel @ react-dom.development.js:4826
batchedUpdates$1 @ react-dom.development.js:20439
batchedUpdates @ react-dom.development.js:2151
dispatchEvent @ react-dom.development.js:4905
eval @ react-dom.development.js:20490
unstable_runWithPriority @ scheduler.development.js:255
interactiveUpdates$1 @ react-dom.development.js:20489
interactiveUpdates @ react-dom.development.js:2170
dispatchInteractiveEvent @ react-dom.development.js:4882
Show 27 more frames
Just for completeness here's my code snippet, where client is extracted from this.props (using withApollo() ):
_handleActionAdded(complaintActionCreate, cache, client) {
const action = complaintActionCreate.record;
let {actionType} = action
if( actionType !== 'MESSAGE' && actionType !== 'COMMENT' )
actionType = 'OTHER_ACTIONS'
const issueId = action.entity.complaintId;
const oldActions = client.readQuery({
query: COMPLAINT_ACTIONS,
variables: {issueId, actionTypeFilter: actionType}
});
Calling client.query instead works fine, this is maybe a misunderstanding of readQuery that I naively thought will check if exists in cache and if not will call client.query... (otherwise I don't get the difference between client.readQuery and cache.readQuery).
I also suggest, the update method of a mutation provide client as a param since I always need to pass it using the withApollo() artefact generating unnecessary boilerplate code
@ziedHamdi Could you please open another issue, and provide a reproduction?
Can confirm the same
I鈥檓 so confused... is client.query() actually exists or you mean client.readQuery()?
I'm seeing this issue too. In the resolver, I had to revert to pulling in the whole set of data to then "find" the one I needed and return it.
Scott
From the Apollo docs readQuery section:
If your cache doesn't contain all of the data necessary to fulfill a specified query, readQuery throws an error. It never attempts to fetch data from a remote server.
I kept running into this when using readQuery to grab an item from the Apollo cache when said item wasn't cached yet. If you're getting the invariant violation error and your query is formatted properly (e.g. all the necessary variables are set), check to make sure the item(s) for which you're querying are, in fact, already in the cache.
In the cases where I suspect the item(s) may not yet be in the cache, and I'm using readQuery to get them, I wrap the block in a try / catch.
Also got the invariant violation, but the section from the docs mentioned above was adapted to returns null. Guess that's only for 3.3 then? Not clear because lines below are about missing fields.
Most helpful comment
Calling client.query instead works fine, this is maybe a misunderstanding of readQuery that I naively thought will check if exists in cache and if not will call client.query... (otherwise I don't get the difference between client.readQuery and cache.readQuery).
I also suggest, the update method of a mutation provide client as a param since I always need to pass it using the withApollo() artefact generating unnecessary boilerplate code