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

97.5% Statements 39/40
77.77% Branches 21/27
100% Functions 6/6
97.5% Lines 39/40

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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 1471x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x   1x         1x 1x   1x 23x 23x 23x             23x   23x         23x               3x 3x 3x         3x           3x                               3x 1x     2x             3x       3x     3x       3x     3x         3x     3x         23x                               33x                              
import { CircularProgress } from "@material-ui/core";
import Alert from "components/Alert";
import Button from "components/Button";
import HtmlMeta from "components/HtmlMeta";
import NotFoundPage from "features/NotFoundPage";
import { communityEventsBaseKey, eventKey } from "features/queryKeys";
import type { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { COMMUNITIES, GLOBAL } from "i18n/namespaces";
import { useRouter } from "next/router";
import { Event } from "proto/events_pb";
import { useMutation, useQueryClient } from "react-query";
import { routeToEvent } from "routes";
import { service } from "service";
import type { UpdateEventInput } from "service/events";
import dayjs, { TIME_FORMAT } from "utils/dayjs";
 
import EventForm, {
  CreateEventVariables,
  useEventFormStyles,
} from "./EventForm";
import { useEvent } from "./hooks";
 
export default function EditEventPage({ eventId }: { eventId: number }) {
  const { t } = useTranslation([GLOBAL, COMMUNITIES]);
  const classes = useEventFormStyles();
  const router = useRouter();
 
  const {
    data: event,
    error: eventError,
    isLoading: isEventLoading,
    isValidEventId,
  } = useEvent({ eventId });
 
  const queryClient = useQueryClient();
  const {
    mutate: updateEvent,
    error,
    isLoading,
  } = useMutation<
    Event.AsObject,
    RpcError,
    CreateEventVariables,
    { parentCommunityId?: number }
  >(
    (data) => {
      let updateEventInput: UpdateEventInput;
      const startTime = dayjs(data.startTime, TIME_FORMAT);
      const endTime = dayjs(data.endTime, TIME_FORMAT);
      const finalStartDate = data.startDate
        .startOf("day")
        .add(startTime.get("hour"), "hour")
        .add(startTime.get("minute"), "minute")
        .toDate();
      const finalEndDate = data.endDate
        .startOf("day")
        .add(endTime.get("hour"), "hour")
        .add(endTime.get("minute"), "minute")
        .toDate();
 
      updateEventInput = {
        eventId,
        isOnline: data.isOnline,
        title: data.dirtyFields.title ? data.title : undefined,
        content: data.dirtyFields.content ? data.content : undefined,
        photoKey: data.dirtyFields.eventImage ? data.eventImage : undefined,
        startTime:
          data.dirtyFields.startTime || data.dirtyFields.startDate
            ? finalStartDate
            : undefined,
        endTime:
          data.dirtyFields.endTime || data.dirtyFields.endDate
            ? finalEndDate
            : undefined,
      };
 
      if (data.isOnline) {
        updateEventInput = Object.assign(updateEventInput, {
          link: data.dirtyFields.link ? data.link : undefined,
        });
      } else Iif (data.dirtyFields.location) {
        updateEventInput = Object.assign(updateEventInput, {
          address: data.location.name,
          lat: data.location.location.lat,
          lng: data.location.location.lng,
        });
      }
      return service.events.updateEvent(updateEventInput);
    },
    {
      onMutate({ parentCommunityId }) {
        return { parentCommunityId };
      },
      onSuccess(updatedEvent, _, context) {
        queryClient.setQueryData<Event.AsObject>(
          eventKey(eventId),
          updatedEvent
        );
        queryClient.invalidateQueries(eventKey(eventId), {
          refetchActive: false,
        });
        queryClient.invalidateQueries(
          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 ? (
      <CircularProgress />
    ) : (
      <>
        <HtmlMeta title={t("communities:edit_event")} />
        <EventForm
          error={error}
          event={event}
          isMutationLoading={isLoading}
          mutate={updateEvent}
          title={t("communities:edit_event")}
        >
          {({ isMutationLoading }) => (
            <Button
              className={classes.submitButton}
              loading={isMutationLoading}
              type="submit"
            >
              {t("global:update")}
            </Button>
          )}
        </EventForm>
      </>
    )
  ) : (
    <NotFoundPage />
  );
}