Skip to content

Package @reatom/web

@reatom/web

Interfaces

FetchRequestInit<Result, Params>

Defined in: packages/core/src/web/fetch.ts:5

Extends

  • RequestInit

Type Parameters

Result

Result = unknown

Params

Params extends any[] = any[]

Properties

body?

optional body: null | BodyInit

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2041

A BodyInit object or null to set request’s body.

Inherited from

RequestInit.body

cache?

optional cache: RequestCache

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2043

A string indicating how the request will interact with the browser’s cache to set request’s cache.

Inherited from

RequestInit.cache

credentials?

optional credentials: RequestCredentials

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2045

A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request’s credentials.

Inherited from

RequestInit.credentials

getInit()?

optional getInit: (…params) => object

Defined in: packages/core/src/web/fetch.ts:12

Parameters
params

Params

Returns

object

body?

optional body: any[] | Record<string, any> | BodyInit

searchParams?

optional searchParams: string | URLSearchParams | Record<string, string> | string[][]

getResult()?

optional getResult: (response) => Result | Promise<Result>

Defined in: packages/core/src/web/fetch.ts:16

Parameters
response

Response

Returns

Result | Promise<Result>

headers?

optional headers: HeadersInit

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2047

A Headers object, an object literal, or an array of two-item arrays to set request’s headers.

Inherited from

RequestInit.headers

integrity?

optional integrity: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2049

A cryptographic hash of the resource to be fetched by request. Sets request’s integrity.

Inherited from

RequestInit.integrity

keepalive?

optional keepalive: boolean

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2051

A boolean to set request’s keepalive.

Inherited from

RequestInit.keepalive

method?

optional method: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2053

A string to set request’s method.

Inherited from

RequestInit.method

mode?

optional mode: RequestMode

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2055

A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request’s mode.

Inherited from

RequestInit.mode

origin?

optional origin: string

Defined in: packages/core/src/web/fetch.ts:10

priority?

optional priority: RequestPriority

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2056

Inherited from

RequestInit.priority

redirect?

optional redirect: RequestRedirect

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2058

A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request’s redirect.

Inherited from

RequestInit.redirect

referrer?

optional referrer: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2060

A string whose value is a same-origin URL, “about:client”, or the empty string, to set request’s referrer.

Inherited from

RequestInit.referrer

referrerPolicy?

optional referrerPolicy: ReferrerPolicy

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2062

A referrer policy to set request’s referrerPolicy.

Inherited from

RequestInit.referrerPolicy

signal?

optional signal: null | AbortSignal

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2064

An AbortSignal to set request’s signal.

Inherited from

RequestInit.signal

transport()?

optional transport: {(input, init?): Promise<Response>; (input, init?): Promise<Response>; }

Defined in: packages/core/src/web/fetch.ts:11

Call Signature

(input, init?): Promise<Response>

MDN Reference

Parameters
input

URL | RequestInfo

init?

RequestInit

Returns

Promise<Response>

Call Signature

(input, init?): Promise<Response>

MDN Reference

Parameters
input

string | URL | Request

init?

RequestInit

Returns

Promise<Response>

url?

optional url: string | URL

Defined in: packages/core/src/web/fetch.ts:9

window?

optional window: null

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.dom.d.ts:2066

Can only be null. Used to disassociate request from any Window.

Inherited from

RequestInit.window


UrlAtom()

Defined in: packages/core/src/web/url.ts:19

URL atom interface that extends the base Atom type.

Extends

UrlAtom(…params): URL

Defined in: packages/core/src/web/url.ts:19

URL atom interface that extends the base Atom type.

Parameters

params

…[]

Parameters to pass to the atom

Returns

URL

The atom’s payload (typically its current state)

Properties

__reatom

__reatom: AtomMeta

Defined in: packages/core/src/core/atom.ts:106

Reference to the atom’s internal metadata.

Inherited from

Atom.__reatom

actions

actions: Actions<UrlAtom>

Defined in: packages/core/src/core/atom.ts:86

Bind methods to the atom to extend its functionality.

Deprecated

Use extend instead

Inherited from

Atom.actions

catchLinks: Atom<boolean>

Defined in: packages/core/src/web/url.ts:57

Whether to intercept link clicks for SPA navigation.

Default
true
extend

extend: Extend<UrlAtom>

Defined in: packages/core/src/core/atom.ts:92

Extension system to add capabilities to atoms. Allows adding middleware, methods, or other functionality to modify atom behavior.

