Skip to content

Commit

Permalink
feat: further progress getting the edit page to work
Browse files Browse the repository at this point in the history
  • Loading branch information
ob6160 committed Sep 25, 2021
1 parent 2f3f1b1 commit cd05b3d
Show file tree
Hide file tree
Showing 5 changed files with 152 additions and 144 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ node_modules
# Local config
.env
.now
.vscode

build

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"@mapbox/geojson-area": "0.2.2",
"@mapbox/geojson-rewind": "0.5.1",
"@types/jest": "27.0.1",
"@types/lodash": "4.14.174",
"@types/node": "16.9.1",
"@types/react": "17.0.20",
"@types/react-dom": "17.0.9",
Expand Down
286 changes: 144 additions & 142 deletions src/pages/loos/[id]/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,32 @@ import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import { withApollo } from '../../../components/withApollo';
import { NextPage } from 'next';
import { useFindLooById } from '../../../api-client/page';
import {
UpdateLooMutationVariables,
useFindLooByIdQuery,
useUpdateLooMutation,
} from '../../../api-client/graphql';
import { cloneDeep } from '@apollo/client/utilities';
import { merge, uniqBy } from 'lodash';
import Notification from '../../../components/Notification';
import { css } from '@emotion/react';

const MapLoader = () => <p>Loading map...</p>;

