Total Complexity | 2 |
Complexity/F | 2 |
Lines of Code | 58 |
Function Count | 1 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
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 |