Passed
Push — feature/data-hook-error-toast ( 1a9769 )
by Tristan
07:34
created

ErrorContainer.tsx ➔ errorReducer   A

Complexity

Conditions 2

Size

Total Lines 10
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 10
rs 9.9
c 0
b 0
f 0
cc 2
1
import React, { useReducer } from "react";
2
3
type ErrorState = {
4
  errorQueue: string[];
5
};
6
7
export type ErrorAction =
8
  | {
9
      type: "push";
10
      payload: string;
11
    }
12
  | {
13
      type: "pop";
14
    };
15
16
const initialState: ErrorState = { errorQueue: [] };
17
function errorReducer(state: ErrorState, action: ErrorAction) {
18
  switch (action.type) {
19
    case "push":
20
      // Add payload to the end of the array.
21
      return { errorQueue: [...state.errorQueue, action.payload] };
22
    case "pop":
23
      // Remove the first element of the array.
24
      return { errorQueue: state.errorQueue.slice(1) };
25
    default:
26
      throw new Error("Undefined action type in errorReducer.");
27
  }
28
}
29
30
interface ContextProps {
31
  state: ErrorState;
32
  dispatch: React.Dispatch<ErrorAction>;
33
}
34
35
export const ErrorContext = React.createContext<ContextProps>({
36
  state: initialState,
37
  dispatch: (action) => {},
38
});
39
40
export const ErrorContainer: React.FunctionComponent = ({
41
  children,
42
}): React.ReactElement => {
43
  const [state, dispatch] = useReducer(errorReducer, initialState);
44
45
  return (
46
    <ErrorContext.Provider
47
      value={{
48
        state,
49
        dispatch,
50
      }}
51
    >
52
      {children}
53
    </ErrorContext.Provider>
54
  );
55
};
56
57
export default ErrorContainer;
58