Total Complexity | 2 |
Complexity/F | 2 |
Lines of Code | 51 |
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 = { type: "push"; payload: string; } | { type: "pop"; }; |
||
8 | |||
9 | const initialState: ErrorState = { errorQueue: [] }; |
||
10 | function errorReducer(state: ErrorState, action: ErrorAction) { |
||
11 | switch (action.type) { |
||
12 | case "push": |
||
13 | // Add payload to the end of the array. |
||
14 | return { errorQueue: [...state.errorQueue, action.payload] }; |
||
15 | case "pop": |
||
16 | // Remove the first element of the array. |
||
17 | return { errorQueue: state.errorQueue.slice(1) }; |
||
18 | default: |
||
19 | throw new Error("Undefined action type in errorReducer."); |
||
20 | } |
||
21 | } |
||
22 | |||
23 | interface ErrorContextProps { |
||
24 | state: ErrorState; |
||
25 | dispatch: React.Dispatch<ErrorAction>; |
||
26 | } |
||
27 | |||
28 | export const ErrorContext = React.createContext<ErrorContextProps>({ |
||
29 | state: initialState, |
||
30 | dispatch: (action) => {}, |
||
31 | }); |
||
32 | |||
33 | export const ErrorContainer: React.FunctionComponent = ({ |
||
34 | children, |
||
35 | }): React.ReactElement => { |
||
36 | const [state, dispatch] = useReducer(errorReducer, initialState); |
||
37 | |||
38 | return ( |
||
39 | <ErrorContext.Provider |
||
40 | value={{ |
||
41 | state, |
||
42 | dispatch, |
||
43 | }} |
||
44 | > |
||
45 | {children} |
||
46 | </ErrorContext.Provider> |
||
47 | ); |
||
48 | }; |
||
49 | |||
50 | export default ErrorContainer; |
||
51 |