1
Fork 0
mirror of https://github.com/Steffo99/sophon.git synced 2024-12-22 06:44: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 d06959dc06
commit 6a4e695d55
2 changed files with 82 additions and 12 deletions

View file

@ -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 (
<Bluelib theme={"sophon"}>
<LayoutThreeCol>
<LayoutThreeCol.Center>
<Heading level={1}>
Sophon
</Heading>
<Box>
Welcome to Sophon!
</Box>
</LayoutThreeCol.Center>
</LayoutThreeCol>
</Bluelib>
<SophonContextProvider>
<Bluelib theme={"sophon"}>
<LayoutThreeCol>
<LayoutThreeCol.Center>
<Heading level={1}>
Sophon
</Heading>
<Box>
Welcome to Sophon!
</Box>
</LayoutThreeCol.Center>
</LayoutThreeCol>
</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>
)
}