1
Fork 0
mirror of https://github.com/Steffo99/sophon.git synced 2024-12-23 07:14:21 +00:00

Create SophonContext, the app context containing global data

This commit is contained in:
Steffo 2021-09-09 16:01:49 +02:00
parent 4a4824395a
commit ae3fb7f1b0
Signed by: steffo
GPG key ID: 6965406171929D01
2 changed files with 82 additions and 12 deletions

View file

@ -1,8 +1,10 @@
import * as React from 'react'; import * as React from 'react';
import {Bluelib, Box, Heading, LayoutThreeCol} from "@steffo/bluelib-react"; import {Bluelib, Box, Heading, LayoutThreeCol} from "@steffo/bluelib-react";
import {SophonContextProvider} from "./methods/apiTools";
function App() { function App() {
return ( return (
<SophonContextProvider>
<Bluelib theme={"sophon"}> <Bluelib theme={"sophon"}>
<LayoutThreeCol> <LayoutThreeCol>
<LayoutThreeCol.Center> <LayoutThreeCol.Center>
@ -15,6 +17,7 @@ function App() {
</LayoutThreeCol.Center> </LayoutThreeCol.Center>
</LayoutThreeCol> </LayoutThreeCol>
</Bluelib> </Bluelib>
</SophonContextProvider>
); );
} }

View file

@ -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<React.SetStateAction<SophonInstanceURL>>,
authorization: SophonAuthorization,
setAuthorization: React.Dispatch<React.SetStateAction<SophonAuthorization>>,
}
export const SophonContext = React.createContext<SophonContextContents | null>(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<SophonInstanceURL>(defaultInstanceUrl)
const [authorization, setAuthorization] = useState<SophonAuthorization>(null)
return (
<SophonContext.Provider value={{instanceUrl, setInstanceUrl, authorization, setAuthorization}}>
{children}
</SophonContext.Provider>
)
}