This is a clone library of React SWR ported for Jetpack Compose and Compose Multiplatform.
Supported platforms are Android, and experimentally Desktop (JVM) and iOS.
The API specification of React SWR
is followed as much as possible.
Options are also supported for the most part.
According to React SWR
, "SWR" refers to
The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.
Add the following gradle dependency exchanging *.*.*
for the latest release.
implementation("com.kazakago.swr.compose:swr:*.*.*")
As with React SWR
, implement the "fetcher function" and set it with the key to useSWR()
.
Using Kotlin's Destructuring declarations for return values can be written in the same way as in React SWR
.
private val fetcher: suspend (key: String) -> String = {
getNameApi.execute(key)
}
@Composable
fun Profile() {
val (data, error) = useSWR("/api/user", fetcher)
if (error != null) {
Text("failed to load")
} else if (data == null) {
Text("loading...")
} else {
Text("hello $data!")
}
}
Refer to the example module for details. This module works as an Compose Multiplatform app.
Feature name | Status | Note |
---|---|---|
Options | See below | |
Global Configuration | ✅ | |
Data Fetching | ✅ | |
Error Handling | ✅ | |
Auto Revalidation | ✅ | |
Conditional Data Fetching | ✅ | |
Arguments | ✅ | |
Mutation | ✅️ | |
Pagination | ✅ | |
Prefetching Data | ✅️ | Available by useSWRPreload() |
Suspense | ❌ | |
Middleware | ❌ |
The following options are supported for React SWR.
https://swr.vercel.app/docs/options
Option name | Status | Default value |
---|---|---|
suspense | ❌ | |
fetcher(args) | ✅ | |
revalidateIfStale | ✅ | true |
revalidateOnMount | ✅ | true if fallbackData is not set |
revalidateOnFocus | ✅ | true |
revalidateOnReconnect | ✅ | true |
refreshInterval | ✅ | 0.seconds (disable) |
refreshWhenHidden | ✅ | false |
refreshWhenOffline | ✅ | false |
shouldRetryOnError | ✅ | true |
dedupingInterval | ✅ | 2.seconds |
focusThrottleInterval | ✅ | 5.seconds |
loadingTimeout | ✅ | 3.seconds |
errorRetryInterval | ✅ | 5.seconds |
errorRetryCount | ✅ | |
fallback | ✅ | |
fallbackData | ✅ | |
keepPreviousData | ✅ | false |
onLoadingSlow(key, config) | ✅ | |
onSuccess(data, key, config) | ✅ | |
onError(err, key, config) | ✅ | |
onErrorRetry(err, key, config, revalidate, revalidateOps) | ✅ | Exponential backoff algorithm |
compare(a, b) | ❌ | |
isPaused() | ✅ | false |
use | ❌ |
Deduplication and Deep Comparison are supported, but Dependency Collection is not supported due to Kotlin's language specification.
Therefore, the number of re-rendering (re-compose) may be higher than in the original React SWR
.
However, it is possible to prevent performance degradation by limiting the number of arguments passed to child Composable functions (e.g., only data).