Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
cacabo opened this issue Nov 4, 2024 · 0 comments

Comments

@cacabo
Copy link

cacabo commented Nov 4, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant