SettingsPassword.tsx 2.4 KB

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