All files / app/features/communities/events EditEventPage.tsx

86.36% Statements 38/44
78.12% Branches 25/32
85.71% Functions 6/7
86.04% Lines 37/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 1291x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x     1x 1x 1x 1x   11x           5x 18x 18x 18x   18x                       18x   18x         18x   3x                                 3x       3x     3x 3x       3x         3x     3x       18x                                                              
import { styled } from "@mui/material";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import Alert from "components/Alert";
import Button from "components/Button";
import CenteredSpinner from "components/CenteredSpinner/CenteredSpinner";
import HeaderButton from "components/HeaderButton";
import HtmlMeta from "components/HtmlMeta";
import { BackIcon } from "components/Icons";
import NotFoundPage from "features/NotFoundPage";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { COMMUNITIES, GLOBAL, PROFILE } from "i18n/namespaces";
import { useRouter } from "next/router";
import { service } from "service";
import type { UpdateEventInput } from "service/events";
import { theme } from "theme";
import { sendNativeBack, useIsNativeEmbed } from "utils/nativeLink";
 
import { Event } from "../../../proto/events_pb";
import { eventsRoute, routeToEvent } from "../../../routes";
import { communityEventsBaseKey, eventKey } from "../../queryKeys";
import EventForm, { CreateEventVariables } from "./EventForm";
import { useEvent } from "./hooks";
 
const StyledBackButton = styled(HeaderButton)(() => ({
  width: "2.5rem",
  height: "2.5rem",
  marginTop: theme.spacing(2),
}));
 
export default function EditEventPage({ eventId }: { eventId: number }) {
  const { t } = useTranslation([GLOBAL, COMMUNITIES, PROFILE]);
  const router = useRouter();
  const isNativeEmbed = useIsNativeEmbed();
 
  const handleBackClick = () => {
    if (isNativeEmbed) {
      sendNativeBack();
      return;
    }
    if (window.history.length > 1) {
      router.back();
    } else {
      router.push(eventsRoute);
    }
  };
 
  const { data: event, error: eventError, isLoading: isEventLoading, isValidEventId } = useEvent({ eventId });
 
  const queryClient = useQueryClient();
  const {
    mutate: updateEvent,
    error,
    isPending,
  } = useMutation<Event.AsObject, RpcError, CreateEventVariables, { parentCommunityId?: number }>({
    mutationFn: (data) => {
      const updateEventInput: UpdateEventInput = {
        eventId,
        title: data.dirtyFields.title ? data.title : undefined,
        content: data.dirtyFields.content ? data.content : undefined,
        photoKey: data.dirtyFields.eventImage ? data.eventImage : undefined,
        startTime:
          data.dirtyFields.startDate || data.dirtyFields.startTime
            ? data.startDate.toPlainDateTime(data.startTime)
            : undefined,
        endTime:
          data.dirtyFields.endDate || data.dirtyFields.endTime ? data.endDate.toPlainDateTime(data.endTime) : undefined,
        shouldNotify: data.dirtyFields.shouldNotify,
        address: data.dirtyFields.location ? data.location.name : undefined,
        lat: data.dirtyFields.location ? data.location.location.lat : undefined,
        lng: data.dirtyFields.location ? data.location.location.lng : undefined,
      };
 
      return service.events.updateEvent(updateEventInput);
    },
 
    onMutate({ parentCommunityId }) {
      return { parentCommunityId };
    },
    onSuccess(updatedEvent, _, context) {
      queryClient.setQueryData<Event.AsObject>(eventKey(eventId), updatedEvent);
      queryClient.invalidateQueries({
        queryKey: eventKey(eventId),
        refetchType: "none",
      });
      queryClient.invalidateQueries({
        queryKey: [
          context?.parentCommunityId ? [communityEventsBaseKey, context.parentCommunityId] : communityEventsBaseKey,
        ],
      });
      router.push(routeToEvent(updatedEvent.eventId, updatedEvent.slug));
    },
    onSettled() {
      window.scroll({ top: 0, behavior: "smooth" });
    },
  });
 
  return isValidEventId ? (
    eventError ? (
      <Alert severity="error">{eventError.message}</Alert>
    ) : isEventLoading ? (
      <CenteredSpinner />
    ) : (
      <>
        <HtmlMeta title={t("communities:edit_event")} />
        <StyledBackButton onClick={handleBackClick} aria-label={t("communities:previous_page")}>
          <BackIcon />
        </StyledBackButton>
        <EventForm
          error={error}
          event={event}
          isMutationLoading={isPending}
          mutate={updateEvent}
          title={t("communities:edit_event")}
          isEdit
        >
          {({ isMutationLoading }) => (
            <Button loading={isMutationLoading} type="submit" sx={{ justifySelf: "start" }}>
              {t("global:update")}
            </Button>
          )}
        </EventForm>
      </>
    )
  ) : (
    <NotFoundPage />
  );
}