如何在 GraphQL 中正确链接 useQuery 和 useMutation?

How do I chain useQuery and useMutation in GraphQL properly?

我有来自 react-apollo-hooks 的 useQuery 和 useMutation。我希望能够使用 useQuery 的返回值作为 useMutation 的变量。目前,useQuery 的值没有及时为变量返回,导致变量未定义。

const { data, error, loading } = useQuery(GET_POSTS, { 
    variables: {
        id: props.match.params.id
    }
})
const item = props.match.params.id
const owner = data.posts[0].author.id
const variables = { item , owner, startDate, endDate }
const bookItem = useMutation(CREATE_BOOKING_MUTATION, variables)

变量data.posts[0].author.id显示未定义。如何确保返回值是及时定义的?

How do I make sure that the returned value is defined in time?

您可以在 useQuery 块后简单地检查条件


更新

不能有条件地调用挂钩。

通常的建议是将条件放在 useEffect:

const { data, error, loading } = useQuery(GET_POSTS, { 
  variables: {
    id: props.match.params.id
  }
})
const item = props.match.params.id

// data.posts can be undefined at start
const owner = loading ? null : data.posts[0].author.id
const variables = { item , owner, startDate, endDate }
const bookItem = useMutation(CREATE_BOOKING_MUTATION, variables)
useEffect(() => {
  if(!loading) {
    bookItem(); // called when data ready
  }
})

另一种选择:useApolloClient:

  • useQuery加载mutation需要的数据

  • const client = useApolloClient();

  • useEffect - 有条件地(!loadingdata 不为空)使用 client.mutate() 将获取的(查询中的)数据作为变量;

自定义挂钩可以通过 3 个参数完成:(query, mutation, { mapDataToVariables })

我认为您可以在实际调用突变时传递变量,例如:

...
const bookItem = useMutation(CREATE_BOOKING_MUTATION)
...
if(!loading && !error && data) {
  bookItem({
    variables: {
      owner: data.posts[0].author.id,
      ...
    }
  })
}