且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-25 13:25:56

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

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 })