Context.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import React, { Component } from 'react';
  2. import { ProjectType, Cluster } from '../shared/types';
  3. type PropsType = {
  4. }
  5. type StateType = {
  6. }
  7. const Context = React.createContext({});
  8. const { Provider } = Context;
  9. const ContextConsumer = Context.Consumer;
  10. /**
  11. * Component managing a universal (application-wide) data store.
  12. *
  13. * Important Usage Notes:
  14. * 1) Each field must have an accompanying setter
  15. * 2) No function calls are allowed from within Context (not counting
  16. * initialization)
  17. * 3) Context should be used as a last-resort (changes will re-render ALL
  18. * components consuming Context)
  19. * 4) As a rule of thumb, Context should not be used for UI-related state
  20. */
  21. class ContextProvider extends Component {
  22. state = {
  23. currentModal: null as string | null,
  24. currentModalData: null as any,
  25. setCurrentModal: (currentModal: string, currentModalData?: any) => {
  26. this.setState({ currentModal, currentModalData });
  27. },
  28. currentError: null as string | null,
  29. setCurrentError: (currentError: string) => {
  30. this.setState({ currentError });
  31. },
  32. currentCluster: null as Cluster | null,
  33. setCurrentCluster: (currentCluster: Cluster) => {
  34. this.setState({ currentCluster });
  35. },
  36. currentProject: null as ProjectType | null,
  37. setCurrentProject: (currentProject: ProjectType) => {
  38. this.setState({ currentProject });
  39. },
  40. projects: [] as ProjectType[],
  41. setProjects: (projects: ProjectType[]) => {
  42. this.setState({ projects });
  43. },
  44. user: null as any,
  45. setUser: (userId: number, email: string) => {
  46. this.setState({ user: {userId, email} });
  47. },
  48. devOpsMode: true,
  49. setDevOpsMode: (devOpsMode: boolean) => {
  50. this.setState({ devOpsMode });
  51. },
  52. clearContext: () => {
  53. this.setState({
  54. currentModal: null,
  55. currentModalData: null,
  56. currentError: null,
  57. currentCluster: null,
  58. currentProject: null,
  59. projects: [],
  60. user: null,
  61. devOpsMode: true,
  62. });
  63. }
  64. };
  65. render() {
  66. return (
  67. <Provider value={this.state}>{this.props.children}</Provider>
  68. );
  69. }
  70. }
  71. export { Context, ContextProvider, ContextConsumer };