formik#FormikProvider JavaScript Examples
The following examples show how to use
formik#FormikProvider.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppTasks.js From course-manager with MIT License | 6 votes |
export default function AppTasks() {
const formik = useFormik({
initialValues: {
checked: [TASKS[2]]
},
onSubmit: (values) => {
console.log(values);
}
});
const { values, handleSubmit } = formik;
return (
<Card>
<CardHeader title="Tasks" />
<Box sx={{ px: 3, py: 1 }}>
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
{TASKS.map((task) => (
<TaskItem
key={task}
task={task}
formik={formik}
checked={values.checked.includes(task)}
/>
))}
</Form>
</FormikProvider>
</Box>
</Card>
);
}
Example #2
Source File: CourseFilterSidebar.js From course-manager with MIT License | 4 votes |
export default function ShopFilterSidebar({
isOpenFilter,
onResetFilter,
onOpenFilter,
onCloseFilter,
formik
}) {
const { values, getFieldProps, handleChange } = formik;
return (
<>
<Button
disableRipple
color="inherit"
endIcon={<Icon icon={roundFilterList} />}
onClick={onOpenFilter}
>
Filters
</Button>
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate>
<Drawer
anchor="right"
open={isOpenFilter}
onClose={onCloseFilter}
PaperProps={{
sx: { width: 280, border: 'none', overflow: 'hidden' }
}}
>
<Stack
direction="row"
alignItems="center"
justifyContent="space-between"
sx={{ px: 1, py: 2 }}
>
<Typography variant="subtitle1" sx={{ ml: 1 }}>
Filters
</Typography>
<IconButton onClick={onCloseFilter}>
<Icon icon={closeFill} width={20} height={20} />
</IconButton>
</Stack>
<Divider />
<Scrollbar>
<Stack spacing={3} sx={{ p: 3 }}>
<div>
<Typography variant="subtitle1" gutterBottom>
Gender
</Typography>
<FormGroup>
{FILTER_GENDER_OPTIONS.map((item) => (
<FormControlLabel
key={item}
control={
<Checkbox
{...getFieldProps('gender')}
value={item}
checked={values.gender.includes(item)}
/>
}
label={item}
/>
))}
</FormGroup>
</div>
<div>
<Typography variant="subtitle1" gutterBottom>
Category
</Typography>
<RadioGroup {...getFieldProps('category')}>
{FILTER_CATEGORY_OPTIONS.map((item) => (
<FormControlLabel key={item} value={item} control={<Radio />} label={item} />
))}
</RadioGroup>
</div>
<div>
<Typography variant="subtitle1" gutterBottom>
Colour
</Typography>
<ColorManyPicker
name="colors"
colors={FILTER_COLOR_OPTIONS}
onChange={handleChange}
onChecked={(color) => values.colors.includes(color)}
sx={{ maxWidth: 36 * 4 }}
/>
</div>
<div>
<Typography variant="subtitle1" gutterBottom>
Price
</Typography>
<RadioGroup {...getFieldProps('priceRange')}>
{FILTER_PRICE_OPTIONS.map((item) => (
<FormControlLabel
key={item.value}
value={item.value}
control={<Radio />}
label={item.label}
/>
))}
</RadioGroup>
</div>
<div>
<Typography variant="subtitle1" gutterBottom>
Rating
</Typography>
<RadioGroup {...getFieldProps('rating')}>
{FILTER_RATING_OPTIONS.map((item, index) => (
<FormControlLabel
key={item}
value={item}
control={
<Radio
disableRipple
color="default"
icon={<Rating readOnly value={4 - index} />}
checkedIcon={<Rating readOnly value={4 - index} />}
/>
}
label="& Up"
sx={{
my: 0.5,
borderRadius: 1,
'& > :first-of-type': { py: 0.5 },
'&:hover': {
opacity: 0.48,
'& > *': { bgcolor: 'transparent' }
},
...(values.rating.includes(item) && {
bgcolor: 'background.neutral'
})
}}
/>
))}
</RadioGroup>
</div>
</Stack>
</Scrollbar>
<Box sx={{ p: 3 }}>
<Button
fullWidth
size="large"
type="submit"
color="inherit"
variant="outlined"
onClick={onResetFilter}
startIcon={<Icon icon={roundClearAll} />}
>
Clear All
</Button>
</Box>
</Drawer>
</Form>
</FormikProvider>
</>
);
}
Example #3
Source File: VideoCreateForm.js From course-manager with MIT License | 4 votes |
function VideoCreateForm({ open, onClose, courseId, onDataCreated }) {
const classes = useStyles();
const [videoThumbnailUrl, setVideoThumbnailUrl] = useState('');
const [videoUrl, setVideoUrl] = useState('');
const VideoSchema = Yup.object().shape({
title: Yup.string().required('Title is required'),
description: Yup.string().required('Description is required')
});
const formik = useFormik({
initialValues: {
title: '',
description: ''
},
validationSchema: VideoSchema,
onSubmit: async (values) => {
const data = {
...values,
thumbnailUrl: videoThumbnailUrl,
videoUrl,
courseId
};
const newVideo = await apis.video.create(data);
if (!newVideo) {
return;
}
onDataCreated(newVideo);
onClose();
}
});
const { errors, touched, isSubmitting, handleSubmit, getFieldProps } = formik;
return (
<Modal open={open} onClose={onClose}>
<Card className={classes.card}>
<Stack direction="row" alignItems="center" justifyContent="space-between" mb={5}>
<Typography variant="h4" gutterBottom>
New Video
</Typography>
</Stack>
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<TextField
fullWidth
autoComplete="title"
type="text"
label="Title"
{...getFieldProps('title')}
error={Boolean(touched.title && errors.title)}
helperText={touched.title && errors.title}
/>
<TextField
fullWidth
autoComplete="description"
type="text"
label="Description"
{...getFieldProps('description')}
error={Boolean(touched.description && errors.description)}
helperText={touched.description && errors.description}
/>
<FileUploader
initUrl={videoThumbnailUrl}
type={VIDEO_THUMBNAIL_TYPE}
setUrl={setVideoThumbnailUrl}
title="Upload thumbnail"
name="create-video-thumb"
/>
<FileUploader
initUrl={videoUrl}
type={VIDEO_TYPE}
setUrl={setVideoUrl}
title="Upload video"
name="create-video"
/>
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={isSubmitting}
>
Submit
</LoadingButton>
</Stack>
</Form>
</FormikProvider>
</Card>
</Modal>
);
}
Example #4
Source File: LoginForm.js From course-manager with MIT License | 4 votes |
// ----------------------------------------------------------------------
export default function LoginForm() {
const navigate = useNavigate();
const [showPassword, setShowPassword] = useState(false);
const LoginSchema = Yup.object().shape({
username: Yup.string().required('Username is required'),
password: Yup.string().required('Password is required')
});
setUpdateLoginState((newProfile) => {
console.log(`${newProfile.username} logged in`);
});
const formik = useFormik({
initialValues: {
username: '',
password: ''
},
validationSchema: LoginSchema,
onSubmit: async (values) => {
const user = await apis.auth.login(values);
if (user) navigate('/dashboard', { replace: true });
}
});
const { errors, touched, isSubmitting, handleSubmit, getFieldProps } = formik;
const handleShowPassword = () => {
setShowPassword((show) => !show);
};
return (
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<TextField
fullWidth
autoComplete="username"
type="text"
label="Username"
{...getFieldProps('username')}
error={Boolean(touched.username && errors.username)}
helperText={touched.username && errors.username}
/>
<TextField
fullWidth
autoComplete="current-password"
type={showPassword ? 'text' : 'password'}
label="Password"
{...getFieldProps('password')}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton onClick={handleShowPassword} edge="end">
<Icon icon={showPassword ? eyeFill : eyeOffFill} />
</IconButton>
</InputAdornment>
)
}}
error={Boolean(touched.password && errors.password)}
helperText={touched.password && errors.password}
/>
</Stack>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ my: 2 }}>
<Link component={RouterLink} variant="subtitle2" to="#">
Forgot password?
</Link>
</Stack>
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={isSubmitting}
>
Login
</LoadingButton>
</Form>
</FormikProvider>
);
}
Example #5
Source File: RegisterForm.js From course-manager with MIT License | 4 votes |
// ----------------------------------------------------------------------
export default function RegisterForm() {
const navigate = useNavigate();
const [showPassword, setShowPassword] = useState(false);
const RegisterSchema = Yup.object().shape({
firstName: Yup.string()
.min(2, 'Too Short!')
.max(50, 'Too Long!')
.required('First name required'),
lastName: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('Last name required'),
email: Yup.string().email('Email must be a valid email address').required('Email is required'),
password: Yup.string().required('Password is required')
});
const formik = useFormik({
initialValues: {
firstName: '',
lastName: '',
email: '',
password: ''
},
validationSchema: RegisterSchema,
onSubmit: () => {
navigate('/dashboard', { replace: true });
}
});
const { errors, touched, handleSubmit, isSubmitting, getFieldProps } = formik;
return (
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
<TextField
fullWidth
label="First name"
{...getFieldProps('firstName')}
error={Boolean(touched.firstName && errors.firstName)}
helperText={touched.firstName && errors.firstName}
/>
<TextField
fullWidth
label="Last name"
{...getFieldProps('lastName')}
error={Boolean(touched.lastName && errors.lastName)}
helperText={touched.lastName && errors.lastName}
/>
</Stack>
<TextField
fullWidth
autoComplete="username"
type="email"
label="Email address"
{...getFieldProps('email')}
error={Boolean(touched.email && errors.email)}
helperText={touched.email && errors.email}
/>
<TextField
fullWidth
autoComplete="current-password"
type={showPassword ? 'text' : 'password'}
label="Password"
{...getFieldProps('password')}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton edge="end" onClick={() => setShowPassword((prev) => !prev)}>
<Icon icon={showPassword ? eyeFill : eyeOffFill} />
</IconButton>
</InputAdornment>
)
}}
error={Boolean(touched.password && errors.password)}
helperText={touched.password && errors.password}
/>
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={isSubmitting}
>
Register
</LoadingButton>
</Stack>
</Form>
</FormikProvider>
);
}
Example #6
Source File: Create.js From course-manager with MIT License | 4 votes |
// ----------------------------------------------------------------------
export default function Create() {
const [thumbnailUrl, setThumbnailUrl] = useState('');
const navigate = useNavigate();
const CourseSchema = Yup.object().shape({
title: Yup.string().required('Full name is required'),
description: Yup.string().required('Username is required')
});
const formik = useFormik({
initialValues: {
title: '',
description: ''
},
validationSchema: CourseSchema,
onSubmit: async (values) => {
const data = {
...values,
thumbnailUrl
};
const newCourse = await apis.course.create(data);
if (!newCourse) {
return;
}
navigate('/dashboard/courses', { replace: true });
}
});
const { errors, touched, isSubmitting, handleSubmit, getFieldProps } = formik;
return (
<Page title="List | Minimal-UI">
<Container>
<Stack direction="row" alignItems="center" justifyContent="space-between" mb={5}>
<Typography variant="h4" gutterBottom>
New Course
</Typography>
</Stack>
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<TextField
fullWidth
autoComplete="title"
type="text"
label="Title"
{...getFieldProps('title')}
error={Boolean(touched.title && errors.title)}
helperText={touched.title && errors.title}
/>
<TextField
fullWidth
autoComplete="description"
type="text"
label="Description"
{...getFieldProps('description')}
error={Boolean(touched.description && errors.description)}
helperText={touched.description && errors.description}
/>
<FileUploader
initUrl={thumbnailUrl}
type={COURSE_THUMBNAIL_TYPE}
setUrl={setThumbnailUrl}
title="Upload thumbnail"
name="create-course-thumb"
/>
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={isSubmitting}
>
Submit
</LoadingButton>
</Stack>
</Form>
</FormikProvider>
<Card />
</Container>
</Page>
);
}
Example #7
Source File: Edit.js From course-manager with MIT License | 4 votes |
// ----------------------------------------------------------------------
export default function Edit() {
const navigate = useNavigate();
const { id } = useParams();
const [course, setCourse] = useState();
const [videos, setVideos] = useState([]);
const [isVideoModelOpen, setVideoModelOpen] = useState(false);
const [thumbnailUrl, setThumbnailUrl] = useState('');
useEffect(() => {
async function fetchCourse() {
const queryString = RequestQueryBuilder.create({
join: {
field: 'videos'
}
});
const course = await apis.course.findOne(id, queryString.query());
if (!course) navigate('/dashboard/courses', { replace: true });
formik.initialValues = {
title: course.title,
description: course.description
};
setCourse(course);
setVideos(course.videos);
setThumbnailUrl(course.thumbnailUrl);
}
fetchCourse();
}, []);
const CourseSchema = Yup.object().shape({
title: Yup.string().required('Full name is required'),
description: Yup.string().required('Username is required')
});
const formik = useFormik({
initialValues: course,
enableReinitialize: true,
validationSchema: CourseSchema,
onSubmit: async (values) => {
const data = {
...values,
thumbnailUrl
};
const updatedCourse = await apis.course.update(id, data);
if (!updatedCourse) {
return;
}
navigate('/dashboard/courses', { replace: true });
}
});
const { errors, touched, isSubmitting, handleSubmit, getFieldProps } = formik;
const closeVideoForm = (e, reason) => {
if (reason !== 'backdropClick') setVideoModelOpen(false);
};
const videoCreatedHandler = (newVideo) => {
setVideos([...videos, newVideo]);
};
return (
<Page title="List | Minimal-UI">
<Container>
<VideoCreateForm
open={isVideoModelOpen}
onClose={closeVideoForm}
onDataCreated={videoCreatedHandler}
/>
<Stack direction="row" alignItems="center" justifyContent="space-between" mb={5}>
<Typography variant="h4" gutterBottom>
Edit Course
</Typography>
</Stack>
{course && (
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<TextField
fullWidth
autoComplete="title"
type="text"
label="Title"
{...getFieldProps('title')}
error={Boolean(touched.title && errors.title)}
helperText={touched.title && errors.title}
/>
<TextField
fullWidth
autoComplete="description"
type="text"
label="Description"
{...getFieldProps('description')}
error={Boolean(touched.description && errors.description)}
helperText={touched.description && errors.description}
/>
<FileUploader
initUrl={thumbnailUrl}
type={COURSE_THUMBNAIL_TYPE}
setUrl={setThumbnailUrl}
title="Upload thumbnail"
name="edit-course-thumb"
/>
<Stack direction="row" alignItems="center" justifyContent="space-between" mb={5}>
<Typography variant="h5" gutterBottom>
Videos
</Typography>
<Button
variant="contained"
onClick={() => setVideoModelOpen(true)}
startIcon={<Icon icon={plusFill} />}
>
Add video
</Button>
</Stack>
{videos && (
<Grid container spacing={3}>
{videos.map((video) => (
<Grid key={video.id} item xs={12} sm={6} md={3}>
<VideoCard video={video} />
</Grid>
))}
</Grid>
)}
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={isSubmitting}
>
Submit
</LoadingButton>
</Stack>
</Form>
</FormikProvider>
)}
<Card />
</Container>
</Page>
);
}
Example #8
Source File: Create.js From course-manager with MIT License | 4 votes |
// ----------------------------------------------------------------------
export default function Create() {
const navigate = useNavigate();
const [isAdmin, setIsAdmin] = useState(false);
const [isMod, setIsMod] = useState(false);
const [isSupporter, setIsSupporter] = useState(false);
const UserSchema = Yup.object().shape({
fullName: Yup.string().required('Full name is required'),
username: Yup.string().required('Username is required'),
email: Yup.string().email('Email must be a valid email address').required('Email is required')
});
const formik = useFormik({
initialValues: {
fullName: '',
username: '',
email: ''
},
validationSchema: UserSchema,
onSubmit: async (values) => {
const roles = [];
if (isAdmin) roles.push('ADMIN');
if (isSupporter) roles.push('SUPPORTER');
if (isMod) roles.push('MOD');
const newUser = await apis.user.create({
...values,
roles
});
console.log(`New user ${newUser.username}`);
navigate('/dashboard/user', { replace: true });
}
});
const handleChange = (event) => {
switch (event.target.name) {
case 'isAdmin':
setIsAdmin(event.target.checked);
if (event.target.checked) {
setIsMod(false);
setIsSupporter(false);
}
break;
case 'isMod':
setIsMod(event.target.checked);
break;
case 'isSupporter':
setIsSupporter(event.target.checked);
break;
default:
break;
}
};
const { errors, touched, isSubmitting, handleSubmit, getFieldProps } = formik;
return (
<Page title="List | Minimal-UI">
<Container>
<Stack direction="row" alignItems="center" justifyContent="space-between" mb={5}>
<Typography variant="h4" gutterBottom>
Edit User
</Typography>
<Button
variant="contained"
component={RouterLink}
to="#"
startIcon={<Icon icon={plusFill} />}
>
New List
</Button>
</Stack>
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<TextField
fullWidth
autoComplete="username"
type="text"
label="Username"
{...getFieldProps('username')}
error={Boolean(touched.username && errors.username)}
helperText={touched.username && errors.username}
/>
<TextField
fullWidth
autoComplete="fullName"
type="text"
label="Full name"
{...getFieldProps('fullName')}
error={Boolean(touched.fullName && errors.fullName)}
helperText={touched.fullName && errors.fullName}
/>
<TextField
fullWidth
autoComplete="email"
type="email"
label="Email"
{...getFieldProps('email')}
error={Boolean(touched.email && errors.email)}
helperText={touched.email && errors.email}
/>
<FormControlLabel
control={<ODCheckbox checked={isAdmin} onChange={handleChange} name="isAdmin" />}
label="Is Admin"
/>
<FormGroup row>
<FormControlLabel
disabled={isAdmin}
control={<ODCheckbox checked={isMod} onChange={handleChange} name="isMod" />}
label="Is Mod"
/>
<FormControlLabel
disabled={isAdmin}
control={
<ODCheckbox checked={isSupporter} onChange={handleChange} name="isSupporter" />
}
label="Is Supporter"
/>
</FormGroup>
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={isSubmitting}
>
Submit
</LoadingButton>
</Stack>
</Form>
</FormikProvider>
<Card />
</Container>
</Page>
);
}
Example #9
Source File: index.js From certificate-generator with MIT License | 4 votes |
FormRegister = (props) => {
/*Verifica se o acesso foi aprovado*/
const [ acessAproved, setAproved ] = useState(false)
/*Organizador do evento*/
const [ organizador, setOrganizador ] = useState('')
const formik = useFormik({
initialValues: {
name: "",
email: "",
password: "",
remember: true,
},
validationSchema: Yup.object().shape({
name: Yup.string().required('Digite seu nome'),
email: Yup.string().email('E-mail inválido').required('Digite seu e-mail'),
password: Yup.string().min(4).required('Digite uma senha')
})
})
const { handleSubmit, values } = formik
/*JSON dos usuários*/
const [ user, setUser ] = useState(users)
const addNewUser = (name, email, password, avatar) => {
setUser([
...user, {
name: name,
email: email,
password: password,
token: true,
avatar: avatar
}
])
setAproved(true)
setOrganizador(name)
message.success('Conta criada com sucesso')
}
/*Função acionada após criar a conta com o formulário*/
const actionButton = () => {
if(!values.name || !values.email || !values.password) {
message.warning('Por favor, preencha todos os campos')
} else {
/*Verificando se já existe um usuário cadastrado*/
let listEmails = []
user.map(itemJson => {
listEmails.push(itemJson.email)
})
/*Se o e-mail digitado pelo usuário pelo usuário ainda não está no JSON de usuários*/
if(!listEmails.includes(values.email)) {
addNewUser(values.name, values.email, values.password, " ")
} else {
message.warning('Esta conta já existe')
}
}
}
/*Função acionada após o login com o Google*/
const responseGoogle = response => {
/*Verificando se já existe um usuário cadastrado*/
let listEmails = []
user.map(itemJson => {
listEmails.push(itemJson.email)
})
/*Se o e-mail digitado pelo usuário pelo usuário ainda não está no JSON de usuários*/
if(!listEmails.includes(response.profileObj.email)) {
addNewUser(response.profileObj.name, response.profileObj.email, true, response.profileObj.imageUrl)
} else {
message.warning('Esta conta já existe')
}
}
return (
<>
<div className="form" style={{ display: acessAproved ? 'none' : 'block' }}>
<h1 className="title-cadastre">Cadastre uma conta já, é simples e rápido</h1>
<div className="button-google" >
<GoogleLogin
clientId="78039332386-46h93ebkr1bb708hqv47h410pdd89mj9.apps.googleusercontent.com"
render={renderProps => (
<button
onClick={renderProps.onClick} disabled={renderProps.disabled} className="loginBtn loginBtn-google">
Cadastrar com o Google </button>
)}
buttonText="Cadastrar com o Google"
onSuccess={responseGoogle}
onFailure={responseGoogle}
/>
</div>
<p className="ou">OU</p>
<FormikProvider value={formik}>
<Form onSubmit={handleSubmit}>
<Field
name="name"
type="text"
className="form-field"
prefix={<UserOutlined className="site-form-item-icon" />}
placeholder="Digite seu nome"
/>
<ErrorMessage
render={msg => <p className="msg-error" >{msg}</p>}
name="name" />
<Field
name="email"
type="text"
className="form-field"
prefix={<ScheduleOutlined className="site-form-item-icon" />}
placeholder="Digite seu e-mail"
/>
<ErrorMessage
render={msg => <p className="msg-error" >{msg}</p>}
name="email" />
<Field
name="password"
type="password"
className="form-field"
placeholder="Digite uma senha"
prefix={<LockOutlined className="site-form-item-icon" />}
/>
<ErrorMessage
render={msg => <p className="msg-error" >{msg}</p>}
name="password" />
<Button
type="submit"
onClick={actionButton}
className="button"
>Criar conta</Button>
</Form>
</FormikProvider>
</div>
{/*Renderizando a pagina de lista de eventos*/}
{ acessAproved && <ListEvents users={user} organizador={organizador}/>}
</>
);
}
Example #10
Source File: index.jsx From UpStats with MIT License | 4 votes |
export default function Dashboard() {
const api = create({
baseURL: "/api",
});
const toast = useToast();
const router = useRouter();
const [systems, setSystems] = useState([]);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [mailing, setMailing] = useState(false);
const [currentEditSystem, setCurrentEditSystem] = useState({
name: "",
url: "",
});
const [subsCount, setSubsCount] = useState(0);
const loadSystems = async () => {
try {
const { data } = await http.get("/systems");
setSystems(data);
} catch (e) {
toast({
title: "Error",
description: "Error Loading Systems",
status: "error",
duration: 9000,
isClosable: true,
});
}
};
const loadConfig = async () => {
try {
const { data } = await http.get("/config");
setMailing(data.mailing);
} catch (e) {
console.log("Error Loading Config");
}
};
const loadCount = async () => {
try {
const { data } = await http.get("/subs");
setSubsCount(data.length);
} catch (e) {
toast({
title: "Error",
description: "Error Loading Subs Count",
status: "error",
duration: 9000,
isClosable: true,
});
}
};
useEffect(() => {
const token = window.localStorage.getItem("token");
http.setJwt(token);
if (!token) {
setIsLoggedIn(false);
toast({
title: "Error",
description: "Redirecting to Login Page",
status: "warning",
duration: 9000,
isClosable: true,
});
router.push("/login");
} else setIsLoggedIn(true);
}, []);
useEffect(() => {
loadSystems();
}, []);
useEffect(() => {
loadCount();
}, []);
useEffect(() => {
loadConfig();
}, []);
const handleDelete = async (system) => {
const originalSystems = systems;
const newSystems = originalSystems.filter((s) => s._id !== system._id);
setSystems(newSystems);
try {
await http.delete(`/systems/${system._id}`);
} catch (ex) {
if (ex.response && ex.response.status === 404)
toast({
title: "Error",
description: "System May be Already Deleted",
status: "error",
duration: 9000,
isClosable: true,
});
setSystems(originalSystems);
}
};
const handleAdd = async (system) => {
try {
const { data } = await api.post("/systems", system, {
headers: localStorage.getItem("token"),
});
setSystems([...systems, data]);
} catch (ex) {
toast({
title: "Error",
description: "Submit Unsuccessful",
status: "error",
duration: 9000,
isClosable: true,
});
}
};
const formik = useFormik({
initialValues: {
name: "",
url: "",
type: "web",
},
validationSchema: Yup.object({
name: Yup.string()
.max(15, "Must be 15 characters or less")
.required("Required"),
url: Yup.string().required("Required"),
type: Yup.string(),
}),
onSubmit: (values) => {
handleAdd(values);
//alert(JSON.stringify(values, null, 2));
},
});
const handleEdit = async () => {
const originalSystems = systems;
let newSystems = [...systems];
const idx = newSystems.findIndex(
(sys) => sys._id === currentEditSystem._id
);
newSystems[idx] = { ...currentEditSystem };
setSystems(newSystems);
try {
await http.put(`/systems/${currentEditSystem._id}`, {
name: currentEditSystem.name,
url: currentEditSystem.url,
type: currentEditSystem.type,
});
setCurrentEditSystem({ name: "", url: "" });
} catch (ex) {
toast({
title: "Error",
description: "Error Updating The System",
status: "error",
duration: 9000,
isClosable: true,
});
setSystems(originalSystems);
setCurrentEditSystem({ name: "", url: "" });
}
};
const handleChangeConfig = async () => {
try {
await http.put(`/config`, {
mailing: mailing,
});
} catch (ex) {
toast({
title: "Error",
description: "Error Updating The Config",
status: "error",
duration: 9000,
isClosable: true,
});
}
};
return (
<FormikProvider value={formik}>
<>
<Layout>
{isLoggedIn ? (
<>
<div className=" mt-12 mx-auto">
<div>
<div className="m-auto p-4 md:w-1/4 sm:w-1/2 w-full">
<div className="p-12 py-6 rounded-lg">
<svg
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
className="w-12 h-12 inline-block users-status"
viewBox="0 0 24 24"
>
<path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" />
<circle cx={9} cy={7} r={4} />
<path d="M23 21v-2a4 4 0 00-3-3.87m-4-12a4 4 0 010 7.75" />
</svg>
<h2 className="title-font font-medium text-3xl">
{subsCount}
</h2>
<p className="leading-relaxed ">Users Subscribed</p>
</div>
</div>
</div>
</div>
{/* CRUD Status List */}
<div className="w-full max-w-sm overflow-hidden rounded-lg items-center mx-auto">
<h3 className="text-2xl font-black text-black">
Add New System
</h3>
<form onSubmit={formik.handleSubmit} className="p-3">
<Stack>
<Text>System Title</Text>
<Input
id="name"
name="name"
type="text"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.name}
placeholder="Enter here"
isInvalid={
formik.touched.name && formik.errors.name ? true : false
}
/>
{formik.touched.name && formik.errors.name ? (
<Alert status="error">
<AlertIcon />
{formik.errors.name}
</Alert>
) : null}
</Stack>
<Stack mt={2}>
<Text>System URL</Text>
<Input
placeholder="Enter here"
id="url"
name="url"
type="text"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.url}
isInvalid={
formik.touched.url && formik.errors.url ? true : false
}
/>
{formik.touched.url && formik.errors.url ? (
<Alert status="error">
<AlertIcon />
{formik.errors.url}
</Alert>
) : null}
</Stack>
{/* Select System Type */}
<RadioGroup>
<Stack mt={5}>
<Field as={Radio} type="radio" name="type" value="web">
Web
</Field>
<Field
as={Radio}
type="radio"
name="type"
value="telegram"
>
Telegram Bot
</Field>
</Stack>
</RadioGroup>
{/* Add */}
<div className="mt-4">
<button
style={{ backgroundColor: "#3747D4" }}
className="px-4 py-2 text-white rounded hover:bg-black focus:outline-none"
type="submit"
>
Add
</button>
</div>
</form>
{/* Status Page List */}
{/* Show Sites here */}
{systems.map((system) => (
<div key={system._id} className="status-items-manage">
<div className="items">
<span className="site-title">{system?.name}</span>
<div className="i">
<EditIcon
mr="2"
onClick={() => {
setCurrentEditSystem(system);
}}
/>
<DeleteIcon
color="red"
m="2"
onClick={() => {
handleDelete(system);
}}
/>
</div>
</div>
</div>
))}
{/* End */}
{currentEditSystem.name ? (
<div className="mt-4">
<Stack>
<h3 className="text-2xl font-black text-black">
Edit System
</h3>
<Stack>
<Text>System Title</Text>
<Input
id="name"
name="name"
type="text"
value={currentEditSystem.name}
onChange={(e) => {
setCurrentEditSystem({
...currentEditSystem,
name: e.target.value,
});
}}
placeholder="Enter here"
/>
</Stack>
<Stack mt={2}>
<Text>System URL</Text>
<Input
placeholder="Enter here"
id="url"
name="url"
type="text"
value={currentEditSystem.url}
onChange={(e) =>
setCurrentEditSystem({
...currentEditSystem,
url: e.target.value,
})
}
/>
</Stack>
</Stack>
{/* Add */}
<div className="mt-4">
<button
onClick={handleEdit}
style={{ backgroundColor: "#3747D4" }}
className="px-4 py-2 text-white rounded hover:bg-black focus:outline-none"
>
Done
</button>
</div>
</div>
) : (
""
)}
<Stack mt={12}>
<h3 className="text-xl font-black text-bold">Configs</h3>
<p className="text-md font-black text-bold">Mailing</p>
<Switch
size="lg"
isChecked={mailing}
onChange={(e) => setMailing(e.target.checked)}
/>
<div className="mt-4">
<button
onClick={handleChangeConfig}
style={{ backgroundColor: "#3747D4" }}
className="px-4 py-2 text-white rounded hover:bg-black focus:outline-none"
>
Done
</button>
</div>
</Stack>
</div>
</>
) : (
""
)}
{/* Total No. of Users Subscribed */}
</Layout>
</>
</FormikProvider>
);
}
Example #11
Source File: manage-admin.jsx From UpStats with MIT License | 4 votes |
Test = (props) => {
const api = create({
baseURL: `/api`,
});
const toast = useToast();
const router = useRouter();
const [users, setUsers] = useState([]);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [currentEditUser, setCurrentEditUser] = useState({
email: "",
});
const loadUsers = async () => {
try {
const { data } = await http.get("/users");
setUsers(data);
} catch (e) {
toast({
title: "Error",
description: "Error Loading Users",
status: "error",
duration: 9000,
isClosable: true,
});
}
};
useEffect(() => {
const token = window.localStorage.getItem("token");
http.setJwt(token);
if (!token) {
setIsLoggedIn(false);
toast({
title: "Error",
description: "Redirecting to Login Page",
status: "warning",
duration: 9000,
isClosable: true,
});
router.push("/login");
} else setIsLoggedIn(true);
}, []);
useEffect(() => {
loadUsers();
}, []);
const handleDelete = async (user) => {
const originalUsers = users;
const newUsers = originalUsers.filter((s) => s._id !== user._id);
setUsers(newUsers);
try {
await http.delete(`/users/${user._id}`);
} catch (ex) {
if (ex.response && ex.response.status === 404)
toast({
title: "Error",
description: "User May be Already Deleted",
status: "error",
duration: 9000,
isClosable: true,
});
setUsers(originalUsers);
}
};
const handleAdd = async (user) => {
try {
const { data } = await api.post("/users", user, {
headers: localStorage.getItem("token"),
});
setUsers([...users, data]);
} catch (ex) {
toast({
title: "Error",
description: "Submit Unsuccessful",
status: "error",
duration: 9000,
isClosable: true,
});
}
};
const handleEdit = async () => {
const originalUsers = users;
let newUsers = [...users];
const idx = newUsers.findIndex((sys) => sys._id === currentEditUser._id);
newUsers[idx] = { ...currentEditUser };
setUsers(newUsers);
try {
await http.put(`/users/${currentEditUser._id}`, {
email: currentEditUser.email,
});
setCurrentEditUser({ email: "" });
} catch (ex) {
toast({
title: "Error",
description: "Error Updating The User",
status: "error",
duration: 9000,
isClosable: true,
});
setUsers(originalUsers);
setCurrentEditUser({ email: "" });
}
};
const formik = useFormik({
initialValues: {
email: "",
},
validationSchema: Yup.object({
email: Yup.string().label("Email").email().required("Required"),
}),
onSubmit: (values) => {
handleAdd(values);
},
});
return (
<FormikProvider value={formik}>
<Layout>
<>
{isLoggedIn ? (
<>
{/* CRUD Status List */}
<div className="w-full max-w-sm overflow-hidden rounded-lg items-center mx-auto">
<h3 className="text-2xl font-black text-black">New Admin</h3>
<form onSubmit={formik.handleSubmit} className="p-3">
<Stack>
<Text>Email</Text>
<Input
id="email"
name="email"
type="text"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.email}
placeholder="Enter here"
isInvalid={
formik.touched.email && formik.errors.email
? true
: false
}
/>
{formik.touched.email && formik.errors.email ? (
<Alert status="error">
<AlertIcon />
{formik.errors.email}
</Alert>
) : null}
</Stack>
{/* Add */}
<div className="mt-4">
<button
style={{ backgroundColor: "#3747D4" }}
className="px-4 py-2 text-white rounded hover:bg-black focus:outline-none"
type="submit"
>
Add
</button>
</div>
</form>
{users.map((user) => (
<div key={user._id} className="status-items-manage">
<div className="items">
<span className="site-title">{user.name}</span>
<div className="i">
<EditIcon
mr="2"
onClick={() => {
setCurrentEditUser(user);
}}
/>
<DeleteIcon
color="red"
m="2"
onClick={() => {
handleDelete(user);
}}
/>
</div>
</div>
</div>
))}
{/* End */}
{currentEditUser.email ? (
<div className="mt-4">
<Stack>
<h3 className="text-2xl font-black text-black">
Edit User
</h3>
<Stack mt={2}>
<Text>Email</Text>
<Input
placeholder="Enter here"
id="email"
name="email"
type="text"
value={currentEditUser.email}
onChange={(e) =>
setCurrentEditUser({
...currentEditUser,
email: e.target.value,
})
}
/>
</Stack>
</Stack>
{/* Add */}
<div className="mt-4">
<button
onClick={handleEdit}
style={{ backgroundColor: "#3747D4" }}
className="px-4 py-2 text-white rounded hover:bg-black focus:outline-none"
>
Done
</button>
</div>
</div>
) : (
""
)}
</div>
</>
) : (
""
)}
</>
</Layout>
</FormikProvider>
);
}
Example #12
Source File: LoginForm.js From Django-REST-Framework-React-BoilerPlate with MIT License | 4 votes |
// ----------------------------------------------------------------------
export default function LoginForm() {
const dispatch = useDispatch();
const navigate = useNavigate();
const userLogin = useSelector((state) => state.userLogin);
const { error: loginError, loading: loginLoading, userInfo } = userLogin;
const [showPassword, setShowPassword] = useState(false);
const LoginSchema = Yup.object().shape({
email: Yup.string().email('Email must be a valid email address').required('Email is required'),
password: Yup.string().required('Password is required'),
});
const formik = useFormik({
initialValues: {
email: '',
password: '',
},
validationSchema: LoginSchema,
onSubmit: () => {
dispatch(login(values.email, values.password));
},
});
const { errors, touched, values, isSubmitting, handleSubmit, getFieldProps } = formik;
const handleShowPassword = () => {
setShowPassword((show) => !show);
};
useEffect(() => {
if (userInfo) {
navigate('/dashboard/app', { replace: true });
}
}, [navigate, userInfo]);
return (
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<TextField
fullWidth
autoComplete="username"
type="email"
label="Email address"
{...getFieldProps('email')}
error={Boolean(touched.email && errors.email)}
helperText={touched.email && errors.email}
/>
<TextField
fullWidth
autoComplete="current-password"
type={showPassword ? 'text' : 'password'}
label="Password"
{...getFieldProps('password')}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton onClick={handleShowPassword} edge="end">
<Iconify icon={showPassword ? 'eva:eye-fill' : 'eva:eye-off-fill'} />
</IconButton>
</InputAdornment>
),
}}
error={Boolean(touched.password && errors.password)}
helperText={touched.password && errors.password}
/>
</Stack>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ my: 2 }}>
<Link component={RouterLink} variant="subtitle2" to="#" underline="hover">
Forgot password?
</Link>
</Stack>
{loginError ? (
<Alert severity="error">
<AlertTitle>Login Error</AlertTitle>
{loginError}
</Alert>
) : null}
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={loginLoading ? isSubmitting : null}
>
Login
</LoadingButton>
</Form>
</FormikProvider>
);
}
Example #13
Source File: RegisterForm.js From Django-REST-Framework-React-BoilerPlate with MIT License | 4 votes |
// ----------------------------------------------------------------------
export default function RegisterForm() {
const dispatch = useDispatch();
const navigate = useNavigate();
const userLogin = useSelector((state) => state.userLogin);
const { userInfo } = userLogin;
const userRgister = useSelector((state) => state.userRgister);
const { error: registerError, loading: registerLoading } = userRgister;
const [showPassword, setShowPassword] = useState(false);
const RegisterSchema = Yup.object().shape({
firstName: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('First name required'),
lastName: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('Last name required'),
email: Yup.string().email('Email must be a valid email address').required('Email is required'),
password: Yup.string().required('Password is required'),
});
const formik = useFormik({
initialValues: {
firstName: '',
lastName: '',
email: '',
password: '',
},
validationSchema: RegisterSchema,
onSubmit: () => {
dispatch(register(values.firstName, values.lastName, values.email, values.password));
},
});
const { errors, touched, values, handleSubmit, isSubmitting, getFieldProps } = formik;
useEffect(() => {
if (userInfo) {
navigate('/dashboard/app', { replace: true });
}
}, [navigate, userInfo]);
return (
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
<TextField
fullWidth
label="First name"
{...getFieldProps('firstName')}
error={Boolean(touched.firstName && errors.firstName)}
helperText={touched.firstName && errors.firstName}
/>
<TextField
fullWidth
label="Last name"
{...getFieldProps('lastName')}
error={Boolean(touched.lastName && errors.lastName)}
helperText={touched.lastName && errors.lastName}
/>
</Stack>
<TextField
fullWidth
autoComplete="username"
type="email"
label="Email address"
{...getFieldProps('email')}
error={Boolean(touched.email && errors.email)}
helperText={touched.email && errors.email}
/>
<TextField
fullWidth
autoComplete="current-password"
type={showPassword ? 'text' : 'password'}
label="Password"
{...getFieldProps('password')}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton edge="end" onClick={() => setShowPassword((prev) => !prev)}>
<Iconify icon={showPassword ? 'eva:eye-fill' : 'eva:eye-off-fill'} />
</IconButton>
</InputAdornment>
),
}}
error={Boolean(touched.password && errors.password)}
helperText={touched.password && errors.password}
/>
{registerError ? (
<Alert severity="error">
<AlertTitle>Register Error</AlertTitle>
{registerError}
</Alert>
) : null}
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={registerLoading ? isSubmitting : null}
>
Register
</LoadingButton>
</Stack>
</Form>
</FormikProvider>
);
}