zereight / simple-react-query

Is react-query heavy? Use simple react-query!
12 stars 0 forks source link

Simple React Query โญ๏ธ


A Light Weight Data Fetching Library


Features


Backgrounds

1. react-query is heavy

2. Too many methods, but I need only some

3. When bugs occurred, debugging is hell

4. Interface of useMutation is different from that of useQuery

5. useQuery data type must include "undefined"

6. Difficult to cancel refreshInterval setting

7. react-query caching is a default


Usage

Install

yarn add simple-react-query

QueryClient

QueryClient has queryCache.

import { QueryClient, QueryClientProvider } from "simple-react-query";

<QueryClientProvider value={QueryClient}>
  <App />
</QueryClientProvider>;

useQuery

const {
  refetch,
  isLoading,
  isError,
  data,
  error,
  setData,
  isSuccess,
  clearRefetchInterval,
  isFetched
} = useQuery<TypeOfResponseData>({
  enabled: true,
  query: () => fetch(...),
  initialData: {},
  onSuccess: () => console.log("fetch success!"),
  refetchInterval: 5000,
  isEqualToPrevDataFunc: (a,b) => a.id === b.id,
  cacheTime: 5000,
  queryKeys: ["User", "id"]
});

Props

  1. enabled: auto fetch, when useQuery called
  2. query: fetch function
  3. onSuccess (optional): action after query fetched successfully
  4. initialData (optional): set initial data
  5. refetchInterval (optional): refetch interval (ms)(background ok)
  6. isEqualToPrevDataFunc (optional): when newData fetched, isEqualToPrevDataFunc called with (newData, prevData), if false update newData, true don't update newData because it is same.
  7. cacheTime (optional): caching time useQuery's return data. (ms) default is 0.
  8. queryKeys (optional): caching is decided by queryKeys. It must be array.

Returns

  1. refetch: refetch query
  2. isLoading: fetch is not complete
  3. isError: fetch has error
  4. data: fetch's return data (or cached data)
  5. error: error object
  6. setData: update data state
  7. isSuccess: fetch is complete successfully
  8. clearRefetchInterval: clear interval refetch
  9. isFetched: query is fetched more then 1 time

useMutation

const { isLoading, isError, error, data, mutation } = useMutation<
  TypeRequestData,
  TypeResponseData
>({
  query: (_data: TypeRequestData) => fetch(_data),
  onSuccess: () => {
    console.log("mutation successfully");
  }
});

Props

  1. query: mutation fetch function
  2. onSuccess (optional): action after query fetched successfully

Returns

  1. isLoading: fetch is not complete
  2. isError: fetch has error
  3. data: fetch's return data
  4. error: error object
  5. mutation: wrapped async fetch function, use this function instead fetch


Has Better Idea?