summaryrefslogtreecommitdiffhomepage
path: root/gui/src
diff options
context:
space:
mode:
authorOskar Nyberg <oskar@mullvad.net>2020-05-12 22:33:32 +0200
committerOskar Nyberg <oskar@mullvad.net>2020-05-18 17:18:51 +0200
commit2c9ad659f9b9ae654291b5a1c0bac28b58de1a04 (patch)
tree5ecf72893e228c5f6342f41b91f5f5b1c11d5aba /gui/src
parent11770c5a073ab15aa26a14e5b9cc01d56f81633e (diff)
downloadmullvadvpn-2c9ad659f9b9ae654291b5a1c0bac28b58de1a04.tar.xz
mullvadvpn-2c9ad659f9b9ae654291b5a1c0bac28b58de1a04.zip
Add hook for getting app context in functional components
Diffstat (limited to 'gui/src')
-rw-r--r--gui/src/renderer/context.tsx19
1 files changed, 15 insertions, 4 deletions
diff --git a/gui/src/renderer/context.tsx b/gui/src/renderer/context.tsx
index 4a905be6b1..113a29fe71 100644
--- a/gui/src/renderer/context.tsx
+++ b/gui/src/renderer/context.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import React, { useContext } from 'react';
import App from './app';
export interface IAppContext {
@@ -10,6 +10,10 @@ if (process.env.NODE_ENV === 'development') {
AppContext.displayName = 'AppContext';
}
+const missingContextError = new Error(
+ 'The context value is empty. Make sure to wrap the component in AppContext.Provider.',
+);
+
export default function withAppContext<Props>(BaseComponent: React.ComponentType<Props>) {
// Exclude the IAppContext from props since those are injected props
const wrappedComponent = (props: Omit<Props, keyof IAppContext>) => {
@@ -23,9 +27,7 @@ export default function withAppContext<Props>(BaseComponent: React.ComponentType
return <BaseComponent {...mergedProps} />;
} else {
- throw new Error(
- 'The context value is empty. Make sure to wrap the component in AppContext.Provider.',
- );
+ throw missingContextError;
}
}}
</AppContext.Consumer>
@@ -39,3 +41,12 @@ export default function withAppContext<Props>(BaseComponent: React.ComponentType
return wrappedComponent;
}
+
+export function useAppContext(): App {
+ const appContext = useContext(AppContext);
+ if (appContext) {
+ return appContext.app;
+ } else {
+ throw missingContextError;
+ }
+}