|
|
|
@ -1,19 +1,51 @@ |
|
|
|
|
import Axios from 'axios' |
|
|
|
|
import React, { createContext, useContext } from 'react' |
|
|
|
|
import { Api } from '../api' |
|
|
|
|
|
|
|
|
|
type Props = { |
|
|
|
|
children: React.ReactNode |
|
|
|
|
api: Api |
|
|
|
|
baseURL?: string |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
type Context = { |
|
|
|
|
api: Api |
|
|
|
|
get: <T>(path: string) => Promise<T> |
|
|
|
|
patch: <T>(path: string, body: Partial<T>) => Promise<T> |
|
|
|
|
post: <T>(path: string, body: Partial<T>) => Promise<T> |
|
|
|
|
create: <T>(path: string, body: Partial<T>) => Promise<T> |
|
|
|
|
destroy: (path: string) => Promise<string> |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
// Just find-replace "AppContext" with whatever context name you like. (ie. DankContext)
|
|
|
|
|
const AppContext = createContext<Context | null>(null) |
|
|
|
|
|
|
|
|
|
export const AppContextProvider = ({ api, children }: Props) => { |
|
|
|
|
return <AppContext.Provider value={{ api }}>{children}</AppContext.Provider> |
|
|
|
|
export const AppContextProvider = ({ children, baseURL }: Props) => { |
|
|
|
|
const axios = Axios.create({ baseURL }) |
|
|
|
|
|
|
|
|
|
async function get<T>(path: string): Promise<T> { |
|
|
|
|
const res = await axios.get<T>(path) |
|
|
|
|
return res.data |
|
|
|
|
} |
|
|
|
|
async function patch<T>(path: string, body: Partial<T>) { |
|
|
|
|
const res = await axios.patch<T>(path, body) |
|
|
|
|
return res.data |
|
|
|
|
} |
|
|
|
|
async function post<T>(path: string, body: Partial<T>) { |
|
|
|
|
const res = await axios.post<T>(path, body) |
|
|
|
|
return res.data |
|
|
|
|
} |
|
|
|
|
async function create<T>(path: string, body: Partial<T>) { |
|
|
|
|
// unauthed POST
|
|
|
|
|
const res = await axios.post<T>(path, body) |
|
|
|
|
return res.data |
|
|
|
|
} |
|
|
|
|
async function destroy(path: string) { |
|
|
|
|
const res = await axios.delete<string>(path) |
|
|
|
|
return res.data |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return ( |
|
|
|
|
<AppContext.Provider value={{ get, patch, post, create, destroy }}> |
|
|
|
|
{children} |
|
|
|
|
</AppContext.Provider> |
|
|
|
|
) |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
export const useAppContext = () => { |
|
|
|
|