simon | 09fe482 | 2022-11-30 23:36:25 -0500 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2022 Savoir-faire Linux Inc. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU Affero General Public License as |
| 6 | * published by the Free Software Foundation; either version 3 of the |
| 7 | * License, or (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU Affero General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Affero General Public |
| 15 | * License along with this program. If not, see |
| 16 | * <https://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | import { createContext, useContext } from 'react'; |
| 19 | |
| 20 | export const createOptionalContext = <T>(displayName: string) => { |
| 21 | const Context = createContext<T | undefined>(undefined); |
| 22 | Context.displayName = displayName; |
| 23 | |
| 24 | function useOptionalContext(noThrow: true): T | undefined; |
| 25 | function useOptionalContext(noThrow?: false): T; |
| 26 | function useOptionalContext(noThrow?: boolean) { |
| 27 | const value = useContext(Context); |
| 28 | if (value === undefined && !noThrow) { |
| 29 | throw new Error(`The context ${Context.displayName} is not provided`); |
| 30 | } |
| 31 | return value; |
| 32 | } |
| 33 | |
| 34 | return { |
| 35 | Context, |
| 36 | useOptionalContext, |
| 37 | }; |
| 38 | }; |