import Axios from 'axios' import React, { createContext, useContext } from 'react' type Props = { children: React.ReactNode baseURL?: string } type Context = { get: (path: string) => Promise patch: (path: string, body: Partial) => Promise post: (path: string, body: Partial) => Promise create: (path: string, body: Partial) => Promise destroy: (path: string) => Promise } const AppContext = createContext(null) export const AppContextProvider = ({ children, baseURL }: Props) => { const axios = Axios.create({ baseURL }) async function get(path: string): Promise { const res = await axios.get(path) return res.data } async function patch(path: string, body: Partial) { const res = await axios.patch(path, body) return res.data } async function post(path: string, body: Partial) { const res = await axios.post(path, body) return res.data } async function create(path: string, body: Partial) { // unauthed POST const res = await axios.post(path, body) return res.data } async function destroy(path: string) { const res = await axios.delete(path) return res.data } return ( {children} ) } export const useAppContext = () => { const context = useContext(AppContext) if (!context) throw new Error( 'AppContext must be called from within the AppContextProvider', ) return context }