Skip to content

Ability to leverage AbortController or similar to abort/ignore superseded requests #955

@cacabo

Description

@cacabo

Context

Example use case: when a user selects a date, I load the shifts for that date. If the user swaps between several dates quickly, depending on my data fetching, if those request finish out of order my app might not use the shifts for the date the user currently has active.

A common browser-supported way to do this is through an AbortController.

In my exploring, SWR and other data fetching libraries recommend passing through an AbortController to fetch: vercel/swr#129

The OSDK wraps fetch, so I can't easily pass through an AbortController. You can provide your own fetch implementation when constructing a client, but that is not an ergonomic place to insert AbortController logic since it's usually dependent on state management you do not have access to when constructing the OSDK client.


Workaround

My current workaround is to use a a class I implemented called RequestCounter:

export class RequestCounter {
  private store: Record<string, number> = {}

  public get(key: string): number {
    return this.store[key] ?? 0
  }

  public increment(key: string): number {
    const value = this.get(key) + 1
    this.store[key] = value
    return value
  }
}

When I fetch data, I can say:

const counter = new RequestCounter()

async function fetchShifts() {
  const count = counter.increment('shifts')
  // Fetch objects async...
  const shifts = await client(Shift).filter({ date }).fetchPage()

  if (count !== counter.get(APPOINTMENTS_KEY)) {
    return ABORT_SYMBOL
  }

  // ... do something with shfits
}

However this approach does not handle errors well and forces me to handle complexity that would be better abstracted away with an AbortController.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions