Skip to content


This package exposes a set of handy bindings to browser APIs.


npm i @reatom/web


The onEvent function enables you to respond to various types of events for the target element that supports the addEventListener interface, such as HTMLInputElement or WebSocket, among others.

You can pass a callback as the last argument. In this case, the method will return an unsubscribe function. If you skip the callback, the returned value will be a promise that will resolve with the event.

Please note that this API handles the abort context from the onConnect effect and other Reatom APIs. It enables you to describe complex logic in a concise and clear manner with memory safety underneath.

onEvent WebSocket example

Here is a usage example, which was revrited from this observable example:

import { atom, onConnect, onCtxAbort } from '@reatom/framework'
import { onEvent } from '@reatom/web'

const socket = new WebSocket('wss://')

const reatomStock = (ticker) => {
  const stockAtom = atom(null, `${ticker}StockAtom`)
  onConnect(stockAtom, async (ctx) => {
    if (socket.readyState !== WebSocket.OPEN) {
      await onEvent(ctx, socket, 'open')
    socket.send(JSON.stringify({ ticker, type: 'sub' }))
    onEvent(ctx, socket, 'message', (event) => {
      if ( === ticker) stockAtom(ctx, JSON.parse(
    onEvent(ctx, socket, 'close', () => ctx.controller.abort())
    onEvent(ctx, socket, 'error', () => ctx.controller.abort())
    onCtxAbort(ctx, () =>
      socket.send(JSON.stringify({ ticker, type: 'unsub' })),

  return stockAtom

const googStockAtom = reatomStock('GOOG')

ctx.subscribe(googStockAtom, updateView)