# Matsuri Hooks

<!-- vscode-markdown-toc -->
<!-- prettier-ignore -->
- [Matsuri Hooks](#matsuri-hooks)
  - [Motivation](#motivation)
  - [Usage](#usage)
    - [Installation](#installation)
  - [Examples](#examples)
    - [useFetch](#usefetch)
      - [Conditional fetch](#conditional-fetch)
      - [Auto refetch](#auto-refetch)
      - [Convenient errors](#convenient-errors)
    - [useAuthFetch](#useauthfetch)
    - [useRequest](#userequest)
    - [createFetcher](#createfetcher)
    - [useIntersectionObserver](#useintersectionobserver)
    - [useOnClickOutside](#useonclickoutside)
    - [useKeyboardShortcut](#usekeyboardshortcut)
    - [useClipboardCopy](#useclipboardcopy)

<!-- vscode-markdown-toc-config
	numbering=false
	autoSave=true
	/vscode-markdown-toc-config -->
<!-- /vscode-markdown-toc -->

## <a name='Motivation'></a>Motivation

- Provide complex processing with safety guaranteed by testing
- Be common processing for each product

## <a name='Usage'></a>Usage

### <a name='Installation'></a>Installation

```
yarn add matsuri-hooks swr
```

## <a name='Examples'></a>Examples

### <a name='useFetch'></a>useFetch

```tsx
const { data, error, refetch } = useFetch<{ species: "fish" }>(
  "https://example.com/fish",
  { method: "GET" },
);

return (
  <div>
    <p>Species: {data?.species}</p>
    <button onClick={refetch}>Refetch</button>
    {error ? (
      <p>
        {error.name}: {error.message}
      </p>
    ) : null}
  </div>
);
```

#### Conditional fetch

```tsx
const [prefId, setPrefId] = useState<string>();
const { data } = useFetch<{ cityId: string }[]>(
  prefId ? `https://example.com/${prefId}/cities` : null,
);
```

#### Auto refetch

dependenciesを指定することで、dependenciesが変わった際に再取得される。

```tsx
const { data: prefecture, refetch } = useFetch<Prefecture>(getPrefecture());
const { data: cities } = useFetch<City[]>(getCities(), {
  dependencies: [prefecture?.id],
});

// dependenciesで紐づけられているため、prefectureのidが変わっていればcitiesも再取得される
refetch();
```

#### Convenient errors

Errorオブジェクトからレスポンスのステータスを取得できる。

```tsx
const { error } = useFetch<Response>("https://example.com/fish");

if (error.status === 404) {
  console.log("Not Found Error");
}
```

Responseがfalsyであり且つJSONフレンドリーであればパースした結果を受け取れる。

```tsx
const { error } = useFetch<Response>("https://example.com/fish");

console.log(error.message)
// 500: {errorType: too_many_fish}

if(error.parse()?.errorType === "too_many_fish){
  console.log("Too many fish")
}
```

パースされた結果に型を当てることも出来る。

```tsx
type ErrorType = "too_many_fish" | "not_found_fish";
interface ParsedError {
  errorType: ErrorType;
}
const { error } = useFetch<Response, ParsedError>("https://example.com/fish");
```

### <a name='useAuthFetch'></a>useAuthFetch

This default token format is `X-Access-Token: [TOKEN]`.

```tsx
const { token } = useAuth()
const { error, refetch } = useAuthFetch<never>(token, "https://example.com", { method: "POST", ... )
```

- useAuthBearerFetch：this default token format is `Authorization: Bearer [TOKEN]`.

### <a name='useRequest'></a>useRequest

useRequestはkey周りの過剰な配慮を撤廃したuseFetchである。フェッチオプションをオブジェクトとして渡すことができ、SWRを十分に理解していれば、より高度なデータ管理が行えるようになる。SWRを直接使いながらも、matsuri-hooksのエラーハンドリングなどの機能を活用できる。

```tsx
const { data, error, refetch, isLoading, isValidating } =
  useRequest<ResponseType>(
    "/foo", // SWR key
    {
      url: "/foo",
      method: "GET", // オプション: デフォルトはGET
      body: JSON.stringify({ param: "value" }), // オプション
    },
  );
```

より複雑なキャッシュシナリオのために、配列をキーとして使用することもできる：

```tsx
const { data } = useRequest([key1, key2], {
  url,
  body: JSON.stringify(input),
  method: "POST",
});
```

SWRの設定は第三引数として渡すことができる：

```tsx
const { data } = useRequest(
  key,
  {
    url,
    method: "GET",
  },
  {
    revalidateOnFocus: false,
    dedupingInterval: 5000,
  },
);
```

#### useAuthRequest

`X-Access-Token`ヘッダーを使用した認証リクエスト：

```tsx
const { data } = useAuthRequest(key, {
  url: "/protected-endpoint",
  token: userToken,
  method: "POST",
  body: JSON.stringify(payload),
});
```

トークンが空の場合、リクエストは行われません。

#### カスタムフックの作成例

useRequestとuseAuthRequestを使用して、カスタムフックを作成することができる：

```tsx
// よくあるuseFetchの記述置き換え
const useCustomRequest = (token, id, input) => {
  const url = endpoint({ id });
  return useAuthRequest(url, {
    url,
    token,
    body: JSON.stringify(input),
    method: endpoint.method,
  });
};

// 以前とほぼ同じ動作を再現する例
const useCustomRequest = (token, id, input) => {
  const url = endpoint({ id });
  const options = {
    url,
    body: JSON.stringify(input),
    method: endpoint.method,
    token,
  };
  return useAuthRequest(options, options);
};
```

#### useAuthBearerRequest

`Authorization: Bearer [TOKEN]`ヘッダーを使用した認証リクエスト：

```tsx
const { data } = useAuthBearerRequest(key, {
  url: "/protected-endpoint",
  token: userToken,
  method: "GET",
});
```

### <a name='createFetcher'></a>createFetcher

createFetcherはSWRで直接使用するためのフェッチャー関数を作成するユーティリティ関数である。これにより、SWRを直接使用しながらも、matsuri-hooksのエラーハンドリングやトークン管理の恩恵を受けることができる。

```tsx
import useSWR from "swr";
import { createFetcher } from "matsuri-hooks";

const MyComponent = ({ token }) => {
  const { data, error } = useSWR(
    "key",
    createFetcher({
      url: "/api/endpoint",
      token,
      method: "POST",
      body: JSON.stringify({ param: "value" }),
    }),
  );

  // データの使用とエラーハンドリング
};
```

### <a name='useIntersectionObserver'></a>useIntersectionObserver

```tsx
const ref = useRef(null);
const { entry, disconnect } = useIntersectionObserver(ref, { threshold: 0.1 });

const [image, setImage] = useState<string>();

useEffect(() => {
  if (entry) {
    const fetchImage = async () => {
      //...
      return image;
    };
    disconnect();
    setImage(fetchImage());
  }
}, []);

return <img ref={ref} src={image || "dummy.png"} />;
```

### <a name='useOnClickOutside'></a>useOnClickOutside

```tsx
const [open, setOpen] = useState(false);
const ref = useRef(null);
useOnClickOutside(ref, () => {
  setOpen(false);
});
return (
  <div>
    <button onClick={() => setOpen(true)}>OPEN</button>
    <Modal ref={ref} open={open} />
  </div>
);
```

### <a name='useKeyboardShortcut'></a>useKeyboardShortcut

If the specified key and control or meta key are pressed together, the second argument callback is executed.

```tsx
const [open, setOpen] = useState(false);
const ref = useRef(null);
useKeyboardShortcut("j", () => {
  setOpen(true);
});
return (
  <div>
    <Modal ref={ref} open={open} />
  </div>
);
```

### <a name='useClipboardCopy'></a>useClipboardCopy

If the specified key is pressed together with a control or meta key, or if the return method is called, the specified text is copied to clipboard.
Then, if the copy fails, onFailure is called, and if it succeeds, onSuccess is called.

```tsx
const [open, setOpen] = useState(false);
const ref = useRef(null);
const copy = useKeyboardShortcut(SOME_TOKEN, {
  key: "j",
  onSuccess: () => {
    addAlert("Success");
  },
  onFailure: () => {
    addAlert("Failed", { type: "error" });
  },
});
return (
  <div>
    <Button onClick={copy} />
  </div>
);
```
