Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refetching queris with Apollo React hooks

I'm trying out the new Apollo React Hooks and I set up a small commerce example.

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 )

Everything works as expected, removing/adding an item correctly refreshes the list of items, but after any mutation executes the loading status of the query is never true (the result is that I don't see the Loading... message in the UI).

Isn't the loading and error variables suppose to update when the query is re-fetched?

like image 334
Daniel Platon Avatar asked Dec 18 '22 16:12

Daniel Platon


1 Answers

refetchQueries will not cause a watched query's loading property to change -- it just asynchronously resolves the listed queries and updates the cache with the results.

useMutation also exposes a loading property. I believe you can achieve the effect you're looking for by setting awaitRefetchQueries to 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

The other approach would be to simply call the query's refetch method directly instead.

like image 176
Daniel Rearden Avatar answered Jan 14 '23 03:01

Daniel Rearden