Inherited from

Atom.extend

go()

go: (path, replace?) => URL

Defined in: packages/core/src/web/url.ts:42

Navigate to a new path.

Parameters
path

string

The path to navigate to

replace?

boolean

Whether to replace the current history entry

Returns

URL

init

init: Action<[], URL> & AbortExt

Defined in: packages/core/src/web/url.ts:65

This initialize DOM subscriptions and returns the current URL. To prevent this action calling (in server on other environments without DOM), just call urlAtom with your custom URL before it will be reded in other places.

match()

match: (path) => Computed<boolean>

Defined in: packages/core/src/web/url.ts:50

Create a computed atom that checks if the current path matches a given pattern.

Parameters
path

string

The path pattern to match against

Returns

Computed<boolean>

routes

routes: Rec<RouteAtom>

Defined in: packages/core/src/web/url.ts:82

subscribe()

subscribe: (cb?) => Unsubscribe

Defined in: packages/core/src/core/atom.ts:103

Subscribe to state changes, with the first call happening immediately. When a subscriber is added, the callback is immediately invoked with the current state. After that, it’s called whenever the atom’s state changes.

Parameters
cb?

(state) => any

Callback function that receives the atom’s state when it changes

Returns

Unsubscribe

An unsubscribe function that removes the subscription when called

Inherited from

Atom.subscribe

sync

sync: Atom<(url, replace?) => void>

Defined in: packages/core/src/web/url.ts:71

Synchronization callback to push URL state updates to the history. Replace with noop to disable syncing.

syncFromSource

syncFromSource: Action<[URL, boolean], URL>

Defined in: packages/core/src/web/url.ts:80

For integrations use: put the new URL from the the source of truth to urlAtom, without syncing it back (calling callback in sync Atom).

Param

The URL from the source

Param

Whether to replace the current history entry

Methods

set()
Call Signature

set(url, replace?): URL

Defined in: packages/core/src/web/url.ts:26

Update the URL atom with a new URL.

Parameters
url

URL

New URL to set

replace?

boolean

Whether to replace the current history entry

Returns

URL

Overrides

Atom.set

Call Signature

set(update, replace?): URL

Defined in: packages/core/src/web/url.ts:34

Update the URL with a function that receives the current URL.

Parameters
update

(url) => URL

Function that takes current URL and returns new URL

replace?

boolean

Whether to replace the current history entry

Returns

URL

Overrides

Atom.set


WebSocketAtom()<T>

Defined in: packages/core/src/web/reatomWebSocket.ts:16

Base changeable state container.

Atom is the core primitive for storing and updating mutable state in Reatom. It can be called to retrieve its current state or update it with a new value or update function.

Extends

Type Parameters

T

T = any

The type of state stored in the atom

WebSocketAtom(…params): WebSocketMessage<T>[]

Defined in: packages/core/src/web/reatomWebSocket.ts:16

Base changeable state container.

Atom is the core primitive for storing and updating mutable state in Reatom. It can be called to retrieve its current state or update it with a new value or update function.

Parameters

params

…[]

Parameters to pass to the atom

Returns

WebSocketMessage<T>[]

The atom’s payload (typically its current state)

Properties

__reatom

__reatom: AtomMeta

Defined in: packages/core/src/core/atom.ts:106

Reference to the atom’s internal metadata.

Inherited from

Atom.__reatom

actions

actions: Actions<WebSocketAtom<T>>

Defined in: packages/core/src/core/atom.ts:86

Bind methods to the atom to extend its functionality.

Deprecated

Use extend instead

Inherited from

Atom.actions

autoReconnect

autoReconnect: Atom<boolean>

Defined in: packages/core/src/web/reatomWebSocket.ts:27

Auto-reconnect enabled

clearError

clearError: Action<[], void>

Defined in: packages/core/src/web/reatomWebSocket.ts:54

Clear errors

clearMessages

clearMessages: Action<[], void>

Defined in: packages/core/src/web/reatomWebSocket.ts:52

Clear message history

closedAt

closedAt: Atom<null | number>

Defined in: packages/core/src/web/reatomWebSocket.ts:35

Connection closed timestamp

connect

connect: Action<[], Promise<void>>

Defined in: packages/core/src/web/reatomWebSocket.ts:44

Connect to WebSocket

connectedAt

connectedAt: Atom<null | number>

Defined in: packages/core/src/web/reatomWebSocket.ts:33

