Skip to content

Instantly share code, notes, and snippets.

@marbemac
Created August 17, 2023 23:01
Show Gist options
  • Save marbemac/3f634619f169a3a87d1cd6f25511602c to your computer and use it in GitHub Desktop.
Save marbemac/3f634619f169a3a87d1cd6f25511602c to your computer and use it in GitHub Desktop.
import { safeParse, safeStringify } from '@shared/utils-json';
import { cache } from 'react';
/**
* By default react cache only supports primitive arguments.
*
* This fn wraps react cache to support a single object argument.
*/
export function safeCache<R>(fn: () => R): () => R;
export function safeCache<T, R>(fn: (p: T) => R): (p: T) => R;
export function safeCache<T, R>(fn: (p?: T) => R): (p?: T) => R {
const cachedFn = cache((x?: string) => fn(safeParse(x) as T));
return p => cachedFn(safeStringify(p));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment