From ae3fb7f1b0fb7eca3e1f32f6a36ee701b8009721 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Thu, 9 Sep 2021 16:01:49 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Create=20`SophonContext`,=20the=20a?= =?UTF-8?q?pp=20context=20containing=20global=20data?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/App.tsx | 27 +++++++------ frontend/src/methods/apiTools.tsx | 67 +++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 12 deletions(-) create mode 100644 frontend/src/methods/apiTools.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 5c7b16e..d791c01 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,20 +1,23 @@ import * as React from 'react'; import {Bluelib, Box, Heading, LayoutThreeCol} from "@steffo/bluelib-react"; +import {SophonContextProvider} from "./methods/apiTools"; function App() { return ( - - - - - Sophon - - - Welcome to Sophon! - - - - + + + + + + Sophon + + + Welcome to Sophon! + + + + + ); } diff --git a/frontend/src/methods/apiTools.tsx b/frontend/src/methods/apiTools.tsx new file mode 100644 index 0000000..d6a2f36 --- /dev/null +++ b/frontend/src/methods/apiTools.tsx @@ -0,0 +1,67 @@ +import * as React from "react" +import axios from "axios" +import {useState} from "react"; + + +export type SophonInstanceURL = string +export type SophonAuthorization = string | null + + +export interface SophonContextContents { + instanceUrl: SophonInstanceURL, + setInstanceUrl: React.Dispatch>, + + authorization: SophonAuthorization, + setAuthorization: React.Dispatch>, +} + + +export const SophonContext = React.createContext(null) + + +export function useSophonContext() { + const ctx = React.useContext(SophonContext) + + if(!ctx) { + throw new Error("useSophonAxios called outside a SophonContext.") + } + + return ctx +} + + +export function useSophonAxios() { + const {instanceUrl, authorization} = useSophonContext() + + return React.useMemo( + () => { + return axios.create({ + baseURL: instanceUrl, + timeout: 3000, + headers: { + "Authorization": authorization, + } + }) + }, + [instanceUrl, authorization] + ) +} + + +export interface SophonContextProviderProps { + children: React.ReactNode, +} + + +export function SophonContextProvider({children}: SophonContextProviderProps) { + const defaultInstanceUrl = process.env.REACT_APP_DEFAULT_INSTANCE_URL ?? "https://prod.sophon.steffo.eu" + + const [instanceUrl, setInstanceUrl] = useState(defaultInstanceUrl) + const [authorization, setAuthorization] = useState(null) + + return ( + + {children} + + ) +}