From 32b918ab4feeafe103177465a2f7f1a542b044a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Chif=20Gerg=C5=91?= <chif.gergo@cloud.bme.hu> Date: Sun, 24 Jan 2021 18:18:22 +0100 Subject: [PATCH] Create ClientContext --- src/context/ClientContext.tsx | 29 +++++++++++++++++++++++++++++ src/context/index.tsx | 2 ++ src/hooks/useClientContext.ts | 13 +++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 src/context/ClientContext.tsx create mode 100644 src/context/index.tsx create mode 100644 src/hooks/useClientContext.ts diff --git a/src/context/ClientContext.tsx b/src/context/ClientContext.tsx new file mode 100644 index 0000000..c113018 --- /dev/null +++ b/src/context/ClientContext.tsx @@ -0,0 +1,29 @@ +import React, { createContext } from 'react'; +import { Client, createClient } from '../client/client'; + +export type ClientContextType = { + client: Client; +}; + +export const ClientContext = createContext<ClientContextType>({ + client: createClient(), +}); + +type ClientContextProviderProps = { + baseUrl?: string; +}; + +export const ClientContextProvider: React.FC<ClientContextProviderProps> = ({ + children, + baseUrl = '', +}) => { + return ( + <ClientContext.Provider + value={{ + client: createClient(baseUrl), + }} + > + {children} + </ClientContext.Provider> + ); +}; diff --git a/src/context/index.tsx b/src/context/index.tsx new file mode 100644 index 0000000..8577543 --- /dev/null +++ b/src/context/index.tsx @@ -0,0 +1,2 @@ +export * from './ClientContext'; +export * from './UserContext'; diff --git a/src/hooks/useClientContext.ts b/src/hooks/useClientContext.ts new file mode 100644 index 0000000..67f603c --- /dev/null +++ b/src/hooks/useClientContext.ts @@ -0,0 +1,13 @@ +import { useContext } from 'react'; +import { ClientContext } from '../context'; +import type { ClientContextType } from '../context'; + +function useClientContext(): ClientContextType { + const clientContext = useContext(ClientContext); + if (!clientContext) { + throw new Error('You must use `ClientContextProvider` to access the `ClientContext`.'); + } + return clientContext; +} + +export default useClientContext; -- GitLab