我有 useQuery 和 useMutation 从react-apollo-hooks 背靠背。我希望能够使用 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
显示未定义。如何确保返回值是及时定义的?
如何确保返回值是及时定义的?
You can simply check condition after useQuery
block
UPDATE
不能有条件地调用 Hooks。
通常的建议是将条件放入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
:
自定义钩子可以通过 3 个参数来完成:(query, mutation, { mapDataToVariables })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)