Skip to content

Instantly share code, notes, and snippets.

@haishanh
Forked from ryanflorence/createResource.js
Created January 1, 2020 16:03
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 haishanh/115ae8050be4f44716259f246bb90e06 to your computer and use it in GitHub Desktop.
Save haishanh/115ae8050be4f44716259f246bb90e06 to your computer and use it in GitHub Desktop.
import React from "react";
import { Link } from "react-router-dom";
export function createResource(getPromise) {
let cache = {};
let inflight = {};
let errors = {};
function load(key) {
inflight[key] = getPromise(key)
.then(val => {
delete inflight[key];
cache[key] = val;
})
.catch(error => {
errors[key] = error;
});
return inflight[key];
}
function preload(key) {
if (cache[key] !== undefined || inflight[key]) return;
load(key);
}
function read(key) {
if (cache[key] !== undefined) {
return cache[key];
} else if (errors[key]) {
throw errors[key];
} else if (inflight[key]) {
throw inflight[key];
} else {
throw load(key);
}
}
function clear(key) {
if (key) {
delete cache[key];
} else {
cache = {};
}
}
function ResourceLink({ cacheKey, ...props }) {
const _preload = () => preload(cacheKey);
return (
<Link onMouseEnter={_preload} onFocus={_preload} {...props} />
);
}
return { preload, read, clear, Link: ResourceLink };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment