You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
fms/hooks/use-api.ts

30 lines
898 B

import {useContext, useEffect, useState} from 'react'
import {SMClient} from "../api/sm/sm-client";
import Context from "../context/token";
import {Token} from "./use-token";
import {BearerAuthentication} from "../api/authentication";
import {grabRawToken} from "../functions/token";
const grabClient = (token: Token | null, rawToken: string | null): SMClient => {
let authentication = {}
if (rawToken) {
authentication = {
authentication: new BearerAuthentication(rawToken)
}
}
return new SMClient({
baseUrl: token?.host || 'localhost',
...authentication
})
}
export function useApi(): SMClient {
let {token} = useContext(Context)
let [client, setClient] = useState<SMClient>(grabClient(token, grabRawToken()))
useEffect(() => {
setClient(grabClient(token, grabRawToken()))
}, [token])
return client
}