0.1.8 • Published 2 years ago

react-query-lite v0.1.8

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

React-query-lite

The tiny react data-loader inspired by react-query

npm i react-query-lite

Less impact on your client-size bundle

LibraryParsed sizeGzipped size
react-query40.77 kb9.96 kb
react-query-lite7.46 kb2.47 kb

The comparison is based on a simple setup with

import { QueryClient, QueryClientProvider, useQuery } from 'react-query-lite'

const client = new QueryClient()

const App = () => (
  <QueryClientProvider client={client}>
    <Page>
  </QueryClientProvider>
)

const Page = () => {
  const { data, error, isLoading } = useQuery('cache-key', async () => {
    const data = await getDataFromApi()
    return data
  })
  return (
    <div>
      {isLoading && 'isloading'}
      {error && error.message}
      {data && 'display data'}
    </div>
  )
}

Api

Query options (Object)

Used as third parameter to useQuery and as defaultOptions to QueryClient

  • keepPreviousData: Bool (default false) - keep previous data if key change in the useQuery hook
  • cacheTime: Int (default Infinity) - how long time before returning renders of components should fetch new data

QueryClient

new QueryClient({ cache, defaultOptions })

  • cache: Object (default {})
  • defaultOptions: Object (defaults to above Query options)
const client = new QueryClient({
  cache: {
    'my-key': {
      'data': 'Hello world'
    }
  },
  defaultOptions: {
    keepPreviousData: true,
    cacheTime: 60 * 60 * 1000 // 1 hour
  }
})

prefetchQuery(queryKey, fetchFn, options)

Use to prefetch data server-side

const data = await client.prefetchQuery(queryKey, fetchFn, options)
console.log(data)

getCache()

Get cache object from client that can be passed to client side QueryClient to avoid refetch

const cache = client.getCache()
console.log(cache)

useQuery(queryKey, fetchFn, options)

Use third option parameter to pass custom options for this query:

const {
  data,
  isLoading,
  error,
  status,
  refetch,
  fetchTime
} = await useQuery(queryKey, fetchFn, {
  keepPreviousData: true,
  cacheTime: 60 * 1000 // 1 minute
})

useMutation(fetchFn)

Use third option parameter to pass custom options for this query:

const {
  data,
  isLoading,
  error,
  mutateAsync
} = await useMutation(async ({ username, password }) => {
  const req = await fetch('/api/login', {
    method: 'post',
    body: body: JSON.stringify({ username, passord })
  })
  const json = await res.json()
  return json
})

Tradeoffs compared with react-query

  • queryKey as to be a string
0.1.8

2 years ago

0.1.7

2 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.4

2 years ago

0.1.3

2 years ago

0.1.6

2 years ago

0.1.5

2 years ago

0.1.0

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago