How to chain two GraphQL queries in sequence using Apollo Client

后端 未结 2 1387
闹比i
闹比i 2020-12-02 17:25

I am using Apollo Client for the frontend and Graphcool for the backend. There are two queries firstQuery and secondQuery that I want them to be ca

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 18:14

    For anyone using react apollo hooks the same approach works.

    You can use two useQuery hooks and pass in the result of the first query into the skip option of the second,

    example code:

    const AlertToolbar = ({ alertUid }: AlertToolbarProps) => {
      const authenticationToken = useSelectAuthenticationToken()
    
      const { data: data1 } = useQuery(query, {
        skip: !authenticationToken,
        variables: {
          alertUid,
        },
        context: makeContext(authenticationToken),
      })
    
      const { data: data2, error: error2 } = useQuery(query2, {
        skip:
          !authenticationToken ||
          !data1 ||
          !data1.alertOverview ||
          !data1.alertOverview.deviceId,
        variables: {
          deviceId:
            data1 && data1.alertOverview ? data1.alertOverview.deviceId : null,
        },
        context: makeContext(authenticationToken),
      })
    
      if (error2 || !data2 || !data2.deviceById || !data2.deviceById.id) {
        return null
      }
      const { deviceById: device } = data2
      return (
        
        ...
        // do some stuff here with data12
    

提交回复
热议问题