@ozymandiasthegreat/use-fetch
v0.1.0
Published
react-native hook that integrates MMKV and supafetch for optional persistent caching, dynamic rate limiting, and automatic retries with exponential backoff.
Maintainers
Readme
use-fetch
A simple react-native hook that integrates MMKV and supafetch for optional persistent caching, dynamic rate limiting, and automatic retries with exponential backoff.
Install
npm i @ozymandiasthegreat/use-fetchUsage
import useFetch from "@ozymandiasthegreat/use-fetch"
export default function Component() {
const [response, loading, error] = useFetch<ResponseShape>(uri, null, {
cache: { duration: "5m" },
limits: { requests: 1, duration: "1s" },
retry: { attempts: 3, delay: "100ms", status: [429, 429] },
})
return (...)
}
This will return last successful response for the next 5 minutes if the last request was successful, limits requests to 1 per second, and retries up to 3 times when response status code is 429 with base delay of 100 milliseconds.
Rate limits are applied per hostname and cache is global as long as options.cache.provider supplied is the same.
API
const [response, loading, error] = useFetch<T>(uri, init, options)
response is JSON decoded response body, or string version of it if the decoding fails. It's type is T | null where <T> is the generic supplied to the hook.
loading is true if the hook is attempting to download data.
error is SupafetchError, a custom error wrapper that provides statusText as error.message and status as error.code. If the error is not an HTTP error, error.code is -1 and error.cause is set to the underlying error, e.g. a network error.
uri
A string address or URL instance. Any object with a toString() method can be passed in.
If you don't know the uri at initial render, pass null. In this case the hook is a noop.
init
The same RequestInit that fetch(...) takes, with the exception that signal is not accepted, as that is used internally. Use it to provide headers or cookies.
options
Options are forwarded to the underlying supafetch library with the addition of CacheProvider set to custom MMKV based implementation by default. See supafetch options for more details.
License
Apache-2.0
