File size: 1,713 Bytes
5be784e
 
 
03ce1cf
5be784e
1ce932e
5be784e
 
 
 
1ce932e
5be784e
03ce1cf
1ce932e
5be784e
 
 
03ce1cf
5be784e
 
 
 
 
 
 
 
 
 
03ce1cf
 
8b61aa5
8f469b4
 
 
 
 
 
 
 
 
 
 
8b61aa5
8f469b4
 
 
03ce1cf
 
 
 
 
 
 
 
 
 
 
 
5be784e
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { useState } from "react"

import axios from "@/utils/axios";
import { Options } from "redaxios";

export const useRequest = (method: "post" | "put" | "patch" | "delete" | "get", endpoint: string | undefined, params: Options, body: Options | undefined) => {
  const [loading, setLoading] = useState<boolean>(false)
  const [data, setData] = useState<any>(null)

  const submit = async () => {
    if (!endpoint) return;
    setLoading(true);


    const url = new URL(endpoint, process.env.NEXT_PUBLIC_APP_APIURL);
    if (params) {
      const parameters = Object.entries(params).filter(
        ([_, value]) =>
          value !== "" &&
          value !== null &&
          value !== undefined &&
          value !== false
      );
      parameters.forEach(([key, value]) => {
        url.searchParams.append(key, value as string);
      });
    }

    const needBody = ["post", "put", "patch"].includes(method);

    const formattedBody = body ? Object?.entries(body as any).reduce((acc: any, [key, value]) => {
      if (key.includes(".")) {
        const [first, ...rest] = key.split(".");
        acc[first] = {
          ...acc[first],
          [rest.join(".")]: value
        }
      } else {
        acc[key] = value;
      }
      return acc;
    }
    , {}) : undefined;

    axios[method](url.pathname, needBody ? formattedBody : {
      data: method === "delete" ? formattedBody : undefined,
      params: url.searchParams
    })
    .then((res: any) => {
      if (res.ok) {
        setData(res.data);
      }
    })
    .catch((err) => {
      setData(err.data);
    })
    .finally(() => setLoading(false));
      
  };

  return {
    submit,
    loading,
    setLoading,
    data
  }
}