Connection established timestamp

disconnect

disconnect: Action<[number, string], void>

Defined in: packages/core/src/web/reatomWebSocket.ts:46

Disconnect from WebSocket

error

error: Atom<null | Error>

Defined in: packages/core/src/web/reatomWebSocket.ts:31

Last error

extend

extend: Extend<WebSocketAtom<T>>

Defined in: packages/core/src/core/atom.ts:92

Extension system to add capabilities to atoms. Allows adding middleware, methods, or other functionality to modify atom behavior.

Inherited from

Atom.extend

isConnected

isConnected: Atom<boolean>

Defined in: packages/core/src/web/reatomWebSocket.ts:37

Whether currently connected

isConnecting

isConnecting: Atom<boolean>

Defined in: packages/core/src/web/reatomWebSocket.ts:39

Whether currently connecting

latestMessage

latestMessage: Atom<null | WebSocketMessage<T>>

Defined in: packages/core/src/web/reatomWebSocket.ts:41

Latest message

protocols

protocols: Atom<string[]>

Defined in: packages/core/src/web/reatomWebSocket.ts:25

Connection protocols

readyState

readyState: Atom<WebSocketReadyState>

Defined in: packages/core/src/web/reatomWebSocket.ts:19

Current connection state

reconnect

reconnect: Action<[], Promise<void>>

Defined in: packages/core/src/web/reatomWebSocket.ts:56

Force reconnect

reconnectAttempts

reconnectAttempts: Atom<number>

Defined in: packages/core/src/web/reatomWebSocket.ts:29

Reconnect attempts count

send

send: Action<[string | Blob | ArrayBuffer | ArrayBufferView<ArrayBufferLike>], void>

Defined in: packages/core/src/web/reatomWebSocket.ts:48

Send message

sendJson

sendJson: Action<[any], void>

Defined in: packages/core/src/web/reatomWebSocket.ts:50

Send JSON message

socket

socket: Atom<null | WebSocket>

Defined in: packages/core/src/web/reatomWebSocket.ts:21

Current WebSocket instance (null if not connected)

subscribe()

subscribe: (cb?) => Unsubscribe

Defined in: packages/core/src/core/atom.ts:103

Subscribe to state changes, with the first call happening immediately. When a subscriber is added, the callback is immediately invoked with the current state. After that, it’s called whenever the atom’s state changes.

Parameters
cb?

(state) => any

Callback function that receives the atom’s state when it changes

Returns

Unsubscribe

An unsubscribe function that removes the subscription when called

Inherited from

Atom.subscribe

url

url: Atom<string>

Defined in: packages/core/src/web/reatomWebSocket.ts:23

Connection URL

Methods

set()
Call Signature

set(update): WebSocketMessage<T>[]

Defined in: packages/core/src/core/atom.ts:127

Update the atom’s state using a function that receives the previous state

Parameters
update

(state) => WebSocketMessage<T>[]

Function that takes the current state and returns a new state

Returns

WebSocketMessage<T>[]

The new state value

Inherited from

Atom.set

Call Signature

set(…params): WebSocketMessage<T>[]

Defined in: packages/core/src/core/atom.ts:135

Set the atom’s state to a new value

Parameters
params

…[WebSocketMessage<T>[]]

Returns

WebSocketMessage<T>[]

The new state value

Inherited from

Atom.set


WebSocketMessage<T>

Defined in: packages/core/src/web/reatomWebSocket.ts:10

Type Parameters

T

T = any

Properties

data

data: T

Defined in: packages/core/src/web/reatomWebSocket.ts:11

timestamp

timestamp: number

Defined in: packages/core/src/web/reatomWebSocket.ts:12

type

type: "message" | "error"

Defined in: packages/core/src/web/reatomWebSocket.ts:13


WebSocketOptions

Defined in: packages/core/src/web/reatomWebSocket.ts:59

Properties

autoReconnect?

optional autoReconnect: boolean

Defined in: packages/core/src/web/reatomWebSocket.ts:65

Auto-reconnect on connection loss

maxMessages?

optional maxMessages: number

Defined in: packages/core/src/web/reatomWebSocket.ts:71

Maximum number of messages to keep in history

maxReconnectAttempts?

optional maxReconnectAttempts: number

Defined in: packages/core/src/web/reatomWebSocket.ts:69

Maximum reconnect attempts (0 for infinite)

messageParser()?

