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

76 lines
2.0 KiB
TypeScript
Raw Normal View History

2019-12-07 13:28:52 +02:00
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';
2019-12-12 09:26:23 +02:00
import Context from 'app/components/profile/Context';
2016-05-02 16:13:18 +03:00
type Props = {
2020-05-24 02:08:24 +03:00
username: string;
updateUsername: (username: string) => void;
};
2016-05-02 16:13:18 +03:00
2019-12-07 13:28:52 +02:00
class ChangeUsernamePage extends React.Component<Props> {
2020-05-24 02:08:24 +03:00
static contextType = Context;
/* TODO: use declare */ context: React.ContextType<typeof Context>;
2016-05-02 16:13:18 +03:00
2020-05-24 02:08:24 +03:00
form = new FormModel();
2016-05-02 16:13:18 +03:00
2020-05-24 02:08:24 +03:00
actualUsername: string = this.props.username;
2016-05-02 16:13:18 +03:00
2020-05-24 02:08:24 +03:00
componentWillUnmount() {
this.props.updateUsername(this.actualUsername);
}
2020-05-24 02:08:24 +03:00
render() {
return (
<ChangeUsername
form={this.form}
onSubmit={this.onSubmit}
onChange={this.onUsernameChange}
username={this.props.username}
/>
);
}
2020-05-24 02:08:24 +03:00
onUsernameChange = (username: string) => {
this.props.updateUsername(username);
};
2016-05-02 16:13:18 +03:00
2020-05-24 02:08:24 +03:00
onSubmit = () => {
const { form } = this;
2020-05-24 02:08:24 +03:00
if (this.actualUsername === this.props.username) {
this.context.goToProfile();
2020-05-24 02:08:24 +03:00
return Promise.resolve();
}
2016-05-02 16:13:18 +03:00
2020-05-24 02:08:24 +03:00
return this.context
.onSubmit({
form,
sendData: () => {
const { username, password } = form.serialize();
2020-05-24 02:08:24 +03:00
return changeUsername(this.context.userId, username, password);
},
})
.then(() => {
this.actualUsername = form.value('username');
2020-05-24 02:08:24 +03:00
this.context.goToProfile();
});
};
2016-05-02 16:13:18 +03:00
}
2019-12-07 13:28:52 +02:00
export default connect(
2020-05-24 02:08:24 +03:00
(state: RootState) => ({
username: state.user.username,
}),
{
updateUsername: (username: string) => updateUser({ username }),
},
)(ChangeUsernamePage);