Context.tsx 2.6 KB

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