我从react-apollo-hooks背对背的fromquery和Usemoten。我希望能够将USEQUERY返回的值用作用途的变量。当前,使用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
显示未定义。我如何确保返回的值是及时定义的?
如何确保返回的值是及时定义的?
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
加载突变中需要的数据const client = useApolloClient();
-
useEffect
-条件(!loading
或data
不为空(将client.mutate()
与获取(在查询中(数据作为变量;
可以使用3个参数进行自定义钩:(query, mutation, { mapDataToVariables })
用usequery这样完成时的使用:
const bookItem = useMutation(CREATE_BOOKING_MUTATION,{
variables:{//your variables},
// to refrech your query after you create mutation
refetchQueries: [
{
query: GET_POSTS,
awaitRefetchQueries: true,
},
]} );
const { data, error, loading } = useQuery(GET_POSTS, {
variables: {
id: props.match.params.id
},
//useMutation when the useQuery is completed
onCompleted: () => {
bookItem();
},
}(
我认为当您实际调用突变时,您可以通过变量,例如:
...
const bookItem = useMutation(CREATE_BOOKING_MUTATION)
...
if(!loading && !error && data) {
bookItem({
variables: {
owner: data.posts[0].author.id,
...
}
})
}