Add React Native + React Navigation compatibility to [`swr`](https://swr.vercel.app). 👨🏻🔧
Add React Native + React Navigation compatibility to swr. 👨🏻🔧
``diff`
- import useSWR from 'swr'
+ import useSWRNative from '@nandorojo/swr-react-native'
That's it.
SWR revalidation now works in your React Native app. Requests also revalidate when your React Navigation screens focus.
swr is an awesome data fetching + caching library by Vercel.
However, some of its essential features, such as revalidateOnFocus & revalidateOnConnect, don't work on React Native.
This library provides a simple drop-in replacement for useSWR, which adds compatibility for React Native / React Navigation.
It comes with 2 hooks: useSWRNative, and useSWRNativeRevalidate.
- Adds support for revalidateOnConnect & revalidateOnFocus.focusEventThrottle
- Configurable AppState
- Web, iOS and Android support
- Zero config
- Revalidates when becomes activefocus
- Works with React Navigation, revalidating on screen useSWRInfinite
- TypeScript support
- support
`sh`
yarn add @nandorojo/swr-react-native
Next, install peer dependencies:
`shif you're using expo
expo install @react-native-community/netinfo
$3
Currently, SWR v1 is in
beta:`sh
yarn add swr@beta
`To use
swr-react-native, you can install with @beta too:`sh
yarn add @nandorojo/swr-react-native@beta
`Usage
There are 2 ways to use this library:
$3
Replace imports of
useSWR with useSWRNative. That's it!`ts
import useSWRNative from '@nandorojo/swr-react-native'const { data, mutate, error } = useSWRNative(key, fetcher, config)
`$3
If, for some reason, you don't want to replace your imports, you can use the
useSWRNativeRevalidate hook. This allows you to de-couple the revalidation from the useSWR hook itself.This option exists in case
useSWR makes some big changes to their API or something down the line. Or, maybe you're using React Native web, and not all screens are nested in a React Navigation stack, so you want to call this only in those places.If you're using
useSWRInfinite, then this is the method for you.`ts
import { useSWRNativeRevalidate } from '@nandorojo/swr-react-native'
`Call
useSWRNativeRevalidate, likely below your useSWR function:`ts
const { data, mutate } = useSWR(key, fetcher)useSWRNativeRevalidate({
// required: pass your mutate function returned by SWR
mutate
// optional, defaults copied from SWR
revalidateOnFocus: true,
revalidateOnReconnect: true,
focusThrottleInterval: 5000,
})
`The
mutate function is required!If you're using
useSWRInfinite, this you should rely on this usage:`ts
const { data, mutate } = useSWRInfinite(...)useSWRNativeRevalidate({
// required: pass your mutate function returned by SWR
mutate
})
``I'm a big fan of SWR. I've also built a fetching library for Firebase/Firestore based on swr, which you can find here.
The idea for this library originated from this issue. Thanks to @te-online for help testing it.