React hooks and Business Logic
鳥山明
Posted on September 20, 2022
Overview
hooks can use map
.
It is a very lightweight library. There are no dependencies.
https://www.npmjs.com/package/@bird-studio/use-map
Use case
with useSWR
import useSWR from "swr";
import type { SWRResponse } from "swr";
import { useMap } from "@bird-studio/use-map";
type MainRes = {
value: string;
};
// Easy to test because it does not use hook
const businessLogic = (p: SWRResponse<MainRes>) => {
if (p.data.value === "foo") {
return {
...p,
data: {
...p.data,
isFoo: true,
},
};
}
return {
...p,
data: {
...p.data,
isFoo: false,
},
};
};
const useMain = () => {
const res = useMap({ useHook: () => useSWR("/main", fetchMain) })
.map(businessLogic)
// Can be continuous.
.map((v) => v).value;
};
with useQuery
import { useQuery } from "@apollo/client";
import { useMap } from "@bird-studio/use-map";
import { QUERY } from "./QUERY";
// Easy to test because it does not use hook
const reducer = (p) => {
if (p.loading) {
return {
type: "loading",
};
}
if (p.error) {
return {
type: "error",
...p,
};
}
if (p.data) {
return {
type: "success",
data: p.data,
};
}
return new Error("🤬");
};
const useMain = () => {
const res = useMap({ useHook: () => useQuery(QUERY) }).map(reducer).value;
};
💖 💪 🙅 🚩
鳥山明
Posted on September 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
typescript Data fetching in React the functional way powered by TypeScript, io-ts & fp-ts
January 20, 2019