Properly call trpc from state (Mobx, Zustand etc.)

I'm currently struggling to find the proper way to use trpc, to make an api call from a state management library such as MobX. I'm fully aware of react-query, but because of the complexity of my use-case I decided to use MobX for some routes. Because of the 'useQuery' function, I came up with this (ugly) code snippet: async getData() { const userRes = (await api.users.getMe.useQuery(undefined, { enabled: false }).refetch()) if (userRes.error) { throw userRes.error } else if (!userRes.data) { throw new Error('No data found.') } else if (userRes.status !== 'success') { throw new Error('Status not success.') } const data = userRes.data this.patchUser({ ...data, isAuthenticated: true, }); return data; This seems like a very hacky solution, but the best I could come up with, would be wrapping each api call in a hof, which implements this logic to call the api. Is there a better way?
2 Replies
cje
cje2y ago
if you're mainly just trying to avoid dealing with hook rules, look at the vanilla client https://trpc.io/docs/vanilla
Vanilla client | tRPC
The magic of tRPC is making strongly typed API calls without relying on code generation. With full-stack TypeScript projects, you can directly import types from the server into the client! This is a vital part of how tRPC works.
jonnyfapson
jonnyfapsonOP2y ago
Thanks a lot! This is exactly what I was looking for
Want results from more Discord servers?
Add your server