#loading state for mutation

3 messages · Page 1 of 1 (latest)

brittle delta
#

is there a nice way to get loading state for actions/mutations?

unique rampartBOT
#

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

#

Convex's React client does not provide a built-in loading state for mutations or actions directly via the useMutation hook. The typical pattern is to manage loading state manually in your component. For example, you can set a local state variable before and after calling the mutation:

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

export function MyComponent() {
  const [loading, setLoading] = useState(false);
  const doSomething = useMutation(api.functions.doSomething);

  const handleClick = async () => {
    setLoading(true);
    try {
      await doSomething();
    } finally {
      setLoading(false);
    }
  };

  return (
    <button onClick={handleClick} disabled={loading}>
      {loading ? "Loading..." : "Click me"}
    </button>
  );
}

This approach is shown in the Convex documentation, where you can use either async/await or .then/.catch to handle mutation responses and errors, and update your loading state accordingly Editing data.

For queries, the useQuery hook returns undefined while loading, which you can use to show loading indicators. For mutations and actions, manual state management is the recommended approach according to the current documentation.

If you are looking for more advanced or built-in loading state management for mutations/actions, the knowledge sources do not mention such a feature at this time.

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