📄 tanstack/pacer/latest/docs/framework/solid/examples/createAsyncRateLimiter

File: createAsyncRateLimiter.md | Updated: 11/15/2025

Source: https://tanstack.com/pacer/latest/docs/framework/solid/examples/createAsyncRateLimiter



TanStack

Pacer v0v0

Search...

+ K

Auto

Log In

TanStack StartRC

Docs Examples GitHub Contributors

TanStack Router

Docs Examples GitHub Contributors

TanStack Query

Docs Examples GitHub Contributors

TanStack Table

Docs Examples Github Contributors

TanStack Formnew

Docs Examples Github Contributors

TanStack DBbeta

Docs Github Contributors

TanStack Virtual

Docs Examples Github Contributors

TanStack Paceralpha

Docs Examples Github Contributors

TanStack Storealpha

Docs Examples Github Contributors

TanStack Devtoolsalpha

Docs Github Contributors

More Libraries

Maintainers Partners Support Learn StatsBETA Discord Merch Blog GitHub Ethos Brand Guide

Documentation

Framework

Solid logo

Solid

Version

Latest

Search...

+ K

Menu

Getting Started

Guides

API Reference

Debouncer API Reference

Throttler API Reference

Rate Limiter API Reference

Queue API Reference

Batcher API Reference

Debouncer Examples

Throttler Examples

Rate Limiter Examples

Queue Examples

Batcher Examples

Framework

Solid logo

Solid

Version

Latest

Menu

Getting Started

Guides

API Reference

Debouncer API Reference

Throttler API Reference

Rate Limiter API Reference

Queue API Reference

Batcher API Reference

Debouncer Examples

Throttler Examples

Rate Limiter Examples

Queue Examples

Batcher Examples

Solid Example: CreateAsyncRateLimiter

Github StackBlitz CodeSandbox

=================================================================================================================================================================================================================================================================================================================================================================================================================================================================

Code ExplorerCode

Interactive SandboxSandbox

  • public

  • src

    • index.tsx file iconindex.tsx
  • .eslintrc.cjs file icon.eslintrc.cjs

  • .gitignore file icon.gitignore

  • README.md file iconREADME.md

  • index.html file iconindex.html

  • package.json file iconpackage.json

  • tsconfig.json file icontsconfig.json

  • vite.config.ts file iconvite.config.ts

tsx

import { For, createSignal } from 'solid-js'
import { render } from 'solid-js/web'
import { createAsyncRateLimiter } from '@tanstack/solid-pacer/async-rate-limiter'

interface SearchResult {
  id: number
  title: string
}

// Simulate API call with fake data
const fakeApi = async (term: string): Promise<Array<SearchResult>> => {
  await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate network delay
  return [\
    { id: 1, title: `${term} result ${Math.floor(Math.random() * 100)}` },\
    { id: 2, title: `${term} result ${Math.floor(Math.random() * 100)}` },\
    { id: 3, title: `${term} result ${Math.floor(Math.random() * 100)}` },\
  ]
}

function App() {
  const [windowType, setWindowType] = createSignal<'fixed' | 'sliding'>('fixed')
  const [searchTerm, setSearchTerm] = createSignal('')
  const [results, setResults] = createSignal<Array<SearchResult>>([])

  // The function that will become rate limited
  const handleSearch = async (term: string) => {
    if (!term) {
      setResults([])
      return
    }

    // throw new Error('Test error') // you don't have to catch errors here (though you still can). The onError optional handler will catch it

    const data = await fakeApi(term)
    setResults(data)

    console.log(setSearchAsyncRateLimiter.state().successCount)
  }

  // hook that gives you an async rate limiter instance
  const setSearchAsyncRateLimiter = createAsyncRateLimiter(
    handleSearch,
    {
      windowType: windowType(),
      limit: 2, // Maximum 2 requests
      window: 1000, // per 1 second
      onError: (error) => {
        // optional error handler
        console.error('Search failed:', error)
        setResults([])
      },
      onReject: (_args, rateLimiter) => {
        console.log(
          'Rate limit exceeded:',
          rateLimiter.store.state.rejectionCount,
        )
      },
    },
    // Optional Selector function to pick the state you want to track and use
    (state) => ({
      successCount: state.successCount,
      isExecuting: state.isExecuting,
    }),
  )

  // get and name our rate limited function
  const handleSearchRateLimited = setSearchAsyncRateLimiter.maybeExecute

  // instant event handler that calls both the instant local state setter and the rate limited function
  async function onSearchChange(e: Event) {
    const newTerm = (e.target as HTMLInputElement).value
    setSearchTerm(newTerm)
    await handleSearchRateLimited(newTerm) // optionally await if you need to
  }

  return (
    <div>
      <h1>TanStack Pacer createAsyncRateLimiter Example</h1>
      <div style={{ display: 'grid', gap: '0.5rem', 'margin-bottom': '1rem' }}>
        <label>
          <input
            type="radio"
            name="windowType"
            value="fixed"
            checked={windowType() === 'fixed'}
            onChange={() => setWindowType('fixed')}
          />
          Fixed Window
        </label>
        <label>
          <input
            type="radio"
            name="windowType"
            value="sliding"
            checked={windowType() === 'sliding'}
            onChange={() => setWindowType('sliding')}
          />
          Sliding Window
        </label>
      </div>
      <div>
        <input
          autofocus
          type="search"
          value={searchTerm()}
          onInput={onSearchChange}
          placeholder="Type to search..."
          style={{ width: '100%' }}
          autocomplete="new-password"
        />
      </div>
      <div>
        <p>API calls made: {setSearchAsyncRateLimiter.state().successCount}</p>
        {results().length > 0 && (
          <ul>
            <For each={results()}>{(item) => <li>{item.title}</li>}</For>
          </ul>
        )}
        {setSearchAsyncRateLimiter.state().isExecuting && <p>Loading...</p>}
      </div>
      <pre style={{ 'margin-top': '20px' }}>
        {JSON.stringify(setSearchAsyncRateLimiter.state(), null, 2)}
      </pre>
    </div>
  )
}

