#get loading state from useMutation

1 messages · Page 1 of 1 (latest)

lime raft
#

When I use useMutation with convex, do I get access to the loading state or do I need another useState that I need to manage by myself?

molten wedgeBOT
#

Hi @lime raft. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

When using Convex's useMutation hook in React, you do not automatically get a loading state as part of the return value from useMutation itself. The typical usage is:

import { useMutation } from "convex/react";
import { api } from "../convex/_generated/api";

function App() {
  const increment = useMutation(api.incrementCounter.default);
  // Your component here!
}

If you want to show a loading state while a mutation is in progress, you need to manage that state yourself, for example by using useState and updating it before and after calling the mutation:

const [isLoading, setIsLoading] = useState(false);

const handleClick = async () => {
  setIsLoading(true);
  try {
    await increment();
  } finally {
    setIsLoading(false);
  }
};

Alternatively, if you use Convex with TanStack Query, the useMutation hook from TanStack Query does provide an isPending property that you can use to track the loading state:

import { useMutation } from "@tanstack/react-query";
import { useConvexMutation } from "@convex-dev/react-query";
import { api } from "../convex/_generated/api";

export function App() {
  const { mutate, isPending } = useMutation({
    mutationFn: useConvexMutation(api.functions.doSomething),
  });
  return <button onClick={() => mutate({a: "Hello"})}>Click me</button>;
}

In this case, isPending will be true while the mutation is in progress, so you do not need to manage a separate loading state yourself when using TanStack Query integration with Convex Convex with TanStack Query: Mutations.

In summary:

#
  • With Convex's useMutation: manage loading state yourself.
  • With TanStack Query's useMutation: use the isPending property provided by the hook.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: