我尝试从apollo缓存(React + Apollo Client 2.6)中读取数据。
我的代码:
try {
const {users} = client.readQuery({
query: GetUsersForView
});
console.log(users);
}
catch(e) {
console.log('Query is not in cache:', e);
}
我的查询:
query GetUsersForView($search : String, $country_id : [ID]) {
users (
filters : {
search: $search
country: $country_id
}) {
...BasicData
country {
...BasicData
}
}
}
控制台中的结果
Query is not in cache: Invariant Violation: Can't find field users({"filters":{}}) on object {
"authenticatedUser": {…},
"userSettings": {…},
"users({\"filters\":{\"country\":[],\"search\":\"\"}})": [
{…},
{…},
{…}
],
"countries": [
{…},
{…},
{…},
{…}
]
}.
我做错了什么? 查询结果在缓存中,所以为什么我不能检索数据?
答案 0 :(得分:0)
此代码段表明它正在缓存中寻找users({"filters":{}})
:
Query is not in cache: Invariant Violation: Can't find field users({"filters":{}}) on object {
"authenticatedUser": {…},
"userSettings": {…},
"users({\"filters\":{\"country\":[],\"search\":\"\"}})": [
{…},
{…},
{…}
],
"countries": [
{…},
{…},
{…},
{…}
]
}.
但是您可以在下面看到4行,即您的缓存中包含键users({\"filters\":{\"country\":[],\"search\":\"\"}})
{
country: [],
search: ""
}
,因此,您必须再次传递这些信息,以允许apollo在缓存中找到它,如下所示(适应您的第一个代码段):
try {
const {users} = client.readQuery({
query: GetUsersForView,
variables: {
country: [],
search: ":
},
});
console.log(users);
}
catch(e) {
console.log('Query is not in cache:', e);
}