Do not redirect after data update (#1965)

Do not redirect to other page after data was simply updated. After removing this redirect we stumbled upon some bigger issue with stale data inside our forms. This led to conflicts (Concurrent Modification Exceptions) if data was updated multiple times without reloading the page because of the last modified date of the single entities. This issue was hidden through the redirect and we fixed this by refactoring the form to functional components and simplify the state handling.
This commit is contained in:
Eduard Heimbuch
2022-02-28 15:02:30 +01:00
committed by GitHub
parent a1edf1ce8e
commit 1d432a6511
12 changed files with 311 additions and 422 deletions

View File

@@ -0,0 +1,2 @@
- type: fixed
description: Do not redirect after simple data updates ([#1965](https://github.com/scm-manager/scm-manager/pull/1965))

View File

@@ -162,7 +162,8 @@
"bellTitle": "Benachrichtigungen",
"empty": "Keine Benachrichtigungen",
"dismiss": "Löschen",
"dismissAll": "Alle löschen"
"dismissAll": "Alle löschen",
"updateSuccessful": "Die Änderungen wurden gespeichert."
},
"alerts": {
"shieldTitle": "Alerts"

View File

@@ -41,9 +41,6 @@
"add-member-button": {
"label": "Mitglied hinzufügen"
},
"add-member-textfield": {
"error": "Ungültiger Name für Mitglied"
},
"add-member-autocomplete": {
"placeholder": "Mitglied hinzufügen",
"loading": "Suche ...",

View File

@@ -163,7 +163,8 @@
"bellTitle": "Notifications",
"empty": "No notifications",
"dismiss": "Dismiss",
"dismissAll": "Dismiss all"
"dismissAll": "Dismiss all",
"updateSuccessful": "The update was successful."
},
"alerts": {
"shieldTitle": "Alerts"

View File

@@ -41,9 +41,6 @@
"add-member-button": {
"label": "Add Member"
},
"add-member-textfield": {
"error": "Invalid member name"
},
"add-member-autocomplete": {
"placeholder": "Add Member",
"loading": "Loading ...",

View File

@@ -38,9 +38,6 @@
"add-member-button": {
"label": "Añadir miembro"
},
"add-member-textfield": {
"error": "El nombre del miembro es incorrecto"
},
"add-member-autocomplete": {
"placeholder": "Añadir miembro",
"loading": "Cargando...",

View File

@@ -0,0 +1,51 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import React, { FC, useEffect, useState } from "react";
import { Notification } from "@scm-manager/ui-components";
import { useTranslation } from "react-i18next";
type Props = {
isUpdated: boolean;
};
const UpdateNotification: FC<Props> = ({ isUpdated }) => {
const [t] = useTranslation("commons");
const [showSuccess, setShowSuccess] = useState(false);
useEffect(() => {
setShowSuccess(isUpdated);
}, [isUpdated]);
if (showSuccess) {
return (
<Notification type="success" onClose={() => setShowSuccess(false)}>
{t("notifications.updateSuccessful")}
</Notification>
);
}
return null;
};
export default UpdateNotification;

View File

@@ -21,9 +21,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import React from "react";
import { WithTranslation, withTranslation } from "react-i18next";
import { Group, SelectValue } from "@scm-manager/ui-types";
import React, { FC, FormEvent, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Group, Member, SelectValue } from "@scm-manager/ui-types";
import {
AutocompleteAddEntryToTableField,
Checkbox,
@@ -36,83 +36,61 @@ import {
} from "@scm-manager/ui-components";
import * as validator from "./groupValidation";
type Props = WithTranslation & {
type Props = {
submitForm: (p: Group) => void;
loading?: boolean;
group?: Group;
loadUserSuggestions: (p: string) => Promise<SelectValue[]>;
};
type State = {
group: Group;
nameValidationError: boolean;
};
const GroupForm: FC<Props> = ({ submitForm, loading, group, loadUserSuggestions }) => {
const [t] = useTranslation("groups");
const [groupState, setGroupState] = useState({
name: "",
description: "",
_embedded: {
members: [] as Member[]
},
_links: {},
members: [] as string[],
type: "",
external: false
});
const [nameValidationError, setNameValidationError] = useState(false);
class GroupForm extends React.Component<Props, State> {
constructor(props) {
super(props);
this.state = {
group: {
name: "",
description: "",
_embedded: {
members: []
},
_links: {},
members: [],
type: "",
external: false
},
nameValidationError: false
};
}
componentDidMount() {
const { group } = this.props;
useEffect(() => {
if (group) {
this.setState({
...this.state,
group: {
...group
}
});
setGroupState(group);
}
}
}, [group]);
isFalsy(value) {
return !value;
}
const isValid = !(nameValidationError || !groupState.name);
isValid = () => {
const group = this.state.group;
return !(this.state.nameValidationError || this.isFalsy(group.name));
};
submit = (event: Event) => {
const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (this.isValid()) {
const { group } = this.state;
if (group.external) {
group.members = [];
if (isValid) {
if (groupState.external) {
groupState.members = [];
}
this.props.submitForm(group);
submitForm(groupState);
}
};
renderMemberfields = (group: Group) => {
if (group.external) {
const renderMemberfields = () => {
if (groupState.external) {
return null;
}
const { loadUserSuggestions, t } = this.props;
return (
<>
<MemberNameTagGroup members={group.members} memberListChanged={this.memberListChanged} />
<MemberNameTagGroup
members={groupState.members}
memberListChanged={(memberNames: string[]) => setGroupState({ ...groupState, members: memberNames })}
/>
<AutocompleteAddEntryToTableField
addEntry={this.addMember}
addEntry={addMember}
disabled={false}
buttonLabel={t("add-member-button.label")}
errorMessage={t("add-member-textfield.error")}
loadSuggestions={loadUserSuggestions}
placeholder={t("add-member-autocomplete.placeholder")}
loadingMessage={t("add-member-autocomplete.loading")}
@@ -122,122 +100,69 @@ class GroupForm extends React.Component<Props, State> {
);
};
renderExternalField = (group: Group) => {
const { t } = this.props;
if (this.isExistingGroup()) {
const renderExternalField = () => {
if (!groupState) {
return null;
}
return (
<Checkbox
label={t("group.external")}
checked={group.external}
checked={groupState.external}
helpText={t("groupForm.help.externalHelpText")}
onChange={this.handleExternalChange}
onChange={external => setGroupState({ ...groupState, external })}
/>
);
};
isExistingGroup = () => !!this.props.group;
render() {
const { loading, t } = this.props;
const { group } = this.state;
let nameField = null;
let subtitle = null;
if (!this.isExistingGroup()) {
// create new group
nameField = (
<InputField
label={t("group.name")}
errorMessage={t("groupForm.nameError")}
onChange={this.handleGroupNameChange}
value={group.name}
validationError={this.state.nameValidationError}
helpText={t("groupForm.help.nameHelpText")}
/>
);
} else if (group.external) {
subtitle = <Subtitle subtitle={t("groupForm.externalSubtitle")} />;
} else {
subtitle = <Subtitle subtitle={t("groupForm.subtitle")} />;
}
return (
<>
{subtitle}
<form onSubmit={this.submit}>
{nameField}
<Textarea
label={t("group.description")}
errorMessage={t("groupForm.descriptionError")}
onChange={this.handleDescriptionChange}
value={group.description}
validationError={false}
helpText={t("groupForm.help.descriptionHelpText")}
/>
{this.renderExternalField(group)}
{this.renderMemberfields(group)}
<Level right={<SubmitButton disabled={!this.isValid()} label={t("groupForm.submit")} loading={loading} />} />
</form>
</>
);
}
memberListChanged = membernames => {
this.setState({
...this.state,
group: {
...this.state.group,
members: membernames
}
});
};
addMember = (value: SelectValue) => {
if (this.isMember(value.value.id)) {
const addMember = (value: SelectValue) => {
if (groupState.members.includes(value.value.id)) {
return;
}
this.setState({
...this.state,
group: {
...this.state.group,
members: [...this.state.group.members, value.value.id]
}
});
setGroupState({ ...groupState, members: [...groupState.members, value.value.id] });
};
isMember = (membername: string) => {
return this.state.group.members.includes(membername);
};
let nameField = null;
let subtitle = null;
if (!group) {
// create new group
nameField = (
<InputField
label={t("group.name")}
errorMessage={t("groupForm.nameError")}
onChange={name => {
setNameValidationError(!validator.isNameValid(name));
setGroupState({ ...groupState, name });
}}
value={groupState.name}
validationError={nameValidationError}
helpText={t("groupForm.help.nameHelpText")}
/>
);
} else if (group.external) {
subtitle = <Subtitle subtitle={t("groupForm.externalSubtitle")} />;
} else {
subtitle = <Subtitle subtitle={t("groupForm.subtitle")} />;
}
handleGroupNameChange = (name: string) => {
this.setState({
nameValidationError: !validator.isNameValid(name),
group: {
...this.state.group,
name
}
});
};
return (
<>
{subtitle}
<form onSubmit={submit}>
{nameField}
<Textarea
label={t("group.description")}
errorMessage={t("groupForm.descriptionError")}
onChange={description => setGroupState({ ...groupState, description })}
value={groupState.description}
validationError={false}
helpText={t("groupForm.help.descriptionHelpText")}
/>
{renderExternalField()}
{renderMemberfields()}
<Level right={<SubmitButton disabled={!isValid} label={t("groupForm.submit")} loading={loading} />} />
</form>
</>
);
};
handleDescriptionChange = (description: string) => {
this.setState({
group: {
...this.state.group,
description
}
});
};
handleExternalChange = (external: boolean) => {
this.setState({
group: {
...this.state.group,
external
}
});
};
}
export default withTranslation("groups")(GroupForm);
export default GroupForm;

View File

@@ -22,12 +22,12 @@
* SOFTWARE.
*/
import React, { FC } from "react";
import { Redirect } from "react-router-dom";
import { Group } from "@scm-manager/ui-types";
import { useUpdateGroup, useUserSuggestions } from "@scm-manager/ui-api";
import { ErrorNotification } from "@scm-manager/ui-components";
import GroupForm from "../components/GroupForm";
import DeleteGroup from "./DeleteGroup";
import UpdateNotification from "../../components/UpdateNotification";
type Props = {
group: Group;
@@ -37,12 +37,9 @@ const EditGroup: FC<Props> = ({ group }) => {
const { error, isLoading, update, isUpdated } = useUpdateGroup();
const userSuggestions = useUserSuggestions();
if (isUpdated) {
return <Redirect to={`/group/${group.name}`} />;
}
return (
<div>
<UpdateNotification isUpdated={isUpdated} />
<ErrorNotification error={error || undefined} />
<GroupForm group={group} submitForm={update} loading={isLoading} loadUserSuggestions={userSuggestions} />
<DeleteGroup group={group} />

View File

@@ -22,7 +22,7 @@
* SOFTWARE.
*/
import React, { FC } from "react";
import { Redirect, useRouteMatch } from "react-router-dom";
import { useRouteMatch } from "react-router-dom";
import RepositoryForm from "../components/form";
import { Repository } from "@scm-manager/ui-types";
import { ErrorNotification, Subtitle, urls } from "@scm-manager/ui-components";
@@ -33,6 +33,7 @@ import ExportRepository from "./ExportRepository";
import { useUpdateRepository } from "@scm-manager/ui-api";
import HealthCheckWarning from "./HealthCheckWarning";
import RunHealthCheck from "./RunHealthCheck";
import UpdateNotification from "../../components/UpdateNotification";
type Props = {
repository: Repository;
@@ -43,10 +44,6 @@ const EditRepo: FC<Props> = ({ repository }) => {
const { isLoading, error, update, isUpdated } = useUpdateRepository();
const [t] = useTranslation("repos");
if (isUpdated) {
return <Redirect to={`/repo/${repository.namespace}/${repository.name}`} />;
}
const url = urls.matchedUrlFromMatch(match);
const extensionProps = {
repository,
@@ -57,6 +54,7 @@ const EditRepo: FC<Props> = ({ repository }) => {
<>
<HealthCheckWarning repository={repository} />
<Subtitle subtitle={t("repositoryForm.subtitle")} />
<UpdateNotification isUpdated={isUpdated} />
<ErrorNotification error={error} />
<RepositoryForm repository={repository} loading={isLoading} modifyRepository={update} />
<ExtensionPoint name="repo-config.details" props={extensionProps} renderAll={true} />

View File

@@ -21,12 +21,11 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import React from "react";
import { WithTranslation, withTranslation } from "react-i18next";
import React, { FC, FormEvent, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { User } from "@scm-manager/ui-types";
import {
Checkbox,
ErrorNotification,
InputField,
Level,
PasswordConfirmation,
@@ -36,244 +35,171 @@ import {
} from "@scm-manager/ui-components";
import * as userValidator from "./userValidation";
type Props = WithTranslation & {
type Props = {
submitForm: (p: User) => void;
user?: User;
loading?: boolean;
};
type State = {
user: User;
mailValidationError: boolean;
nameValidationError: boolean;
displayNameValidationError: boolean;
passwordValid: boolean;
error?: Error;
const UserForm: FC<Props> = ({ submitForm, user, loading }) => {
const [t] = useTranslation("users");
const [userState, setUserState] = useState<User>({
name: "",
displayName: "",
mail: "",
password: "",
active: true,
external: false,
_links: {}
});
const [mailValidationError, setMailValidationError] = useState(false);
const [displayNameValidationError, setDisplayNameValidationError] = useState(false);
const [nameValidationError, setNameValidationError] = useState(false);
const [passwordValid, setPasswordValid] = useState(false);
useEffect(() => {
if (user) {
setUserState(user);
}
}, [user]);
const createUserComponentsAreInvalid = () => {
if (!user) {
return nameValidationError || !userState.name || (!userState.external && !passwordValid);
} else {
return false;
}
};
const editUserComponentsAreUnchanged = () => {
if (user) {
return (
user.displayName === userState.displayName &&
user.mail === userState.mail &&
user.active === userState.active &&
user.external === userState.external
);
} else {
return false;
}
};
const isInvalid = () => {
return (
createUserComponentsAreInvalid() ||
editUserComponentsAreUnchanged() ||
mailValidationError ||
displayNameValidationError ||
nameValidationError ||
!userState.displayName
);
};
const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!isInvalid()) {
submitForm(userState);
}
};
const passwordChangeField = (
<PasswordConfirmation
passwordChanged={password => {
setPasswordValid(!!password && passwordValid);
setUserState({ ...userState, password });
}}
/>
);
let nameField = null;
let subtitle = null;
if (!user) {
// create new user
nameField = (
<div className="column is-half">
<InputField
label={t("user.name")}
onChange={name => {
setNameValidationError(!!name && !validator.isNameValid(name));
setUserState({ ...userState, name });
}}
value={userState ? userState.name : ""}
validationError={nameValidationError}
errorMessage={t("validation.name-invalid")}
helpText={t("help.usernameHelpText")}
/>
</div>
);
} else {
// edit existing user
subtitle = <Subtitle subtitle={t("userForm.subtitle")} />;
}
return (
<>
{subtitle}
<form onSubmit={submit}>
<div className="columns is-multiline">
{nameField}
<div className="column is-half">
<InputField
label={t("user.displayName")}
onChange={displayName => {
setDisplayNameValidationError(!userValidator.isDisplayNameValid(displayName));
setUserState({ ...userState, displayName });
}}
value={userState ? userState.displayName : ""}
validationError={displayNameValidationError}
errorMessage={t("validation.displayname-invalid")}
helpText={t("help.displayNameHelpText")}
/>
</div>
<div className="column is-half">
<InputField
label={t("user.mail")}
onChange={mail => {
setMailValidationError(!!mail && !validator.isMailValid(mail));
setUserState({ ...userState, mail });
}}
value={userState ? userState.mail : ""}
validationError={mailValidationError}
errorMessage={t("validation.mail-invalid")}
helpText={t("help.mailHelpText")}
/>
</div>
</div>
{!user && (
<>
<div className="columns">
<div className="column">
<Checkbox
label={t("user.externalFlag")}
onChange={external => setUserState({ ...userState, external })}
checked={userState.external}
helpText={t("help.externalFlagHelpText")}
/>
</div>
</div>
</>
)}
{!userState.external && (
<>
{!user && passwordChangeField}
<div className="columns">
<div className="column">
<Checkbox
label={t("user.active")}
onChange={active => setUserState({ ...userState, active })}
checked={userState ? userState.active : false}
helpText={t("help.activeHelpText")}
/>
</div>
</div>
</>
)}
<Level right={<SubmitButton disabled={isInvalid()} loading={loading} label={t("userForm.button.submit")} />} />
</form>
</>
);
};
class UserForm extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
user: {
name: "",
displayName: "",
mail: "",
password: "",
active: true,
external: false,
_links: {}
},
mailValidationError: false,
displayNameValidationError: false,
nameValidationError: false,
passwordValid: false
};
}
componentDidMount() {
const { user } = this.props;
if (user) {
this.setState({
user: {
...user
}
});
}
}
createUserComponentsAreInvalid = () => {
const user = this.state.user;
if (!this.props.user) {
return this.state.nameValidationError || !user.name || (!user.external && !this.state.passwordValid);
} else {
return false;
}
};
editUserComponentsAreUnchanged = () => {
const user = this.state.user;
if (this.props.user) {
return (
this.props.user.displayName === user.displayName &&
this.props.user.mail === user.mail &&
this.props.user.active === user.active &&
this.props.user.external === user.external
);
} else {
return false;
}
};
isInvalid = () => {
const { user } = this.state;
return (
this.createUserComponentsAreInvalid() ||
this.editUserComponentsAreUnchanged() ||
this.state.mailValidationError ||
this.state.displayNameValidationError ||
this.state.nameValidationError ||
!user.displayName
);
};
submit = (event: Event) => {
event.preventDefault();
if (!this.isInvalid()) {
this.props.submitForm(this.state.user);
}
};
render() {
const { loading, t } = this.props;
const { user, error } = this.state;
const passwordChangeField = <PasswordConfirmation passwordChanged={this.handlePasswordChange} />;
let nameField = null;
let subtitle = null;
if (!this.props.user) {
// create new user
nameField = (
<div className="column is-half">
<InputField
label={t("user.name")}
onChange={this.handleUsernameChange}
value={user ? user.name : ""}
validationError={this.state.nameValidationError}
errorMessage={t("validation.name-invalid")}
helpText={t("help.usernameHelpText")}
/>
</div>
);
} else {
// edit existing user
subtitle = <Subtitle subtitle={t("userForm.subtitle")} />;
}
return (
<>
{subtitle}
<form onSubmit={this.submit}>
<div className="columns is-multiline">
{nameField}
<div className="column is-half">
<InputField
label={t("user.displayName")}
onChange={this.handleDisplayNameChange}
value={user ? user.displayName : ""}
validationError={this.state.displayNameValidationError}
errorMessage={t("validation.displayname-invalid")}
helpText={t("help.displayNameHelpText")}
/>
</div>
<div className="column is-half">
<InputField
label={t("user.mail")}
onChange={this.handleEmailChange}
value={user ? user.mail : ""}
validationError={this.state.mailValidationError}
errorMessage={t("validation.mail-invalid")}
helpText={t("help.mailHelpText")}
/>
</div>
</div>
{!this.props.user && (
<>
<div className="columns">
<div className="column">
<Checkbox
label={t("user.externalFlag")}
onChange={this.handleExternalChange}
checked={user.external}
helpText={t("help.externalFlagHelpText")}
/>
</div>
</div>
</>
)}
{!user.external && (
<>
{!this.props.user && passwordChangeField}
<div className="columns">
<div className="column">
<Checkbox
label={t("user.active")}
onChange={this.handleActiveChange}
checked={user ? user.active : false}
helpText={t("help.activeHelpText")}
/>
</div>
</div>
</>
)}
{error && <ErrorNotification error={error} />}
<Level
right={<SubmitButton disabled={this.isInvalid()} loading={loading} label={t("userForm.button.submit")} />}
/>
</form>
</>
);
}
handleUsernameChange = (name: string) => {
this.setState({
nameValidationError: !validator.isNameValid(name),
user: {
...this.state.user,
name
}
});
};
handleDisplayNameChange = (displayName: string) => {
this.setState({
displayNameValidationError: !userValidator.isDisplayNameValid(displayName),
user: {
...this.state.user,
displayName
}
});
};
handleEmailChange = (mail: string) => {
this.setState({
mailValidationError: !!mail && !validator.isMailValid(mail),
user: {
...this.state.user,
mail
}
});
};
handlePasswordChange = (password: string, passwordValid: boolean) => {
this.setState({
user: {
...this.state.user,
password
},
passwordValid: !!password && passwordValid
});
};
handleActiveChange = (active: boolean) => {
this.setState({
user: {
...this.state.user,
active
}
});
};
handleExternalChange = (external: boolean) => {
this.setState({
user: {
...this.state.user,
external
}
});
};
}
export default withTranslation("users")(UserForm);
export default UserForm;

View File

@@ -22,13 +22,13 @@
* SOFTWARE.
*/
import React, { FC } from "react";
import { Redirect } from "react-router-dom";
import UserForm from "../components/UserForm";
import DeleteUser from "./DeleteUser";
import { User } from "@scm-manager/ui-types";
import { ErrorNotification } from "@scm-manager/ui-components";
import UserConverter from "../components/UserConverter";
import { useUpdateUser } from "@scm-manager/ui-api";
import UpdateNotification from "../../components/UpdateNotification";
type Props = {
user: User;
@@ -37,12 +37,9 @@ type Props = {
const EditUser: FC<Props> = ({ user }) => {
const { error, isLoading, update, isUpdated } = useUpdateUser();
if (isUpdated) {
return <Redirect to={`/user/${user.name}`} />;
}
return (
<div>
<UpdateNotification isUpdated={isUpdated} />
<ErrorNotification error={error || undefined} />
<UserForm submitForm={update} user={user} loading={isLoading} />
<hr />