accounts-frontend/packages/app/pages/profile/ChangeUsernamePage.tsx

85 lines
1.9 KiB
TypeScript
Raw Normal View History

import PropTypes from 'prop-types';
2019-12-07 16:58:52 +05:30
import React from 'react';
import { connect } from 'react-redux';
import { updateUser } from 'app/components/user/actions';
import { RootState } from 'app/reducers';
import { changeUsername } from 'app/services/api/accounts';
import { FormModel } from 'app/components/ui/form';
import ChangeUsername from 'app/components/profile/changeUsername/ChangeUsername';
2016-05-02 18:43:18 +05:30
2019-12-07 16:58:52 +05:30
type OwnProps = {};
type Props = {
2019-12-07 16:58:52 +05:30
username: string;
updateUsername: (username: string) => void;
};
2016-05-02 18:43:18 +05:30
2019-12-07 16:58:52 +05:30
class ChangeUsernamePage extends React.Component<Props> {
static contextTypes = {
userId: PropTypes.number.isRequired,
onSubmit: PropTypes.func.isRequired,
goToProfile: PropTypes.func.isRequired,
};
2016-05-02 18:43:18 +05:30
form = new FormModel();
2016-05-02 18:43:18 +05:30
actualUsername: string;
componentWillMount() {
this.actualUsername = this.props.username;
}
2016-05-02 18:43:18 +05:30
componentWillUnmount() {
this.props.updateUsername(this.actualUsername);
}
render() {
return (
<ChangeUsername
form={this.form}
onSubmit={this.onSubmit}
onChange={this.onUsernameChange}
username={this.props.username}
/>
);
}
onUsernameChange = (username: string) => {
this.props.updateUsername(username);
};
2016-05-02 18:43:18 +05:30
onSubmit = () => {
const { form } = this;
if (this.actualUsername === this.props.username) {
this.context.goToProfile();
return Promise.resolve();
2016-05-02 18:43:18 +05:30
}
return this.context
.onSubmit({
form,
sendData: () => {
const { username, password } = form.serialize();
return changeUsername(this.context.userId, username, password);
},
})
.then(() => {
this.actualUsername = form.value('username');
this.context.goToProfile();
});
};
2016-05-02 18:43:18 +05:30
}
2019-12-07 16:58:52 +05:30
export default connect(
(state: RootState) => ({
username: state.user.username,
}),
{
updateUsername: username => updateUser({ username }),
},
)(ChangeUsernamePage);