import { action, Action, Actions, createContextStore, useStoreActions } from 'easy-peasy'; import { Form, Formik, FormikHelpers } from 'formik'; import React, { useEffect, useState } from 'react'; import { useHistory } from 'react-router'; import { useRouteMatch } from 'react-router-dom'; import tw from 'twin.macro'; import { object, string } from 'yup'; import { Role } from '@/api/admin/roles/getRoles'; import getRole from '@/api/admin/roles/getRole'; import updateRole from '@/api/admin/roles/updateRole'; import FlashMessageRender from '@/components/FlashMessageRender'; import AdminBox from '@/components/admin/AdminBox'; import AdminContentBlock from '@/components/admin/AdminContentBlock'; import RoleDeleteButton from '@/components/admin/roles/RoleDeleteButton'; import Button from '@/components/elements/Button'; import Field from '@/components/elements/Field'; import Spinner from '@/components/elements/Spinner'; import SpinnerOverlay from '@/components/elements/SpinnerOverlay'; import { ApplicationStore } from '@/state'; interface ctx { role: Role | undefined; setRole: Action; } export const Context = createContextStore({ role: undefined, setRole: action((state, payload) => { state.role = payload; }), }); interface Values { name: string; description: string; } const EditInformationContainer = () => { const history = useHistory(); const { clearFlashes, clearAndAddHttpError } = useStoreActions((actions: Actions) => actions.flashes); const role = Context.useStoreState(state => state.role); const setRole = Context.useStoreActions(actions => actions.setRole); if (role === undefined) { return ( <> ); } const submit = ({ name, description }: Values, { setSubmitting }: FormikHelpers) => { clearFlashes('role'); updateRole(role.id, name, description) .then(() => setRole({ ...role, name, description })) .catch(error => { console.error(error); clearAndAddHttpError({ key: 'role', error }); }) .then(() => setSubmitting(false)); }; return ( { ({ isSubmitting, isValid }) => (
history.push('/admin/roles')} />
) }
); }; const RoleEditContainer = () => { const match = useRouteMatch<{ id?: string }>(); const { clearFlashes, clearAndAddHttpError } = useStoreActions((actions: Actions) => actions.flashes); const [ loading, setLoading ] = useState(true); const role = Context.useStoreState(state => state.role); const setRole = Context.useStoreActions(actions => actions.setRole); useEffect(() => { clearFlashes('role'); getRole(Number(match.params?.id)) .then(role => setRole(role)) .catch(error => { console.error(error); clearAndAddHttpError({ key: 'role', error }); }) .then(() => setLoading(false)); }, []); if (loading || role === undefined) { return (
); } return (

{role.name}

{ (role.description || '').length < 1 ?

No description

:

{role.description}

}
); }; export default () => { return ( ); };