使用Apollo React钩子刷新查询

时间:2019-08-14 11:46:19

标签: apollo react-hooks

我正在尝试新的Apollo React Hooks,并建立了一个小型商业示例。

^[

一切正常,删除/添加项目会正确刷新项目列表,但是在执行任何突变后,查询的function App() { const [cartId, setCartId] = useState('V1bvif5UxQThb84iukrxHx9dYQg9nr8j'); const [removeItem, {loading: mutationLoading}] = useMutation(REMOVE_ITEM, { refetchQueries: [{query: CART_DETAILS, variables: {cartId}}] }); const [addToCart] = useMutation(ADD_TO_CART, { refetchQueries: [{query: CART_DETAILS, variables: {cartId}}] }); const {data, loading, error} = useQuery(CART_DETAILS, { variables: {cartId} }); if (data && data.items) { console.log(`We have data`, data); } const handleRemove = itemId => { console.log(`Removing item with id ${itemId}`); removeItem({ variables: {cartId, itemId} }); }; if (error) { console.log(`Some error happened`, error); return <h2>ERROR!</h2>; } if (loading) { return <p>Loading...</p>; } return ( ... some HTML skipped for brevity ) 状态永远不会为真(结果是我看不到{ UI中的{1}}消息。

loadingLoading...变量不是应该在重新获取查询时更新吗?

1 个答案:

答案 0 :(得分:1)

refetchQueries不会导致监视的查询的loading属性发生变化-它只是异步解析列出的查询并使用结果更新缓存。

useMutation还公开了loading属性。我相信您可以通过将awaitRefetchQueries设置为true来达到所需的效果。

const [removeItem, {loading: removeLoading}] = useMutation(REMOVE_ITEM, {
  refetchQueries: [{query: CART_DETAILS, variables: {cartId}}],
  awaitRefetchQueries: true,
});
const [addToCart, {loading: addLoading}] = useMutation(ADD_TO_CART, {
  refetchQueries: [{query: CART_DETAILS, variables: {cartId}}],
  awaitRefetchQueries: true,
});
const loading = queryLoading || addLoading || removeLoading

另一种方法是直接直接调用查询的refetch方法。