Theo's Typesafe CultTTC
Theo's Typesafe Cult4y ago
3 replies
plyglt

Optimistic Updates with TRPC (react-query)?

I am not sure how I would do optimistic updates with trpc? Is this "built-in" or do I have to use react-query's useQuery hook?

So far, I am trying it like so, but it's not working:

 const queryClient = useQueryClient();

    const updateWord = trpc.word.update.useMutation({
        onMutate: async newTodo => {
            // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
            await queryClient.cancelQueries({ queryKey: ['text', 'getOne'] })

            // Snapshot the previous value
            const previousText = queryClient.getQueryData(['text', 'getOne'])

            // Optimistically update to the new value
            queryClient.setQueryData(['text', 'getOne'], old => old ? {...old, { title: "Hello" }} : undefined)

            // Return a context object with the snapshotted value
            return { previousText }
        },
//...


Does this look like it should make sense? It's updating the value, but not optimistically.
Was this page helpful?