optional messageParser: (data) => any

Defined in: packages/core/src/web/reatomWebSocket.ts:73

Message parser function

Parameters
data

any

Returns

any

name?

optional name: string

Defined in: packages/core/src/web/reatomWebSocket.ts:75

Debug name for the WebSocket instance

protocols?

optional protocols: string[]

Defined in: packages/core/src/web/reatomWebSocket.ts:63

WebSocket protocols

reconnectDelay?

optional reconnectDelay: number

Defined in: packages/core/src/web/reatomWebSocket.ts:67

Reconnect delay in milliseconds

url

url: string

Defined in: packages/core/src/web/reatomWebSocket.ts:61

WebSocket URL

Type Aliases

EventOfTarget<Target, Type>

EventOfTarget<Target, Type> = Target extends Record<`on${Type}`, infer Cb> ? Parameters<Cb>[0] : Target extends Record<"onEvent", (type, cb) => any> ? Parameters<Cb>[0] : never

Defined in: packages/core/src/web/onEvent.ts:5

Type Parameters

Target

Target extends EventTarget

Type

Type extends string


UrlSearchParamsInit

UrlSearchParamsInit = ConstructorParameters<typeof URLSearchParams>[0]

Defined in: packages/core/src/web/fetch.ts:1


WebSocketReadyState

WebSocketReadyState = "CONNECTING" | "OPEN" | "CLOSING" | "CLOSED"

Defined in: packages/core/src/web/reatomWebSocket.ts:8

Variables

FetchRequest

FetchRequest: typeof FetchRequest

Defined in: packages/core/src/web/fetch.ts:19


onEvent()

const onEvent: {<Target, Type>(target, type): Promise<EventOfTarget<Target, Type>>; <Event>(target, type): Promise<Event>; <Target, Type>(target, type, cb, options?): Unsubscribe; <Event>(target, type, cb, options?): Unsubscribe; }

Defined in: packages/core/src/web/onEvent.ts:77

Integrates external event sources (DOM elements, WebSockets, etc.) with Reatom’s reactive system and abort context.

Can be used in two ways:

  1. As a Promise (without callback): Returns a promise that resolves when the event fires once. Use with await wrap(onEvent(...)) in actions to wait for events while respecting abort contexts.
  2. As a Subscription (with callback): Registers a callback that fires on each event occurrence. Returns an unsubscribe function for cleanup.

When used within an action with abort context, onEvent automatically cleans up listeners when the action is aborted or when a component unmounts, preventing memory leaks and stale event handlers.

Call Signature

<Target, Type>(target, type): Promise<EventOfTarget<Target, Type>>

Type Parameters
Target

Target extends EventTarget

Type

Type extends string

Parameters
target

Target

type

Type

Returns

Promise<EventOfTarget<Target, Type>>

Call Signature

<Event>(target, type): Promise<Event>

Type Parameters
Event

Event

Parameters
target

EventTarget

type

string

Returns

Promise<Event>

Call Signature

<Target, Type>(target, type, cb, options?): Unsubscribe

Type Parameters
Target

Target extends EventTarget

Type

Type extends string

Parameters
target

Target

type

Type

cb

(value) => any

options?

AddEventListenerOptions

Returns

Unsubscribe

Call Signature

<Event>(target, type, cb, options?): Unsubscribe

Type Parameters
Event

Event

Parameters
target

EventTarget

type

string

cb

(value) => any

options?

AddEventListenerOptions

Returns

Unsubscribe

Examples

import { action, onEvent, wrap } from '@reatom/core'
const handleUserAction = action(async () => {
const button = document.getElementById('confirmButton')
const clickEvent = await wrap(onEvent(button, 'click'))
console.log(clickEvent.clientX, clickEvent.clientY)
processUserConfirmation()
}, 'handleUserAction').extend(withAbort())
import { atom, effect, onEvent } from '@reatom/core'
const activeVideoAtom = atom(null, 'activeVideo')
const videoStatsAtom = atom({ plays: 0, pauses: 0 }, 'videoStats')
effect(() => {
const videoElement = activeVideoAtom()
if (!videoElement) return
// the listener will be cleared automatically, when the new videoElement is set
onEvent(videoElement, 'play', () => {
videoStatsAtom.set((stats) => ({ ...stats, plays: stats.plays + 1 }))
})
onEvent(videoElement, 'pause', () => {
videoStatsAtom.set((stats) => ({
...stats,
pauses: stats.pauses + 1,
}))
})
})

