Skip to Content
ExamplesFetch requests

Fetch requests

A minimal fetch-on-click: URL selections push into a Subject, switchMap runs the fetch (cancelling any in-flight one), and distinctUntilChanged skips repeat clicks on the same URL.

For production-shaped fetching, see offline-resilient fetch (retry, backoff, pause/resume) and Suspense data fetching (loading UI as a Suspense fallback).

import {useMemo} from 'react'
import {useObservable} from 'react-rx'
import {
  distinctUntilChanged,
  map,
  Subject,
  switchMap,
} from 'rxjs'

// URL selections push into a Subject
const url$ = new Subject<string>()

const origin = new URL('https://react-rx.sanity.dev')
const URLS = [
  new URL('/fetch/a.txt', origin),
  new URL('/fetch/b.txt', origin),
]

function FetchExample() {
  // Create fetch response stream
  const response$ = useMemo(
    () =>
      url$.pipe(
        distinctUntilChanged(),
        switchMap((url) =>
          fetch(url).then((response) =>
            response.text(),
          ),
        ),
        map((responseText) => (
          <div>
            The result was: {responseText}
          </div>
        )),
      ),
    [],
  )

  const currentUrl = useObservable(url$, '')
  const response = useObservable(response$)

  return (
    <div>
      <p>
        {URLS.map((url) => (
          <button
            key={url.toString()}
            onClick={() =>
              url$.next(url.toString())
            }
          >
            {url.pathname}
          </button>
        ))}
      </p>
      {currentUrl ? (
        response
      ) : (
        <>Click on url to fetch</>
      )}
    </div>
  )
}

export default FetchExample

Open on CodeSandboxOpen Sandbox
Last updated on