Passed
Push — feature/data-hook-error-toast ( 38b502...b13174 )
by Yonathan
04:31
created

resources/assets/js/hooks/apiResourceHooks.tsx   A

Complexity

Total Complexity 3
Complexity/F 0

Size

Lines of Code 57
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 33
mnd 3
bc 3
fnc 0
dl 0
loc 57
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
2
/* eslint-disable import/prefer-default-export */
3
import { useContext } from "react";
4
import { getApplicantSkillsEndpoint } from "../api/applicantSkills";
5
import { ErrorContext } from "../components/ErrorContainer";
6
import { FetchError } from "../helpers/httpRequests";
7
import { useResource } from "./webResourceHooks";
8
9
/**
10
 * If the error is a FetchError and the response body contains a message field, use that to construct the message.
11
 * Otherwise, simply use the error object's message.
12
 * @param error
13
 */
14
const errorToMessage = async (error: Error | FetchError): Promise<string> => {
15
  if (error instanceof FetchError && error.response.status) {
16
    try {
17
      const responseBody = await error.response.json();
18
      if (responseBody.message) {
19
        return `${error.response.status} - ${responseBody.message}`;
20
      }
21
    } catch (e) {
22
      // Can't parse response json body; fall through and return normal error message.
23
    }
24
  }
25
  return error.message;
26
};
27
28
/**
29
 * This hook returns a handleError function which tries to push the error into the ErrorContext queue.
30
 * If no ErrorContext Provider exists in the component hierarchy, simply nothing will happen.
31
 */
32
const useErrorHandler = () => {
33
  const { dispatch } = useContext(ErrorContext);
34
  const handleError = (error: Error | FetchError) => {
35
    errorToMessage(error).then((message) =>
36
      dispatch({
37
        type: "push",
38
        payload: message,
39
      }),
40
    );
41
  };
42
  return handleError;
43
};
44
45
export const useApplicantSkillIds = (applicantId: number) => {
46
  const handleError = useErrorHandler();
47
  return useResource<{ skill_ids: number[] }>(
48
    getApplicantSkillsEndpoint(applicantId),
49
    {
50
      skill_ids: [],
51
    },
52
    {
53
      handleError,
54
    },
55
  );
56
};
57