Param

The event target (DOM element, WebSocket, etc.)

Param

The event type to listen for (e.g., ‘click’, ‘message’)

Param

Optional callback function. If omitted, returns a Promise

Param

Optional event listener options (capture, passive, etc.)

Returns

A Promise resolving to the event (if no callback), or an unsubscribe function (if callback provided)

Note

Uses abortVar.subscribe() internally to connect the event listener lifecycle to Reatom’s abort context. The listener is automatically removed when the associated AbortController signals abortion, which happens when the parent action is aborted, a component unmounts, or when withAbort() cancels a previous execution (effect do it automatically).


onLineAtom

onLineAtom: OnlineAtom

Defined in: packages/core/src/web/onLineAtom.ts:48

An atom that tracks the browser’s online/offline connectivity status.

Returns true when the browser has network connectivity, false when offline. Automatically updates by listening to the browser’s online and offline events.

Provides additional timestamp tracking:

  • onlineAtAtom: Timestamp (from Date.now()) when the connection was established
  • offlineAtAtom: Timestamp (from Date.now()) when the connection was lost

Example

import { effect, onLineAtom } from '@reatom/core'
effect(() => {
const isOnline = onLineAtom()
const lastOnlineAt = onLineAtom.onlineAtAtom()
const lastOfflineAt = onLineAtom.offlineAtAtom()
if (isOnline) {
if (lastOnlineAt) {
syncPendingChanges()
}
} else {
showOfflineBanner()
queueChangesForLater()
}
})

Note

Due to a Chromium bug (https://issues.chromium.org/issues/338514113), the initial state may not always reflect the actual connectivity status. The atom will correct itself once the first online/offline event fires.


rAF

rAF: Atom<{ delta: number; timestamp: number; }, [object]>

Defined in: packages/core/src/web/rAF.ts:37

An atom that synchronizes with the browser’s animation frame timing.

Provides frame-by-frame timing information including:

  • timestamp: Current high-resolution timestamp from performance.now()
  • delta: Time elapsed since the previous frame in milliseconds

The atom updates automatically on every animation frame using requestAnimationFrame, making it ideal for smooth animations, performance monitoring, and frame-based updates.

Example

import { atom, effect, rAF } from '@reatom/core'
const particlePosition = atom(
{ x: 0, y: 0, velocityX: 2, velocityY: 1.5 },
'particlePosition',
)
effect(() => {
const { delta } = rAF()
const deltaSeconds = delta / 1000
particlePosition.set((state) => ({
x: state.x + state.velocityX * deltaSeconds * 60,
y: state.y + state.velocityY * deltaSeconds * 60,
velocityX:
state.x > 800 || state.x < 0 ? -state.velocityX : state.velocityX,
velocityY:
state.y > 600 || state.y < 0 ? -state.velocityY : state.velocityY,
}))
})

urlAtom

urlAtom: UrlAtom

Defined in: packages/core/src/web/url.ts:87

Create the URL atom with the new Reatom API.

Functions

reatomMediaQuery()

reatomMediaQuery(query): Computed<boolean>

Defined in: packages/core/src/web/reatomMediaQuery.ts:37

Creates a reactive atom that tracks a CSS media query state.

The atom automatically updates when the media query match state changes, providing a reactive way to respond to viewport changes, dark mode preferences, and other media features.

Parameters

query

string

A CSS media query string (e.g., ‘(min-width: 768px)’, ‘(prefers-color-scheme: dark)‘)

Returns

Computed<boolean>

An atom that holds the current match state as a boolean

Examples

const isMobile = reatomMediaQuery('(max-width: 767px)')
const isPrint = reatomMediaQuery('print')
const isDarkModeMedia = reatomMediaQuery('(prefers-color-scheme: dark)')
const themeAtom = reatomEnum(
['light', 'dark', 'system'],
'themeAtom',
).extend(
withComputed((state) => {
if (state === 'system') return isDarkModeMedia() ? 'dark' : 'light'
return state
}),
withLocalStorage(),
withChangeHook((state) => {
document.body.classList.toggle('dark', state)
}),
)

reatomWebSocket()

reatomWebSocket<T>(options): WebSocketAtom<T>

Defined in: packages/core/src/web/reatomWebSocket.ts:78

Type Parameters

T

T = any

Parameters

options

string | WebSocketOptions

Returns

WebSocketAtom<T>