SettingsPassword.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { useFormState } from "react-use-form-state";
  2. import { Flex } from "reflexbox/styled-components";
  3. import React, { FC, useState } from "react";
  4. import axios from "axios";
  5. import { getAxiosConfig } from "../../utils";
  6. import { useMessage } from "../../hooks";
  7. import TextInput from "../TextInput";
  8. import { API } from "../../consts";
  9. import { Button } from "../Button";
  10. import Icon from "../Icon";
  11. import Text, { H2 } from "../Text";
  12. import { Col } from "../Layout";
  13. const SettingsPassword: FC = () => {
  14. const [loading, setLoading] = useState(false);
  15. const [message, setMessage] = useMessage();
  16. const [formState, { password }] = useFormState<{ password: string }>();
  17. const onSubmit = async e => {
  18. e.preventDefault();
  19. if (loading) return;
  20. if (!formState.validity.password) {
  21. return setMessage(formState.errors.password);
  22. }
  23. setLoading(true);
  24. setMessage();
  25. try {
  26. const res = await axios.post(
  27. API.CHANGE_PASSWORD,
  28. formState.values,
  29. getAxiosConfig()
  30. );
  31. formState.clear();
  32. setMessage(res.data.message, "green");
  33. } catch (err) {
  34. setMessage(err?.response?.data?.error || "Couldn't update the password.");
  35. }
  36. setLoading(false);
  37. };
  38. return (
  39. <Col alignItems="flex-start">
  40. <H2 mb={4} bold>
  41. Change password
  42. </H2>
  43. <Text mb={4}>Enter a new password to change your current password.</Text>
  44. <Flex as="form" onSubmit={onSubmit}>
  45. <TextInput
  46. {...password({
  47. name: "password",
  48. validate: value => {
  49. const val = value.trim();
  50. if (!val || val.length < 8) {
  51. return "Password must be at least 8 chars.";
  52. }
  53. }
  54. })}
  55. placeholder="New password"
  56. height={44}
  57. width={[1, 2 / 3]}
  58. pl={24}
  59. pr={24}
  60. mr={3}
  61. required
  62. />
  63. <Button type="submit" disabled={loading}>
  64. <Icon name={loading ? "spinner" : "refresh"} mr={2} stroke="white" />
  65. {loading ? "Updating..." : "Update"}
  66. </Button>
  67. </Flex>
  68. <Text color={message.color} mt={3} fontSize={15}>
  69. {message.text}
  70. </Text>
  71. </Col>
  72. );
  73. };
  74. export default SettingsPassword;