| 1 |
import React, { useState } from "react"; |
| 2 |
import { useDispatch, useSelector } from "react-redux"; |
| 3 |
import { Link, useNavigate } from "react-router-dom"; |
| 4 |
import { Button, Card } from "react-bootstrap"; |
| 5 |
import PropTypes from "prop-types"; |
| 6 |
import { MainContainer } from "../../util/layout"; |
| 7 |
|
| 8 |
const CreateGroup = (props) => { |
| 9 |
const [groupName, setGroupName] = useState(""), |
| 10 |
[errorAlert, setErrorAlert] = useState(null), |
| 11 |
limit = useSelector((state) => state.limit); |
| 12 |
|
| 13 |
const dispatch = useDispatch(); |
| 14 |
const navigate = useNavigate(); |
| 15 |
|
| 16 |
const dispatchPageUpdate = (data, page) => { |
| 17 |
dispatch({ |
| 18 |
type: "GROUPS_PAGE", |
| 19 |
value: { |
| 20 |
data: data, |
| 21 |
page: page, |
| 22 |
}, |
| 23 |
}); |
| 24 |
}; |
| 25 |
|
| 26 |
const { createGroup, updateGroups } = props; |
| 27 |
|
| 28 |
return ( |
| 29 |
<MainContainer errorAlert={errorAlert} setErrorAlert={setErrorAlert}> |
| 30 |
<Card> |
| 31 |
<Card.Header> |
| 32 |
<h4>Create Group</h4> |
| 33 |
</Card.Header> |
| 34 |
<Card.Body> |
| 35 |
<div className="input-group"> |
| 36 |
<input |
| 37 |
className="group-name-input" |
| 38 |
data-testid="group-input" |
| 39 |
type="text" |
| 40 |
id="group-name" |
| 41 |
value={groupName} |
| 42 |
placeholder="group name..." |
| 43 |
onChange={(e) => { |
| 44 |
setGroupName(e.target.value.trim()); |
| 45 |
}} |
| 46 |
></input> |
| 47 |
</div> |
| 48 |
</Card.Body> |
| 49 |
<Card.Footer> |
| 50 |
<Link to="/groups"> |
| 51 |
<Button variant="light" id="return"> |
| 52 |
Back |
| 53 |
</Button> |
| 54 |
</Link> |
| 55 |
<span> </span> |
| 56 |
<Button |
| 57 |
id="submit" |
| 58 |
data-testid="submit" |
| 59 |
variant="primary" |
| 60 |
onClick={() => { |
| 61 |
createGroup(groupName) |
| 62 |
.then((data) => { |
| 63 |
return data.status < 300 |
| 64 |
? updateGroups(0, limit) |
| 65 |
.then((data) => dispatchPageUpdate(data, 0)) |
| 66 |
.then(() => navigate("/groups")) |
| 67 |
.catch(() => |
| 68 |
setErrorAlert(`Could not update groups list.`), |
| 69 |
) |
| 70 |
: setErrorAlert( |
| 71 |
`Failed to create group. ${ |
| 72 |
data.status == 409 ? "Group already exists." : "" |
| 73 |
}`, |
| 74 |
); |
| 75 |
}) |
| 76 |
.catch(() => setErrorAlert(`Failed to create group.`)); |
| 77 |
}} |
| 78 |
> |
| 79 |
Create |
| 80 |
</Button> |
| 81 |
</Card.Footer> |
| 82 |
</Card> |
| 83 |
</MainContainer> |
| 84 |
); |
| 85 |
}; |
| 86 |
|
| 87 |
CreateGroup.propTypes = { |
| 88 |
createGroup: PropTypes.func, |
| 89 |
updateGroups: PropTypes.func, |
| 90 |
}; |
| 91 |
|
| 92 |
export default CreateGroup; |