import axios, { AxiosResponse } from 'axios' import React, { createContext, useContext } from 'react' type Props = { children: React.ReactNode baseURL?: string } type AppContextInterface = { 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 api = axios.create({ baseURL }) api.interceptors.request.use((config) => { // config.url += '?format=json' config.headers = { Authorization: `Token ${window.localStorage.getItem( 'cash-stacks-token', )}`, } return config }) async function get(path: string): Promise { const res = await api.get(path) return res.data } async function patch(path: string, body: Partial) { const res = await api.patch(path, body) return res.data } async function post(path: string, body: Partial) { const res = await api.post>(path, body) return res.data } async function create(path: string, body: Partial) { // unauthed POST const res = await api.post(path, body) return res.data } async function destroy(path: string) { const res = await api.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 }