React hooks and Business Logic

akiratoriyama

鳥山明

Posted on September 20, 2022

React hooks and Business Logic

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;
};
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
akiratoriyama
鳥山明

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 - Type System
typescript Typescript - Type System

July 3, 2023

React hooks and Business Logic
typescript React hooks and Business Logic

September 20, 2022

Generics for user interfaces
typescript Generics for user interfaces

October 14, 2020

Type Safe Routing with fp-ts-routing
typescript Type Safe Routing with fp-ts-routing

July 1, 2020