[英]Apollo Client - Possible to refetch only a fragment of a larger query when it's variables change?
I wanted to explore the pattern of fetching all the needed data for a page in one request.我想探索在一个请求中获取页面所有需要的数据的模式。 So let's say I have a user config page, which needs a list of teams to assign a user to, and a list of roles a user can have.
所以假设我有一个用户配置页面,它需要一个团队列表来分配一个用户,以及一个用户可以拥有的角色列表。 I'm using the following query to get the first page of users as well as all available roles and teams.
我正在使用以下查询来获取用户的第一页以及所有可用的角色和团队。
import { gql } from "@apollo/client";
const listUser = gql`
fragment listUser on Query {
users(page: $page, per: $per) {
edges {
node {
id
name
title
avatar
}
}
pageInfo {
count
}
}
}
`;
const roleFragment = gql`
fragment roleFragment on Query {
roles {
name
id
}
}
`;
const teamsFragment = gql`
fragment teamsFragment on Query {
teams {
nodes {
id
name
manager {
name
}
}
}
}
`;
export const getUserConfig = gql`
query getUserConfig($page: Int, $per: Int) {
...listUser
...roleFragment
...teamsFragment
}
${listUser}
${roleFragment}
${teamsFragment}
`;
And I'm using it like this (generated using graphql-codegen):我像这样使用它(使用graphql-codegen生成):
const { loading, error, data, refetch } = useGetUserConfigQuery({
variables: {
page: 1,
per: 7,
}
});
This works really well and allows me to grab the data I need for the page in one round trip.这非常有效,让我可以在一次往返中获取页面所需的数据。 However, whenever I change the page variable for users (to go to the next page obviously), it's going to refetch everything .
但是,每当我更改用户的页面变量(显然是 go 到下一页)时,它都会重新获取所有内容。 Is there a way of doing this so that it only refetches the fragment that's variables changed?
有没有办法做到这一点,以便它只重新获取变量更改的片段? Or is there a better pattern for what I'm trying to accomplish?
或者我想要完成的事情有更好的模式吗? Thanks!
谢谢!
Instead of using the useQuery hook, you can query the initial data directly using ApolloClient.query method directly, and then in subcomponents of your page subscribe to updates on subsets of your data ApolloClient.watchQuery您可以直接使用ApolloClient.query 方法直接查询初始数据,而不是使用 useQuery 挂钩,然后在页面的子组件中订阅数据子集ApolloClient.watchQuery的更新
You can view example code for a range of different ApolloClient methods here .您可以在此处查看一系列不同 ApolloClient 方法的示例代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.