Is There A Better Way To Communicate With A TRPC Endpoint When You Don't Want To Re-render?
Hello,
I was wondering if there is a better way to send and receive data than
useQuery()
/ useMutate()
if you do not want to re-render at all and what you are doing is purely for internal data stuff.
I could still just use useMutate()
, and then have a effect that is subscribed to its value and then update state but than seems like alot of hoops to jump through.
Thanks in advance for the help!15 Replies
iirc it's possible to use
.mutate()
without a rerender
but honestly you probably want some visual confirmation in the ui that your mutation was successful
rerendering when you send data isn't really a performance concern for the vast majority of apps imoYeah, generally that would work but its just a little weird for what I need to do.
Essentially I need to
Take some form data -> Mutate -> add result to array that is in useState
so it would be alot better if I could just
but instead as far as I can tell I need to
Which seems oddyou should probably do this in the mutation's onSuccess handler
but also what kind of state are you updating?
if it's state that you got from a tRPC query, just invalidate that query
It starts as a empty array of interfaces, and then gets a new record added for each form submission
So no useQuery used
so it disappears when the component unmounts?
Yes
sure, i guess in that case just do
onSuccess: () => setThing(thing => thing.concat(newThing))
or something like thatI though I remember there being some way to do something like
const res = await useMutationAsync()
. Any idea if that's an option instead of callback?there is no useMutate
only useMutation
both useMutation and useMutationAsync don't actually mutate untill you run the mutate function
Sorry, that's what I meant
this is good, otherwise they would mutate as soon as the component renders
Ok, think I found what I am looking for here: https://tanstack.com/query/v4/docs/react/guides/mutations#promises
Mutations | TanStack Query Docs
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook.
Here's an example of a mutation that adds a new todo to the server:
Thanks for the help @cje!
yes that will work 🙂
i don't think you're really avoiding rerenders though
but if that wasn't the main point then this is a good solution
Yeah, I would have preferred if no re-render was needed, but functionally this solves 90% of the problem I was running into and avoids any sort of callback/useEffect hell.