const EditPage = (props: { match: { params: { id: any } } }) => {
const EditPage = (props: { match: { params: { id?: string } } }) => {
const router = useRouter();
const { id: selectedLooId } = router.query;

// const {
// isValidating: loadingLooData,
// data: looData,
// error: looError,
// } = useSWR(
// [FIND_LOO_BY_ID_QUERY, JSON.stringify({ id: selectedLooId })],
// {
// revalidateOnFocus: false,
// }
// );
const {
data: looData,
error: looError,
loading: loadingLooData,
} = useFindLooByIdQuery({ variables: { id: selectedLooId as string } });

const [mapState, setMapState] = useMapState();

// const looLocation = (looData && looData.loo.location) || null;
const looLocation = (looData && looData.loo.location) || null;

const LooMap = React.useMemo(
() =>
Expand All @@ -50,11 +55,11 @@ const EditPage = (props: { match: { params: { id: any } } }) => {
);

// set the map position to the loo location
// React.useEffect(() => {
// if (looLocation) {
// setMapState({ center: looLocation });
// }
// }, [looLocation, setMapState]);
React.useEffect(() => {
if (looLocation) {
setMapState({ center: looLocation });
}
}, [looLocation, setMapState]);

const { data } = useNearbyLoos({
lat: mapState.center.lat,
Expand All @@ -63,96 +68,89 @@ const EditPage = (props: { match: { params: { id: any } } }) => {
});

// local state mapCenter to get fix issues with react-leaflet not being stateless and lat lng rounding issues
const [mapCenter, setMapCenter] = useState();

const [initialData, setInitialData] = useState();

// useEffect(() => {
// if (!looData) {
// return;
// }

// const toilet = cloneDeep(merge({}, { active: null }, looData.loo));
// setMapCenter(toilet.location);

// // keep track of defaults so we only submit new information
// setInitialData({
// loo: toilet,
// center: {
// lat: toilet.location.lat,
// lng: toilet.location.lng,
// },
// });
// }, [looData]);

// const [
// updateLoo,
// { loading: saveLoading, data: saveData, error: saveError },
// ] = useMutation(UPDATE_LOO_MUTATION);

// const save = async (formData: { id: any; }) => {
// formData.id = looData.loo.id;

// try {
// const data = await updateLoo(formData);

// // update cached query
// mutate(
// [
// FIND_LOO_BY_ID_QUERY,
// JSON.stringify({ id: data.submitReport.loo.id }),
// ],
// {
// loo: data.submitReport.loo,
// }
// );
// } catch (err) {
// console.error('save error', err);
// }
// };

// if (saveData) {
// // redirect to updated toilet entry page
// router.push(`/loos/${saveData.submitReport.loo.id}?message=updated`)
// }

// if (loadingLooData || !looData || !initialData || looError) {
// return (
// <PageLayout>
// <Box
// my={4}
// mx="auto"
// css={css`
// max-width: 360px; /* fallback */
// max-width: fit-content;
// `}
// >
// <Notification>
// {looError ? 'Error fetching toilet data' : 'Fetching Toilet Data'}
// </Notification>
// </Box>
// </PageLayout>
// );
// }
const [mapCenter, setMapCenter] = useState({ lat: 0, lng: 0 });

const [initialData, setInitialData] = useState({
loo: null,
center: { lat: 0, lng: 0 },
});

useEffect(() => {
if (!looData) {
return;
}

const toilet = cloneDeep(merge({}, { active: null }, looData.loo));
setMapCenter(toilet.location);

// keep track of defaults so we only submit new information
setInitialData({
loo: toilet,
center: {
lat: toilet.location.lat,
lng: toilet.location.lng,
},
});
}, [looData]);

const [
updateLooMutation,
{ data: saveData, loading: saveLoading, error: saveError },
] = useUpdateLooMutation();

const save = async (formData: UpdateLooMutationVariables) => {
formData.id = looData.loo.id;

try {
const data = await updateLooMutation({ variables: { ...formData } });
useUpdateLooMutation;
} catch (err) {
console.error('save error', err);
}
};

if (saveData) {
// redirect to updated toilet entry page
router.push(`/loos/${saveData.submitReport.loo.id}?message=updated`);
}

if (loadingLooData || !looData || !initialData || looError) {
return (
<PageLayout>
<Box
my={4}
mx="auto"
css={css`
max-width: 360px; /* fallback */
max-width: fit-content;
`}
>
<Notification>
{looError ? 'Error fetching toilet data' : 'Fetching Toilet Data'}
</Notification>
</Box>
</PageLayout>
);
}

// redirect to index if loo is not active (i.e. removed)
// if (looData && !looData.loo.active) {
// router.push('/');
// }
if (looData && !looData.loo.active) {
router.push('/');
}

// const getLoosToDisplay = () => {
// let activeLoo;
const getLoosToDisplay = () => {
let activeLoo;

// if (looData) {
// activeLoo = {
// ...looData.loo,
// isHighlighted: true,
// };
// }
if (looData) {
activeLoo = {
...looData.loo,
isHighlighted: true,
};
}

// // only return the active loos once (activeLoo must be first in array)
// return uniqBy([activeLoo, ...data], 'id').filter(Boolean);
// };
// only return the active loos once (activeLoo must be first in array)
return uniqBy([activeLoo, ...data], 'id').filter(Boolean);
};

return (
<PageLayout>
Expand All @@ -162,7 +160,7 @@ const EditPage = (props: { match: { params: { id: any } } }) => {
</Head>

<Box display="flex" height="40vh">
{/* <LooMap
<LooMap
loos={getLoosToDisplay()}
center={mapState.center}
zoom={mapState.zoom}
Expand All @@ -173,50 +171,54 @@ const EditPage = (props: { match: { params: { id: any } } }) => {
showCrosshair
controlsOffset={20}
withAccessibilityOverlays={false}
onViewportChanged={(mapPosition: { center: (prevState: undefined) => undefined; }) => {
onViewportChanged={(mapPosition: {
center: (prevState: undefined) => undefined;
}) => {
setMapCenter(mapPosition.center);
}}
/> */}
/>
</Box>

<Spacer mt={4} />
{/*
<EntryForm
title="Edit This Toilet"
loo={initialData.loo}
center={mapCenter}
saveLoading={saveLoading}
saveError={saveError}
onSubmit={save}
>
{({ isDirty }) => (
<Box display="flex" flexDirection="column" alignItems="center">
<Button
type="submit"
disabled={!isDirty}
css={{
width: '100%',
}}
data-testid="update-toilet-button"
>
Update the toilet
</Button>
<Spacer mt={2} />
<Button
as={Link}
href={`/loos/${selectedLooId}/remove`}
css={{
width: '100%',
}}
data-testid="remove-toilet-button"
>
Remove the toilet
</Button>
</Box>
)}
</EntryForm> */}

{initialData?.loo && (
<EntryForm
title="Edit This Toilet"
loo={initialData.loo}
center={mapCenter}
saveLoading={saveLoading}
saveError={saveError}
onSubmit={save}
>
{({ isDirty }) => (
<Box display="flex" flexDirection="column" alignItems="center">
<Button
type="submit"
disabled={!isDirty}
css={{
width: '100%',
}}
data-testid="update-toilet-button"
>
Update the toilet
</Button>

<Spacer mt={2} />

<Button
as={Link}
href={`/loos/${selectedLooId}/remove`}
css={{
width: '100%',
}}
data-testid="remove-toilet-button"
>
Remove the toilet
</Button>
</Box>
)}
</EntryForm>
)}
</>
</PageLayout>
);
Expand Down
3 changes: 1 addition & 2 deletions src/pages/loos/add.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@ import useNearbyLoos from '../../components/useNearbyLoos';

import config from '../../config';
import dynamic from 'next/dynamic';
import Router, { useRouter } from 'next/router';
import { useRouter } from 'next/router';
import { NextPage } from 'next';
import { withApollo } from '../../components/withApollo';
import {
UpdateLooMutationVariables,
useFindLooByIdQuery,
useUpdateLooMutation,
} from '../../api-client/graphql';

Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1926,6 +1926,11 @@
dependencies:
"@types/geojson" "*"

"@types/lodash@4.14.174":
version "4.14.174"
resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.174.tgz#b4b06b6eced9850eed6b6a8f1abdd0f5192803c1"
integrity sha512-KMBLT6+g9qrGXpDt7ohjWPUD34WA/jasrtjTEHStF0NPdEwJ1N9SZ+4GaMVDeuk/y0+X5j9xFm6mNiXS7UoaLQ==

"@types/long@^4.0.0":
version "4.0.1"
resolved "https://registry.npmjs.org/@types/long/-/long-4.0.1.tgz"
Expand Down

0 comments on commit cd05b3d

Please sign in to comment.