如何在GraphQL中正确链接useQuery和useMutation? [英] How do I chain useQuery and useMutation in GraphQL properly?

查看:159
本文介绍了如何在GraphQL中正确链接useQuery和useMutation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自react-apollo-hooks的背靠背的useQuery和useMutation.我希望能够将useQuery的返回值用作useMutation的变量.当前,useQuery的值没有及时返回给变量,导致变量未定义.

I have useQuery and useMutation from react-apollo-hooks back to back. I want to be able to use the returned values from useQuery as variables for useMutation. Currently, the values from useQuery isn't returned in time for the variables, causing the variables to be undefined.

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 显示为未定义.如何确保及时定义返回的值?

The variable data.posts[0].author.id shows undefined. How do I make sure that the returned value is defined in time?

推荐答案

如何确保及时定义返回的值?

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

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

You can simply check condition after useQuery block

不能有条件地调用钩子.

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

Usual advice is to place condition in 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 加载突变所需的数据

const client = useApolloClient();

可以使用3个参数完成自定义挂钩:(查询,变异,{mapDataToVariables})

Custom hook can be done with 3 parameters: (query, mutation, { mapDataToVariables })

这篇关于如何在GraphQL中正确链接useQuery和useMutation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