render(() => <App />, document.getElementById('root')!)


import { For, createSignal } from 'solid-js'
import { render } from 'solid-js/web'
import { createAsyncRateLimiter } from '@tanstack/solid-pacer/async-rate-limiter'

interface SearchResult {
  id: number
  title: string
}

// Simulate API call with fake data
const fakeApi = async (term: string): Promise<Array<SearchResult>> => {
  await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate network delay
  return [\
    { id: 1, title: `${term} result ${Math.floor(Math.random() * 100)}` },\
    { id: 2, title: `${term} result ${Math.floor(Math.random() * 100)}` },\
    { id: 3, title: `${term} result ${Math.floor(Math.random() * 100)}` },\
  ]
}

function App() {
  const [windowType, setWindowType] = createSignal<'fixed' | 'sliding'>('fixed')
  const [searchTerm, setSearchTerm] = createSignal('')
  const [results, setResults] = createSignal<Array<SearchResult>>([])

  // The function that will become rate limited
  const handleSearch = async (term: string) => {
    if (!term) {
      setResults([])
      return
    }

    // throw new Error('Test error') // you don't have to catch errors here (though you still can). The onError optional handler will catch it

    const data = await fakeApi(term)
    setResults(data)

    console.log(setSearchAsyncRateLimiter.state().successCount)
  }

  // hook that gives you an async rate limiter instance
  const setSearchAsyncRateLimiter = createAsyncRateLimiter(
    handleSearch,
    {
      windowType: windowType(),
      limit: 2, // Maximum 2 requests
      window: 1000, // per 1 second
      onError: (error) => {
        // optional error handler
        console.error('Search failed:', error)
        setResults([])
      },
      onReject: (_args, rateLimiter) => {
        console.log(
          'Rate limit exceeded:',
          rateLimiter.store.state.rejectionCount,
        )
      },
    },
    // Optional Selector function to pick the state you want to track and use
    (state) => ({
      successCount: state.successCount,
      isExecuting: state.isExecuting,
    }),
  )

  // get and name our rate limited function
  const handleSearchRateLimited = setSearchAsyncRateLimiter.maybeExecute

  // instant event handler that calls both the instant local state setter and the rate limited function
  async function onSearchChange(e: Event) {
    const newTerm = (e.target as HTMLInputElement).value
    setSearchTerm(newTerm)
    await handleSearchRateLimited(newTerm) // optionally await if you need to
  }

  return (
    <div>
      <h1>TanStack Pacer createAsyncRateLimiter Example</h1>
      <div style={{ display: 'grid', gap: '0.5rem', 'margin-bottom': '1rem' }}>
        <label>
          <input
            type="radio"
            name="windowType"
            value="fixed"
            checked={windowType() === 'fixed'}
            onChange={() => setWindowType('fixed')}
          />
          Fixed Window
        </label>
        <label>
          <input
            type="radio"
            name="windowType"
            value="sliding"
            checked={windowType() === 'sliding'}
            onChange={() => setWindowType('sliding')}
          />
          Sliding Window
        </label>
      </div>
      <div>
        <input
          autofocus
          type="search"
          value={searchTerm()}
          onInput={onSearchChange}
          placeholder="Type to search..."
          style={{ width: '100%' }}
          autocomplete="new-password"
        />
      </div>
      <div>
        <p>API calls made: {setSearchAsyncRateLimiter.state().successCount}</p>
        {results().length > 0 && (
          <ul>
            <For each={results()}>{(item) => <li>{item.title}</li>}</For>
          </ul>
        )}
        {setSearchAsyncRateLimiter.state().isExecuting && <p>Loading...</p>}
      </div>
      <pre style={{ 'margin-top': '20px' }}>
        {JSON.stringify(setSearchAsyncRateLimiter.state(), null, 2)}
      </pre>
    </div>
  )
}

render(() => <App />, document.getElementById('root')!)

createRateLimitedValue

queue

Partners Become a Partner

Code RabbitCode Rabbit CloudflareCloudflare AG GridAG Grid NetlifyNetlify NeonNeon WorkOSWorkOS ClerkClerk ConvexConvex ElectricElectric SentrySentry PrismaPrisma StrapiStrapi UnkeyUnkey

scarf analytics