SettingsPassword.tsx 2.2 KB

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