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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
sindouk profile image
Sindou Koné

Add to the discussion

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more