Created
July 10, 2021 15:36
-
-
Save ELI7VH/c554ab236c173479bc793acb29721203 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Axios from 'axios' | |
import React, { createContext, useContext } from 'react' | |
type Props = { | |
children: React.ReactNode | |
baseURL?: string | |
} | |
type Context = { | |
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> | |
} | |
const AppContext = createContext<Context | null>(null) | |
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 = () => { | |
const context = useContext(AppContext) | |
if (!context) | |
throw new Error( | |
'AppContext must be called from within the AppContextProvider' | |
) | |
return context | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment