UserProvider.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import React, { PureComponent } from 'react';
  2. import { getBackendSrv } from '@grafana/runtime';
  3. import { User } from 'app/types';
  4. export interface UserAPI {
  5. changePassword: (changePassword: ChangePasswordFields) => void;
  6. updateUserProfile: (profile: ProfileUpdateFields) => void;
  7. loadUser: () => void;
  8. }
  9. interface LoadingStates {
  10. changePassword: boolean;
  11. loadUser: boolean;
  12. updateUserProfile: boolean;
  13. }
  14. export interface ChangePasswordFields {
  15. oldPassword: string;
  16. newPassword: string;
  17. confirmNew: string;
  18. }
  19. export interface ProfileUpdateFields {
  20. name: string;
  21. email: string;
  22. login: string;
  23. }
  24. export interface Props {
  25. userId?: number; // passed, will load user on mount
  26. children: (api: UserAPI, states: LoadingStates, user?: User) => JSX.Element;
  27. }
  28. export interface State {
  29. user?: User;
  30. loadingStates: LoadingStates;
  31. }
  32. export class UserProvider extends PureComponent<Props, State> {
  33. state: State = {
  34. loadingStates: {
  35. changePassword: false,
  36. loadUser: true,
  37. updateUserProfile: false,
  38. },
  39. };
  40. componentDidMount() {
  41. if (this.props.userId) {
  42. this.loadUser();
  43. }
  44. }
  45. changePassword = async (payload: ChangePasswordFields) => {
  46. this.setState({ loadingStates: { ...this.state.loadingStates, changePassword: true } });
  47. await getBackendSrv().put('/api/user/password', payload);
  48. this.setState({ loadingStates: { ...this.state.loadingStates, changePassword: false } });
  49. };
  50. loadUser = async () => {
  51. this.setState({
  52. loadingStates: { ...this.state.loadingStates, loadUser: true },
  53. });
  54. const user = await getBackendSrv().get('/api/user');
  55. this.setState({ user, loadingStates: { ...this.state.loadingStates, loadUser: Object.keys(user).length === 0 } });
  56. };
  57. updateUserProfile = async (payload: ProfileUpdateFields) => {
  58. this.setState({ loadingStates: { ...this.state.loadingStates, updateUserProfile: true } });
  59. await getBackendSrv()
  60. .put('/api/user', payload)
  61. .then(() => {
  62. this.loadUser();
  63. })
  64. .catch(e => console.log(e))
  65. .finally(() => {
  66. this.setState({ loadingStates: { ...this.state.loadingStates, updateUserProfile: false } });
  67. });
  68. };
  69. render() {
  70. const { children } = this.props;
  71. const { loadingStates, user } = this.state;
  72. const api = {
  73. changePassword: this.changePassword,
  74. loadUser: this.loadUser,
  75. updateUserProfile: this.updateUserProfile,
  76. };
  77. return <>{children(api, loadingStates, user)}</>;
  78. }
  79. }
  80. export default UserProvider;