【问题标题】:Refetching queris with Apollo React hooks使用 Apollo React 钩子重新获取查询
【发布时间】:2019-12-20 23:22:04
【问题描述】:

我正在试用新的 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 )

一切都按预期工作,删除/添加项目会正确刷新项目列表,但在执行任何突变后,loading 查询的状态永远不会为真(结果是我看不到Loading... UI 中的消息)。

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

【问题讨论】:

    标签: apollo react-hooks


    【解决方案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 方法。

    【讨论】:

    • 您好,谢谢您的回答。它在没有设置awaitRefetchQueries的情况下工作。
    • @DanielPlaton 您还可以在不从服务器重新获取查询的情况下更新 apollo 缓存。我写了一个小的 npm 包 - apollo-offline-hooks,它简化了缓存更新。你只需要const [removeItem, {loading: removeLoading}] = useMutation(REMOVE_ITEM, { updateQuery: {query: CART_DETAILS, variables: {cartId}} });
    • 这种方法在一个屏幕上对我有效,但在另一个屏幕上无效。你能看看这里吗? stackoverflow.com/questions/62677019/…
    猜你喜欢
    • 2019-05-10
    • 2021-06-14
    • 2019-12-13
    • 2019-08-15
    • 2021-04-29
    • 2018-05-04
    • 2021-01-27
    • 2018-12-31
    • 2018-10-30
    相关资源
    最近更新 更多