|
| 1 | +import { createContext, useContext, useReducer } from 'react'; |
| 2 | + |
| 3 | +type PageLastUpdatedDatesType = { |
| 4 | + parentPageLastUpdatedDate: string; |
| 5 | +}; |
| 6 | + |
| 7 | +type PageLastUpdatedState = { |
| 8 | + files: PageLastUpdatedDatesType; |
| 9 | +}; |
| 10 | + |
| 11 | +const pageLastUpdatedReducer = ( |
| 12 | + state: PageLastUpdatedState, |
| 13 | + action: { type: string; key: string; lastUpdated: string } |
| 14 | +) => { |
| 15 | + switch (action.type) { |
| 16 | + case 'update': { |
| 17 | + if (!Object.prototype.hasOwnProperty.call(state.files, action.key)) { |
| 18 | + state.files[action.key] = []; |
| 19 | + state.files[action.key].push(action.lastUpdated); |
| 20 | + } else if (!state.files[action.key].includes(action.lastUpdated)) { |
| 21 | + state.files[action.key].push(action.lastUpdated); |
| 22 | + } |
| 23 | + |
| 24 | + return { |
| 25 | + ...state |
| 26 | + }; |
| 27 | + } |
| 28 | + default: |
| 29 | + return state; |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +type LastUpdatedDatesContextType = { |
| 34 | + state: PageLastUpdatedState; |
| 35 | + dispatch: any; |
| 36 | +}; |
| 37 | + |
| 38 | +const LastUpdatedDatesContext = createContext<LastUpdatedDatesContextType>({ |
| 39 | + state: { files: { parentPageLastUpdatedDate: '' } }, |
| 40 | + dispatch: (action: any) => { |
| 41 | + /** no-op */ |
| 42 | + } |
| 43 | +}); |
| 44 | + |
| 45 | +export default function LastUpdatedDatesProvider({ |
| 46 | + children, |
| 47 | + parentPageLastUpdatedDate |
| 48 | +}) { |
| 49 | + const [state, dispatch] = useReducer(pageLastUpdatedReducer, { |
| 50 | + files: { parentPageLastUpdatedDate: parentPageLastUpdatedDate } |
| 51 | + }); |
| 52 | + |
| 53 | + return ( |
| 54 | + <LastUpdatedDatesContext.Provider value={{ state, dispatch }}> |
| 55 | + {children} |
| 56 | + </LastUpdatedDatesContext.Provider> |
| 57 | + ); |
| 58 | +} |
| 59 | + |
| 60 | +export function useLastUpdatedDatesContext() { |
| 61 | + const context = useContext(LastUpdatedDatesContext); |
| 62 | + if (!context) { |
| 63 | + throw new Error( |
| 64 | + 'useLastUpdatedDatesContext must be used within a LastUpdatedDatesProvider' |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + return context; |
| 69 | +} |
0 commit comments