fetch

javascript
import * as Turbo from "@hotwired/turbo";

function metaContent(name) {
  const el = document.querySelector(`meta[name="${name}"]`);
  return el ? el.getAttribute("content") : null;
}

Attach custom headers to Turbo fetch requests (stimulus-free)

rails hotwire turbo
by codesnips 3 tabs
typescript
export interface Todo {
  id: string;
  title: string;
  done: boolean;
}

Optimistic Todo Toggling in React with Rollback via useReducer

javascript typescript react
by codesnips 3 tabs
typescript
export class TimeoutError extends Error {
  constructor(public readonly ms: number) {
    super(`Request timed out after ${ms}ms`);
    this.name = "TimeoutError";
  }
}

HTTP client timeout with AbortController (fetch)

fetch abortcontroller timeout
by codesnips 3 tabs
typescript
export interface Page<T> {
  items: T[];
  nextCursor: string | null;
}

export interface Post {

Infinite-Scroll List in React with IntersectionObserver and Cursor Pagination

react hooks infinite-scroll
by codesnips 3 tabs
typescript
import { useEffect, useState } from "react";

export function useDebouncedValue<T>(value: T, delay = 300): T {
  const [debounced, setDebounced] = useState<T>(value);

  useEffect(() => {

Debounced Search Box With AbortController to Cancel Stale Fetches in React

react hooks debounce
by codesnips 3 tabs
erb
<%# locals: item %>
<button
  type="button"
  class="toggle-btn"
  data-controller="toggle"
  data-action="click->toggle#toggle"

Optimistic toggle button with Stimulus “revert on failure”

rails hotwire stimulus
by codesnips 3 tabs
typescript
const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);

export function isRetryable(error: unknown, response?: Response): boolean {
  if (response) {
    return RETRYABLE_STATUS.has(response.status);
  }

Retrying Fetch With Exponential Backoff and Full Jitter in TypeScript

retry backoff jitter
by codesnips 3 tabs
javascript
import { useEffect, useState } from "react";

export function useDebounce(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {

Debounced Search Box With Live Autocomplete in React

react hooks debounce
by codesnips 3 tabs
javascript
const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);

export function fullJitter(attempt, baseDelay = 300, maxDelay = 10_000) {
  const ceiling = Math.min(maxDelay, baseDelay * 2 ** attempt);
  return Math.random() * ceiling;
}

Fetch With Exponential Backoff and Full Jitter Retries

fetch retry exponential-backoff
by codesnips 3 tabs