-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathNewHackerpackForm.js
More file actions
102 lines (93 loc) · 3.36 KB
/
NewHackerpackForm.js
File metadata and controls
102 lines (93 loc) · 3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React, { useState, useCallback, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { Grid2 as Grid, Box, Typography } from '@mui/material'
import TextInput from 'components/inputs/TextInput'
import Button from 'components/generic/Button'
import HackerpackService from 'services/hackerpack'
import * as AuthSelectors from 'reducers/auth/selectors'
import * as SnackbarActions from 'reducers/snackbar/actions'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
export default () => {
const navigate = useNavigate()
const { t } = useTranslation()
const [name, setName] = useState('')
const [error, setError] = useState()
const [loading, setLoading] = useState(false)
const hasError = Boolean(error)
const dispatch = useDispatch()
const idToken = useSelector(AuthSelectors.getIdToken)
useEffect(() => {
if (hasError) {
if (name.length < 5) {
setError(t('Name_must_five_'))
} else if (name.length >= 50) {
setError(t('Name_must_under_'))
} else {
setError()
}
}
}, [name, hasError, t])
const checkName = useCallback(() => {
if (name.length < 5) {
setError(t('Name_must_five_'))
return false
} else if (name.length >= 50) {
setError(t('Name_must_under_'))
return false
}
return true
}, [name.length, t])
const handleCreate = useCallback(() => {
if (!checkName()) return
setLoading(true)
HackerpackService.createHackerpack(idToken, { name })
.then(data => {
navigate(`/admin/hackerpack/${data.slug}`)
dispatch(SnackbarActions.success(`Created ${data.name}`))
})
.catch(e => {
dispatch(
SnackbarActions.error(t('Unable_to_create_hackerpack_')),
)
})
.finally(() => {
setLoading(false)
})
}, [checkName, idToken, name, dispatch, t])
return (
<Box mt={3}>
<Typography variant="h6" gutterBottom>
{t('Create_new_hackerpack_')}
</Typography>
<Grid container spacing={2} direction="row" alignItems="flex-end">
<Grid size={12}>
<Typography variant="caption" color="error">
{error}
</Typography>
</Grid>
<Grid size={{ xs: 12, sm: 9 }}>
<TextInput
label={t('Hackerpack_name_')}
placeholder={t('Enter_hackerpack_name_')}
value={name}
onChange={setName}
disabled={loading}
/>
</Grid>
<Grid size={{ xs: 12, sm: 3 }}>
<Button
disabled={hasError}
onClick={handleCreate}
loading={loading}
fullWidth
color="primary"
variant="contained"
>
{t('Create_')}
</Button>
</Grid>
</Grid>
</Box>
)
}