Files
web/apps/scandic-web/utils/cache.ts
Anton Gunnarsson 5da3e457cb Merged in chore/migrate-from-next-lint (pull request #3263)
chore: Migrate from next lint to eslint

* Migrate scandic-web

* Migrate partner-sas

* Enable any rule in partner-sas


Approved-by: Joakim Jäderberg
Approved-by: Linus Flood
2025-12-02 10:08:56 +00:00

24 lines
997 B
TypeScript

import stringify from "json-stable-stringify-without-jsonify"
import { cache as reactCache } from "react"
/**
* Wrapper function to handle caching of memoized requests that recieve objects as args.
* React Cache will use shallow equality of the arguments to determine if there is a cache hit,
* therefore we need to stringify the arguments to ensure that the cache works as expected.
* This function will handle the stingification of the arguments, the caching of the function,
* and the parsing of the arguments back to their original form.
*
* @param fn - The function to memoize
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function cache<T extends (...args: any[]) => any>(fn: T) {
const cachedFunction = reactCache((stringifiedParams: string) => {
return fn(...JSON.parse(stringifiedParams))
})
return (...args: Parameters<T>): ReturnType<T> => {
const stringifiedParams = stringify(args)
return cachedFunction(stringifiedParams)
}
}