Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. import * as React from 'react';
  2. import Axios, { AxiosInstance } from 'axios';
  3. import { createContext, consume } from '../lib/context-utils';
  4. import { AuthContext } from './AuthProvider';
  5.  
  6. export const ApiContext = createContext('apiContext', {
  7. api: undefined as AxiosInstance | undefined,
  8. auth: undefined as React.ContextType<typeof AuthContext> | undefined,
  9. })
  10.  
  11. interface Props {
  12. [AuthContext.displayName]: React.ContextType<typeof AuthContext>
  13. children?: React.ReactNode
  14. }
  15.  
  16. interface State {
  17. }
  18.  
  19. class ApiProvider extends React.PureComponent<Props, State> {
  20. render() {
  21. return (
  22. <ApiContext.Provider value={this.api}>
  23. {this.props.children}
  24. </ApiContext.Provider>
  25. )
  26. }
  27.  
  28. makeApi() {
  29. return Axios.create({
  30. baseURL: process.env.REACT_APP_API_ENDPOINT!,
  31. headers: {
  32. common: {
  33. 'Content-Type': 'application/json',
  34. 'Authorization': this.auth.data && `Bearer ${this.auth.data.token}`,
  35. },
  36. },
  37. })
  38. }
  39.  
  40. get auth() {
  41. return this.props[AuthContext.displayName]
  42. }
  43.  
  44. get api() {
  45. return {
  46. api: this.makeApi(),
  47. auth: this.auth,
  48. }
  49. }
  50. }
  51.  
  52. export default consume(AuthContext)(ApiProvider)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement