useMatchMutate
A custom hook to revalidate multiple queries in SWR using regular expressions with. Thanks Lazar for this β¨
import { useSWRConfig } from "swr";
export function useMatchMutate() {
const { cache, mutate } = useSWRConfig();
return (matcher, ...args) => {
if (!(cache instanceof Map)) {
throw new Error(
"matchMutate requires the cache provider to be a Map instance",
);
}
const keys = [];
for (const key of cache.keys()) {
if (matcher.test(key)) {
keys.push(key);
}
}
const mutations = keys.map((key) => mutate(key, ...args));
return Promise.all(mutations);
};
}
keyExtractor
Part of my advanced TypeScript learning, extracting keys from an object array using Generics. This really improves the developer experience when I write my own utilities β¨
function keyExtractor<Data, Key extends keyof Data>
(data: Data[], key: Key) => return data.map(el => el[key]);
formatToMilitary
I've found myself in this dilemma of converting a number and it's meridiem to a proper 24 hour time when generate ISO timestamps. Simple, yet convenient β¨
function formatToMilitary(hour: number, meridiem: string) {
if (meridiem === "AM") {
if (hour === 12) return 0;
return hour;
} else {
if (hour === 12) return 12;
return hour + 12;
}
}