Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as React from 'react';
- import Axios, { AxiosInstance } from 'axios';
- import { createContext, consume } from '../lib/context-utils';
- import { AuthContext } from './AuthProvider';
- export const ApiContext = createContext('apiContext', {
- api: undefined as AxiosInstance | undefined,
- auth: undefined as React.ContextType<typeof AuthContext> | undefined,
- })
- interface Props {
- [AuthContext.displayName]: React.ContextType<typeof AuthContext>
- children?: React.ReactNode
- }
- interface State {
- }
- class ApiProvider extends React.PureComponent<Props, State> {
- render() {
- return (
- <ApiContext.Provider value={this.api}>
- {this.props.children}
- </ApiContext.Provider>
- )
- }
- makeApi() {
- return Axios.create({
- baseURL: process.env.REACT_APP_API_ENDPOINT!,
- headers: {
- common: {
- 'Content-Type': 'application/json',
- 'Authorization': this.auth.data && `Bearer ${this.auth.data.token}`,
- },
- },
- })
- }
- get auth() {
- return this.props[AuthContext.displayName]
- }
- get api() {
- return {
- api: this.makeApi(),
- auth: this.auth,
- }
- }
- }
- export default consume(AuthContext)(ApiProvider)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement