DEV Community

鳥山明
鳥山明

Posted on

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

Top comments (1)

Collapse
 
sindouk profile image
Sindou Koné

Add to the discussion