@mittwald/react-use-promise
Version:
Simple and declarative use of Promises in your React components. Observe their state and refresh them in various advanced ways.
38 lines (37 loc) • 1.03 kB
JavaScript
import { Tags } from "./Tags.js";
export class Store {
entries = new Map();
constructor() { }
getOrSet(id, dataBuilder, options = {}) {
const { tags = [] } = options;
const existing = this.entries.get(id);
if (existing) {
return existing.data;
}
const newData = dataBuilder();
this.entries.set(id, {
data: newData,
tags: new Tags(tags),
});
return newData;
}
set(id, dataBuilder, options = {}) {
this.getOrSet(id, dataBuilder, options);
}
get(id) {
return this.entries.get(id)?.data;
}
findBy(matcher) {
return this.getAll().filter(matcher);
}
getAll(tag) {
const entriesArray = Array.from(this.entries.values());
if (tag === undefined) {
return entriesArray.map((e) => e.data);
}
return entriesArray.filter((e) => e.tags.matching(tag)).map((e) => e.data);
}
clear() {
this.entries.clear();
}
}