Llabe
Llabe•11mo ago

Loading state for mutations

Hey, I am using 'loading state' with useQuery in my nextjs app (when its undefined) and it works fine. Is there any way to do something similar with mutations? For example if I am creating an element, while the mutation (loading) I will show a spinner or smth
8 Replies
erquhart
erquhart•11mo ago
The mutation returns a promise, so you typically use that to set a state variable for loading.
const [isLoading, setIsLoading] = useState(false)
const mutation = useMutation(api.my.mutation)

const handleMutation = async () => {
setIsLoading(true)
await mutation()
setIsLoading(false)
}
const [isLoading, setIsLoading] = useState(false)
const mutation = useMutation(api.my.mutation)

const handleMutation = async () => {
setIsLoading(true)
await mutation()
setIsLoading(false)
}
Llabe
LlabeOP•11mo ago
Okey perfect, thanks And what do you think about combining it with a library like react query? which handles loading and error states? @erquhart
erquhart
erquhart•11mo ago
I know someone was doing that recently somewhere here, trying to find it In my opinion, though, because Convex handles your server state so well already, I'd personally make a thin hook around useMutation to just provide the loading/error state. I also like the react query API and generally have my convex functions return the same sort of object (data, error). Between those two you would probably have everything you need without introducing an entire additional caching layer (which is what react query is).
Llabe
LlabeOP•11mo ago
Yes, thats true, no reason to have another caching layer. So what you do is to create a wrapper custom hook that returns the loading and error state?
erquhart
erquhart•11mo ago
Yeah, it's simple enough to do Similar-ish conversation here: https://discord.com/channels/1019350475847499849/1214799510249939044/1214806468641947648
Llabe
LlabeOP•11mo ago
Okey, I'll give it a look now Thanks for the opinion I'll come back when I implement it 😄
erquhart
erquhart•11mo ago
There's a link to wrapper examples near the end of that other thread
erquhart
erquhart•11mo ago
GitHub
convex-helpers/packages/convex-helpers/react/sessions.ts at d0ad873...
A collection of useful code to complement the official packages. - get-convex/convex-helpers

Did you find this page helpful?