import type { Action, Actions } from 'easy-peasy'; import { action, createContextStore, useStoreActions } from 'easy-peasy'; import type { FormikHelpers } from 'formik'; import { Form, Formik } from 'formik'; import { useEffect, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import tw from 'twin.macro'; import { object, string } from 'yup'; import type { Location } from '@/api/admin/locations/getLocations'; import getLocation from '@/api/admin/locations/getLocation'; import updateLocation from '@/api/admin/locations/updateLocation'; import AdminBox from '@/components/admin/AdminBox'; import AdminContentBlock from '@/components/admin/AdminContentBlock'; import LocationDeleteButton from '@/components/admin/locations/LocationDeleteButton'; 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 FlashMessageRender from '@/components/FlashMessageRender'; import type { ApplicationStore } from '@/state'; interface ctx { location: Location | undefined; setLocation: Action; } export const Context = createContextStore({ location: undefined, setLocation: action((state, payload) => { state.location = payload; }), }); interface Values { short: string; long: string; } const EditInformationContainer = () => { const navigate = useNavigate(); const { clearFlashes, clearAndAddHttpError } = useStoreActions( (actions: Actions) => actions.flashes, ); const location = Context.useStoreState(state => state.location); const setLocation = Context.useStoreActions(actions => actions.setLocation); if (location === undefined) { return <>; } const submit = ({ short, long }: Values, { setSubmitting }: FormikHelpers) => { clearFlashes('location'); updateLocation(location.id, short, long) .then(() => setLocation({ ...location, short, long })) .catch(error => { console.error(error); clearAndAddHttpError({ key: 'location', error }); }) .then(() => setSubmitting(false)); }; return ( {({ isSubmitting, isValid }) => ( <>
navigate('/admin/locations')} />
)}
); }; const LocationEditContainer = () => { const params = useParams<'id'>(); const { clearFlashes, clearAndAddHttpError } = useStoreActions( (actions: Actions) => actions.flashes, ); const [loading, setLoading] = useState(true); const location = Context.useStoreState(state => state.location); const setLocation = Context.useStoreActions(actions => actions.setLocation); useEffect(() => { clearFlashes('location'); getLocation(Number(params.id)) .then(location => setLocation(location)) .catch(error => { console.error(error); clearAndAddHttpError({ key: 'location', error }); }) .then(() => setLoading(false)); }, []); if (loading || location === undefined) { return (
); } return (

{location.short}

{(location.long || '').length < 1 ? (

No long name

) : (

{location.long}

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