34 lines
747 B
JavaScript
34 lines
747 B
JavaScript
|
import { createContext, useContext, useMemo } from 'react'
|
||
|
import Axios, { AxiosInstance } from 'axios'
|
||
|
|
||
|
export const BASE_URL = 'http://localhost:5000'
|
||
|
|
||
|
export const AxiosContext = createContext(undefined)
|
||
|
|
||
|
export default function AxiosProvider ({
|
||
|
children
|
||
|
}) {
|
||
|
const axios = useMemo(() => {
|
||
|
const axios = Axios.create({
|
||
|
baseURL: BASE_URL,
|
||
|
headers: {
|
||
|
'Content-Type': 'application/json'
|
||
|
}
|
||
|
})
|
||
|
|
||
|
return axios
|
||
|
}, [])
|
||
|
|
||
|
return (
|
||
|
<AxiosContext.Provider value={axios}> {children} </AxiosContext.Provider>
|
||
|
)
|
||
|
}
|
||
|
|
||
|
export function useAxios () {
|
||
|
const context = useContext(AxiosContext)
|
||
|
if (context !== undefined) {
|
||
|
return context
|
||
|
}
|
||
|
throw Error('useAxios must be called within axios provider!')
|
||
|
}
|