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):
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 . 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
You can view example code for a range of different ApolloClient methods here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.