React Nitro

Runtime and networking

Use the Hermes environment to fetch data and subscribe to a WebSocket.

Importing the renderer initializes the JavaScript environment used by the app. It includes console, performance.now(), timers, requestAnimationFrame, queueMicrotask, and a native fetch. The starter's TypeScript config describes that environment. Keep browser and Node types in a separate config if your project also contains build scripts.

Fetch a response

Pass a URL string to fetch and check ok before reading the body. The response exposes the HTTP status and final URL. Read a header with response.headers.get(name). Use text() for text, json() for JSON, or arrayBuffer() for binary data. If two consumers need the body, call response.clone() before either reads it.

export async function loadNoteText(url: string): Promise<string> {
  const response = await fetch(url)
  if (response.ok === false) {
    throw new Error(`Could not load note (HTTP ${response.status})`)
  }
  return response.text()
}

Pass the HTTP method, headers and body in the second argument. The method field accepts an uppercase method or a RequestMethod value from react-nitro-networking. If a redirect crosses origins, the runtime removes any caller-supplied Authorization header. Pass an AbortSignal in the signal field to cancel a request or a pending body read.

const body = JSON.stringify({ text: 'Hello' })
const response = await fetch(url, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: body,
})

Listen to a WebSocket

Use the WebSocket export from react-nitro-networking. Add the package as a direct app dependency at the same version as your renderer. For the published alpha used in the installation guide, run bun add --exact react-nitro-networking@0.0.1-alpha.16.

The constructor starts connecting. Register listeners when you create the socket and release them when the screen closes. This hook subscribes to a feed of plain-text messages.

import { useEffect, useState } from 'react'
import { WebSocket } from 'react-nitro-networking'

export function useLatestMessage(url: string) {
  const [message, setMessage] = useState('')
  useEffect(() => {
    const socket = new WebSocket(url)
    const messages = socket.addOnMessageReceivedListener((data) => {
      if (typeof data === 'string') setMessage(data)
    })
    const errors = socket.addOnErrorListener((error) => console.error(error))
    return () => {
      messages.remove()
      errors.remove()
      socket.close()
    }
  }, [url])
  return message
}

send() accepts a string or an ArrayBuffer. Await each send when message order matters. A resolved send means the transport accepted the message. If the sender needs to know that the other device processed it, include an acknowledgement in your application's protocol.

On this page