我的 React 应用程序利用 Apollo 的自动缓存更新来更新 UI。我想使用该mutate函数的 optimistResponse 选项,但它没有按预期工作。我想知道是否有必要update向 mutate 函数添加一个选项,或者 apollo 是否应该能够使用 id 和类型名自动更新缓存。
以下是我提供的选项:
mutate({
variables: {id: attendee_record_id, meal_choice: meal_option},
optimisticResponse: {
__typename: 'Mutation',
updateAttendeeRecord: {
__typename: "UpdateAttendeeRecordPayload",
attendee_record: {
__typename: "AttendeeRecord",
id: attendee_record_id,
meal_choice: meal_option,
}
}
})
Run Code Online (Sandbox Code Playgroud)
膳食选择会更新,但结果不会显示在用户界面中,直到服务器响应。
我在 Apollo/Graphql Expressjs 服务器上设置了 apollo-datasource-rest 数据源。我想将 fetch 响应中的一些标头转发到 /graphql 响应。
这是流程:
POST /graphql
Graphql makes fetch request using this.get('http://example.com/api')
Response from this fetch contains the header "cache-status"
Response from /graphql
I'd like to include the "cache-status" header from the example.com/api response here in the /graphql response
Run Code Online (Sandbox Code Playgroud)
我在其余数据源类的 didReceiveResponse() 方法中看到了标头。我不确定这是访问和存储它的正确位置。如何在 POST /graphql 响应中包含“cache-status”标头?
我是 NextJS 和 GraphQL 的新手,我正在使用 MERN 堆栈(NextJS 和 GraphQL)构建一个应用程序。我只需要澄清一下我是使用从查询返回的数据还是从钩子(apollo/Client)getStaticProps(nextJS)返回的数据useQuery
例如:我有一个根据 ID 获取数据的组件,它的名称是 [id].tsx,我知道在 nextJS 中我们用来在getStaticProps生成组件之前获取数据,就像在我的组件中一样
export const getStaticProps: GetStaticProps = async ({ params }) => {
let oneUserQuery = await client.query({
query: ONE_USER_QUERY,
variables: { id: params.id }
});
let user = oneUserQuery.data.userInfo;
return {
props: {
user //we fetched the userInfo and we have access to it in [id].tsx component props
}
};
};
Run Code Online (Sandbox Code Playgroud)
在组件本身中,我们可以使用 apollo/client 提供的 useQuery hook 来使用相同的 graphQL 查询来获取数据,如下所示
export default …Run Code Online (Sandbox Code Playgroud) 我有一个使用 Angular 10 和 Apollo GraphQL 的网站。
每当请求失败时,我想向用户显示错误MatSnackBar,但我不知道如何MatSnackBar向.OnError()apollo-link-error
这是我的graphql.module.ts代码:
import {NgModule} from '@angular/core';
import {APOLLO_OPTIONS} from 'apollo-angular';
import {ApolloClientOptions, ApolloLink, InMemoryCache} from '@apollo/client/core';
import {HttpLink} from 'apollo-angular/http';
import { onError } from 'apollo-link-error';
function getNewToken(): any {
//TODO: need to implement
}
const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (const err of graphQLErrors) {
switch (err.extensions?.code) {
case 'UNAUTHENTICATED':
// error code is set …Run Code Online (Sandbox Code Playgroud) 有人可以提供使用 Apollo Client 3.0 字段策略实现分页的示例吗?我一直在遵循文档中的示例来实现无限滚动,但在我的控制台中我收到以下警告:
fetchMore 的 updateQuery 回调已弃用,并将在 Apollo Client 的下一个主要版本中删除。
请将 updateQuery 函数转换为具有适当读取和合并函数的字段策略,或使用/改编 @apollo/client/utilities 中的辅助函数(例如 concatPagination、offsetLimitPagination 或 relayStylePagination)。
字段策略系统比手写的 updateQuery 函数更有效地处理分页,并且您只需要定义一次策略,而不是每次调用 fetchMore 时。
所以我尝试用新的 Apollo 方法来实现分页
列表组件.ts
// getOffers() 在 OnInit() 中运行
getOffers(): void {
this.searchService.search
.pipe(
tap(() => {
this.spinnerService.showLoader();
}),
switchMap((term) => {
this.lookupTerm = term;
return this.offersGQL.watch({
phrase: term,
offset: this.pageOffset,
limit: this.pageSize
}, { fetchPolicy: 'network-only' })
.valueChanges
.pipe(
retry(40),
map((result) => result.data),
tap(() => {
this.spinnerService.hideLoader();
})
)
}
)
)
.subscribe((result) => …Run Code Online (Sandbox Code Playgroud) 我写了一个调用 apollo 的钩子useQuery。这很简单:
使用决策者:
import { useState } from 'react';
import { useQuery, gql } from '@apollo/client';
export const GET_DECIDER = gql`
query GetDecider($name: [String]!) {
deciders(names: $name) {
decision
name
value
}
}
`;
export const useDecider = name => {
const [enabled, setEnabled] = useState(false);
useQuery(GET_DECIDER, {
variables: {
name
},
onCompleted: data => {
const decision = data?.deciders[0]?.decision;
setEnabled(decision);
},
onError: error => {
return error;
}
});
return {
enabled
};
};
Run Code Online (Sandbox Code Playgroud)
我现在正在尝试测试它,但MockedProvider …
我希望能够从我需要使用的 React Native 应用程序上传文件,createUploadLink但我在配置它时遇到一些问题。
我当前的设置如下所示:
import SInfo from "react-native-sensitive-info";
import Config from "react-native-config";
import { InMemoryCache, ApolloClient } from "apollo-boost";
import { createHttpLink } from "apollo-link-http";
import { createUploadLink } from "apollo-upload-client";
import { WebSocketLink } from "apollo-link-ws";
import { setContext } from "apollo-link-context";
import { getMainDefinition } from "apollo-utilities";
import { split } from "apollo-link";
let token: any;
const getToken = async () => {
if (token != null) {
return token;
}
token = await SInfo.getItem("ACCESS_TOKEN", …Run Code Online (Sandbox Code Playgroud) 我正在使用 ApolloClient 3 GitHub GraphQL API 从存储库检索所有版本。
查询如下所示:
query ($owner: String!, $name: String!, $first: Int, $after: String, $before: String) {
repository(owner: $owner, name: $name) {
id
releases(orderBy: {field: CREATED_AT, direction: DESC}, first: $first, after: $after, before: $before) {
nodes {
name
publishedAt
resourcePath
tagName
url
id
isPrerelease
description
descriptionHTML
}
totalCount
pageInfo {
endCursor
hasNextPage
hasPreviousPage
startCursor
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果有效负载如下所示:
这将返回前 x 个条目 ( nodes)。到目前为止,一切都很好。
我需要实现分页,并且使用fetchMoreApolloClient 提供的功能useQuery。调用fetchMore成功获取下一个 x 条目,但这些条目未显示在我的组件列表中。
如何解决“有效负载不可序列化:将循环结构转换为 JSON”错误?
我目前正在探索 Apollo、GraphQL 和 Material-UI。我从未遇到过这个错误,并且一直在通过 Stack Overflow 和博客文章寻找解决方案。
我一直在阅读有关圆形结构的文章,但无法在我当前的代码库中识别出任何圆形结构。
我需要对进入的变量进行字符串化吗createLink?
完整错误消息:
Network request failed. Payload is not serializable: Converting circular structure to JSON
--> starting at object with constructor 'HTMLInputElement'
| property '__reactFiber$b12dhgch1cn' -> object with constructor 'FiberNode'
--- property 'stateNode' closes the circle
Run Code Online (Sandbox Code Playgroud)
链接列表.js:
export default function LinkList() {
const classes = useStyles();
const { loading, error, data } = useQuery(LINK_QUERY);
if (loading) {
return (
<Typography component={"span"}>
<span className={classes.grid}>Fetching</span>
</Typography>
);
}
if (error) { …Run Code Online (Sandbox Code Playgroud) 我的 Apollo 缓存中有一个 NuxtJS 应用程序,其中包含深度嵌套的数据。作为一个例子,我的缓存可能看起来像这样,其中旅行有许多类别,其中有许多项目。
ROOT_QUERY
trips: [Trip]
0: Trip:1
categories: [Category]
0: Category:1
items: [Item]
0: Item:1
1: Item:2
2: Item:3
1: Trip:2
Run Code Online (Sandbox Code Playgroud)
我正在尝试在删除或添加项目到位于 的项目数组中后更新缓存trips[0].categories[0]。我所拥有的功能有效,但只有在与我的服务器通信并返回响应时似乎有 1-2 秒的延迟之后。在我看来,optimisticResponse要么无法正常工作,要么数据嵌套太深,无法足够快地更新 UI。
这是我的removeItem函数的样子:
import { remove } from 'lodash';
async function removeItem ({ fields, trip_id, apollo }) {
return await apollo.mutate({
mutation: removeItemMutation,
variables: fields,
optimisticResponse: {
__typename: 'Mutation',
removeItem: {
__typename: 'item',
id: fields.item_id,
name: '',
weight: 0,
unit: '',
price: 0,
category_id: fields.category_id,
quantity: 0, …Run Code Online (Sandbox Code Playgroud) apollo ×10
graphql ×7
reactjs ×3
angular ×2
express ×2
javascript ×1
next.js ×1
nuxt.js ×1
pagination ×1
react-apollo ×1
react-native ×1
typescript ×1
vue-apollo ×1