bob-collective / ui

BOB is a hybrid L2 that combines the security of Bitcoin with the versatility of Ethereum
0 stars 0 forks source link

Improve error/success callback handling with react query #307

Open slavastartsev opened 1 day ago

slavastartsev commented 1 day ago

Description

Ideal case of handling errorMessage | onError | onSuccess callback is passing them through meta property

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => {
      if (query.meta.errorMessage) {
        toast.error(query.meta.errorMessage)
      }
    },
  }),
})

export function useTodos() {
  return useQuery({
    queryKey: ['todos', 'list'],
    queryFn: fetchTodos,
    meta: {
      errorMessage: 'Failed to fetch todos',
    },
  })
}

In order to support typedefs we need to override Register interface from @tanstack/react-query | @gobob/react-query

import '@gobob/react-query';
import { DefaultError, Query } from '@gobob/react-query';

// https://tanstack.com/query/latest/docs/framework/react/typescript#typing-meta
interface CustomQueryMeta extends Record<string, unknown> {
  onSuccess?: ((data: unknown, query: Query<unknown, unknown, unknown>) => void) | undefined;
  onError?: ((error: DefaultError, query: Query<unknown, unknown, unknown>) => void) | undefined;
  onSettled?:
    | ((data: unknown | undefined, error: DefaultError | null, query: Query<unknown, unknown, unknown>) => void)
    | undefined;
}

declare module '@gobob/react-query' {
  interface Register extends Record<string, unknown> {
    queryMeta: CustomQueryMeta;
  }
}

More details in tanstack docs https://tanstack.com/query/latest/docs/framework/react/typescript#typing-meta

Having that setup we can remove useEffect hooks in favour of using onSuccess, onError, onSettled callbacks