|
| 1 | +import React from "react"; |
| 2 | +import PropTypes from "prop-types"; |
| 3 | +import { Form, Button } from "semantic-ui-react"; |
| 4 | +import InlineError from "../messages/InlineError"; |
| 5 | + |
| 6 | +class ResetPasswordForm extends React.Component { |
| 7 | + state = { |
| 8 | + data: { |
| 9 | + token: this.props.token, |
| 10 | + password: "", |
| 11 | + passwordConfirmation: "" |
| 12 | + }, |
| 13 | + loading: false, |
| 14 | + errors: {} |
| 15 | + }; |
| 16 | + |
| 17 | + onChange = e => |
| 18 | + this.setState({ |
| 19 | + ...this.state, |
| 20 | + data: { ...this.state.data, [e.target.name]: e.target.value } |
| 21 | + }); |
| 22 | + |
| 23 | + onSubmit = e => { |
| 24 | + e.preventDefault(); |
| 25 | + const errors = this.validate(this.state.data); |
| 26 | + this.setState({ errors }); |
| 27 | + if (Object.keys(errors).length === 0) { |
| 28 | + this.setState({ loading: true }); |
| 29 | + this.props |
| 30 | + .submit(this.state.data) |
| 31 | + .catch(err => |
| 32 | + this.setState({ errors: err.response.data.errors, loading: false }) |
| 33 | + ); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + validate = data => { |
| 38 | + const errors = {}; |
| 39 | + if (!data.password) errors.password = "Can't be blank"; |
| 40 | + if (data.password !== data.passwordConfirmation) |
| 41 | + errors.password = "Passwords must match"; |
| 42 | + return errors; |
| 43 | + }; |
| 44 | + |
| 45 | + render() { |
| 46 | + const { errors, data, loading } = this.state; |
| 47 | + |
| 48 | + return ( |
| 49 | + <Form onSubmit={this.onSubmit} loading={loading}> |
| 50 | + <Form.Field error={!!errors.password}> |
| 51 | + <label htmlFor="password">New Password</label> |
| 52 | + <input |
| 53 | + type="password" |
| 54 | + id="password" |
| 55 | + name="password" |
| 56 | + placeholder="your new password" |
| 57 | + value={data.password} |
| 58 | + onChange={this.onChange} |
| 59 | + /> |
| 60 | + {errors.password && <InlineError text={errors.password} />} |
| 61 | + </Form.Field> |
| 62 | + |
| 63 | + <Form.Field error={!!errors.passwordConfirmation}> |
| 64 | + <label htmlFor="passwordConfirmation"> |
| 65 | + Confirm your new password |
| 66 | + </label> |
| 67 | + <input |
| 68 | + type="password" |
| 69 | + id="passwordConfirmation" |
| 70 | + name="passwordConfirmation" |
| 71 | + placeholder="type it again, please" |
| 72 | + value={data.passwordConfirmation} |
| 73 | + onChange={this.onChange} |
| 74 | + /> |
| 75 | + {errors.passwordConfirmation && ( |
| 76 | + <InlineError text={errors.passwordConfirmation} /> |
| 77 | + )} |
| 78 | + </Form.Field> |
| 79 | + |
| 80 | + <Button primary>Reset</Button> |
| 81 | + </Form> |
| 82 | + ); |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +ResetPasswordForm.propTypes = { |
| 87 | + submit: PropTypes.func.isRequired, |
| 88 | + token: PropTypes.string.isRequired |
| 89 | +}; |
| 90 | + |
| 91 | +export default ResetPasswordForm; |
0 commit comments