Skip to content

Instantly share code, notes, and snippets.

@intrnl
Created July 8, 2023 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/6649684806f25e6c7a11a452f86006a5 to your computer and use it in GitHub Desktop.
Save intrnl/6649684806f25e6c7a11a452f86006a5 to your computer and use it in GitHub Desktop.
Solid.js cached resource tied to the navigation entry
/// <reference types="navigation-api-types" />
import {
type ResourceFetcher,
type ResourceReturn,
type ResourceSource,
createResource,
onCleanup,
} from 'solid-js';
export const createCachedResource = <T, S, R = unknown>(fetcher: ResourceFetcher<S, T, R>) => {
const entries = new WeakMap<NavigationHistoryEntry, T>();
const create = (source: ResourceSource<S>) => {
const entry = navigation!.currentEntry!;
const exists = entries.has(entry);
const [resource, actions] = createResource(
source,
fetcher,
exists ? { initialValue: entries.get(entry) } : {},
);
onCleanup(() => {
const $state = resource.state;
if ($state === 'ready' || $state === 'refreshing') {
entries.set(entry, resource.latest);
} else {
entries.delete(entry);
}
});
return [resource, actions] as ResourceReturn<T, R>;
};
return create;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment