ap0nia / trpc-svelte-toolbox

🔥 tRPC + svelte integrations
https://trpc-svelte-toolbox.vercel.app
9 stars 1 forks source link

Optimistic updates #2

Closed canastro closed 1 year ago

canastro commented 1 year ago

Hello, I've started using your trpc-svelte-query today and I got a bit confused with how to achieve optimistic updates. Do you have any example on how to use setData? I don't really understand what is the first parameter. I've tried a few different options but never got a query to be refreshed with the data that I pass in setData.

ap0nia commented 1 year ago

It looks like I had a typo with the function arguments to the setData helper. The arguments should be

  1. input to the query
  2. updater set the query data (either function or value)
  3. options for setQueryData

The input to the createQuery and the first argument to setData should be the same since it's used to calculate the query key. The latter two arguments are passed directly to the original setQueryData function: https://tanstack.com/query/v4/docs/react/reference/QueryClient#queryclientsetquerydata.

Here's an example I just added with a query that will be manually set after each successful mutation: https://github.com/ap0nia/trpc-svelte-toolbox/blob/main/examples/kitchen-sink/src/routes/createMutation/%2Bpage.svelte#L15

Per the official tanstack docs, you'd probably just add an utils.invalidate() somewhere to ensure that a fetch request is actually made to refresh the data: https://tanstack.com/query/v4/docs/react/guides/optimistic-updates

I posted a new version that should hopefully rectify the typings for the function call. Please let me know if this works for you!

canastro commented 1 year ago

Awesome, got it working! Thank you 👍🏽