【问题标题】:useQuery gql once from the db and then from the cache after the first requestuseQuery gql 从数据库一次,然后在第一次请求后从缓存中
【发布时间】:2020-08-06 13:15:29
【问题描述】:

是时候提出一个新问题了。每个页面作为一个查询类似:

const {data} = useQuery(EXAMPLE)

export const EXAMPLE = gql`
    query homePage(
        $orderBy: PostOrderByInput
        $userId: ID
    ) {
        posts(                   //Individual query for each page
            orderBy: $orderBy
            userId: $userId
        ) {
            id
            title
          } 
      userUserRelation{  //alway the same query. Need this request just once
            id
        }   
    }
`;

帖子查询是个人的。每个页面总是不同的变量。 userUserRelation 查询始终相同。在第一个访问的页面上,我只需要一次来自数据库的 userUserRelation。然后我可以从缓存中查询它。 是否有可能始终从数据库发出帖子请求,而用户用户关系查询只从数据库发出一次,然后从缓存发出?类似@client

当然,我可以使用全局状态来解决这个问题。并在第一次请求后制作一个没有 userUserRelation 的额外 gql。或者我做一个额外的 useQuery (但是我有 2 个查询最合适的时间......)

感谢您的帮助。

【问题讨论】:

    标签: reactjs graphql apollo-client gql


    【解决方案1】:

    您应该将查询拆分为两个单独的挂钩。这样,只要您使用默认的 fetchPolicycache-firstuserUserRelation 只会被获取一次。

    export const POSTS_QUERY = gql`
      query Posts(
        $orderBy: PostOrderByInput
        $userId: ID
      ) {
        posts(orderBy: $orderBy, userId: $userId) {
          id
          title
        } 
        userUserRelation {
          id
        }   
      }
    `;
    
    export const USER_QUERY = gql`
      query User {
        userUserRelation {
          id
        }   
      }
    `;
    
    const { data: userData } = useQuery(USER_QUERY)
    const { data: postsData } = useQuery(POSTS_QUERY, { variables: { ... } })
    

    如果您希望最初在单个请求中获取查询,您可以enable batching for your client

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 2015-11-06
      • 2018-02-10
      相关资源
      最近更新 更多