示例工程 17-react-state-and-data
17-react-state-and-data/demo-01-local-first/loader.ts
type Item = { id: string; title: string };
type Source = "cache" | "disk" | "network";
function createLoader(disk: Item[] | null) {
let cache: Item[] | null = null;
let version = 0;
return {
load(forceNetwork = false): { items: Item[]; source: Source } {
if (!forceNetwork && cache) return { items: cache, source: "cache" };
if (!forceNetwork && disk) {
cache = disk;
return { items: disk, source: "disk" };
}
version += 1;
const items = [{ id: "note-1", title: `网络结果 ${version}` }];
cache = items;
return { items, source: "network" };
},
clearCache() {
cache = null;
},
};
}
const loader = createLoader([{ id: "note-1", title: "磁盘结果" }]);
const first = loader.load();
const second = loader.load();
loader.clearCache();
const disk = loader.load();
const refreshed = loader.load(true);
console.log(
JSON.stringify({
evt: "smoke",
ok:
first.source === "disk" &&
second.source === "cache" &&
disk.source === "disk" &&
refreshed.source === "network",
first: first.source,
second: second.source,
disk: disk.source,
refreshed: refreshed.source,
}),
);