Documentation

$fetch

Make HTTP requests with automatic JSON parsing and disk caching.

Basic Usage

The simplest form - just a URL:

val data = $fetch("https://api.example.com/data")

HTTP Methods

GET

val shows = $fetch.get(
  url = "https://api.example.com/shows",
  headers = mapOf("Authorization" to "Bearer $token"),
  params = mapOf("page" to "1", "limit" to "20")
)

POST

val response = $fetch.post(
  url = "https://api.example.com/login",
  body = mapOf("email" to email, "password" to password)
)

PUT

$fetch.put(
  url = "https://api.example.com/profile",
  body = mapOf("name" to name, "bio" to bio)
)

DELETE

$fetch.delete(
  url = "https://api.example.com/posts/$id",
  headers = mapOf("Authorization" to "Bearer $token")
)

Disk Caching

Cache responses to disk with TTL support:

// Cache for 1 day
val show = $fetch.get(
  url = "https://api.example.com/show/$id",
  cache = "1d"
)

// Cache forever (static data)
val countries = $fetch.get(
  url = "https://api.example.com/countries",
  cache = "forever"
)

Supported TTL Formats

  • "30s" - 30 seconds
  • "5m" - 5 minutes
  • "1h" - 1 hour
  • "1d" - 1 day
  • "7d" - 7 days
  • "forever" - Never expires

Clear Cache

$fetch.clearCache()

In a Screen Loader

Use $fetch in data loaders for automatic loading states:

// +screen.load.wh
suspend fun load(): Show {
  val id = $screen.params.id
  return $fetch("https://api.example.com/shows/$id")
}

// +screen.wh
<Column>
  <Text>{$data.name}</Text>
  <Text>{$data.description}</Text>
</Column>

Error Handling

Use try-catch for error handling:

var error: String? = null
var data: Show? = null

suspend fun loadData() {
  try {
    data = $fetch("https://api.example.com/show/$id")
  } catch (e: Exception) {
    error = e.message
  }
}

$onMount { loadData() }

@if (error != null) {
  <Text color="#ef4444">Error: {error}</Text>
} else if (data != null) {
  <Text>{data.name}</Text>
}

$fetch automatically parses JSON responses and handles serialization for request bodies.

Type Safety

Define data classes for type-safe responses:

data class Show(
  val id: String,
  val name: String,
  val description: String,
  val posterUrl: String
)

val show: Show = $fetch("https://api.example.com/shows/$id")

See Also