chore: bump @trpc/* and @tanstack/react-query (#13335)

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: zomars <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Benny Joo <[email protected]>
Co-authored-by: Carina Wollendorfer <[email protected]>
Co-authored-by: Gergő Móricz <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
183 files changed
+1203 -1013

No files matched your search

@@ -71,7 +71,7 @@ export default function OmniInstallAppButton({
return (
<Button
loading={mutation.isLoading}
loading={mutation.isPending}
color="secondary"
className="[@media(max-width:260px)]:w-full [@media(max-width:260px)]:justify-center"
StartIcon={Plus}
+54 -51
View File
@@ -32,64 +32,67 @@ function useAddAppMutation(_type: App["type"] | null, allOptions?: UseAddAppMuta
AddAppMutationData,
Error,
{ type?: App["type"]; variant?: string; slug?: string; isOmniInstall?: boolean; teamId?: number } | ""
>(async (variables) => {
let type: string | null | undefined;
let isOmniInstall;
const teamId = variables && variables.teamId ? variables.teamId : undefined;
if (variables === "") {
type = _type;
} else {
isOmniInstall = variables.isOmniInstall;
type = variables.type;
}
if (type?.endsWith("_other_calendar")) {
type = type.split("_other_calendar")[0];
}
>({
...options,
mutationFn: async (variables) => {
let type: string | null | undefined;
let isOmniInstall;
const teamId = variables && variables.teamId ? variables.teamId : undefined;
if (variables === "") {
type = _type;
} else {
isOmniInstall = variables.isOmniInstall;
type = variables.type;
}
if (type?.endsWith("_other_calendar")) {
type = type.split("_other_calendar")[0];
}
if (options?.installGoogleVideo && type !== "google_calendar")
throw new Error("Could not install Google Meet");
if (options?.installGoogleVideo && type !== "google_calendar")
throw new Error("Could not install Google Meet");
const state: IntegrationOAuthCallbackState = {
returnTo:
returnTo ||
WEBAPP_URL +
getInstalledAppPath(
{ variant: variables && variables.variant, slug: variables && variables.slug },
location.search
),
...(type === "google_calendar" && { installGoogleVideo: options?.installGoogleVideo }),
...(teamId && { teamId }),
};
const state: IntegrationOAuthCallbackState = {
returnTo:
returnTo ||
WEBAPP_URL +
getInstalledAppPath(
{ variant: variables && variables.variant, slug: variables && variables.slug },
location.search
),
...(type === "google_calendar" && { installGoogleVideo: options?.installGoogleVideo }),
...(teamId && { teamId }),
};
const stateStr = encodeURIComponent(JSON.stringify(state));
const searchParams = `?state=${stateStr}${teamId ? `&teamId=${teamId}` : ""}`;
const stateStr = encodeURIComponent(JSON.stringify(state));
const searchParams = `?state=${stateStr}${teamId ? `&teamId=${teamId}` : ""}`;
const res = await fetch(`/api/integrations/${type}/add${searchParams}`);
const res = await fetch(`/api/integrations/${type}/add${searchParams}`);
if (!res.ok) {
const errorBody = await res.json();
throw new Error(errorBody.message || "Something went wrong");
}
if (!res.ok) {
const errorBody = await res.json();
throw new Error(errorBody.message || "Something went wrong");
}
const json = await res.json();
const externalUrl = /https?:\/\//.test(json.url) && !json.url.startsWith(window.location.origin);
if (!isOmniInstall) {
gotoUrl(json.url, json.newTab);
return { setupPending: externalUrl || json.url.endsWith("/setup") };
}
// Skip redirection only if it is an OmniInstall and redirect URL isn't of some other origin
// This allows installation of apps like Stripe to still redirect to their authentication pages.
// Check first that the URL is absolute, then check that it is of different origin from the current.
if (externalUrl) {
// TODO: For Omni installation to authenticate and come back to the page where installation was initiated, some changes need to be done in all apps' add callbacks
gotoUrl(json.url, json.newTab);
return { setupPending: externalUrl };
}
const json = await res.json();
const externalUrl = /https?:\/\//.test(json.url) && !json.url.startsWith(window.location.origin);
if (!isOmniInstall) {
gotoUrl(json.url, json.newTab);
return { setupPending: externalUrl || json.url.endsWith("/setup") };
}
// Skip redirection only if it is an OmniInstall and redirect URL isn't of some other origin
// This allows installation of apps like Stripe to still redirect to their authentication pages.
// Check first that the URL is absolute, then check that it is of different origin from the current.
if (externalUrl) {
// TODO: For Omni installation to authenticate and come back to the page where installation was initiated, some changes need to be done in all apps' add callbacks
gotoUrl(json.url, json.newTab);
return { setupPending: externalUrl };
}
return { setupPending: externalUrl || json.url.endsWith("/setup") };
}, options);
},
});
return mutation;
}
@@ -121,7 +121,7 @@ function AlbySetupPage(props: IAlbySetupProps) {
});
}, [credentialId, props.clientId, props.clientSecret, saveKeysMutation]);
if (integrations.isLoading) {
if (integrations.isPending) {
return <div className="absolute z-50 flex h-screen w-full items-center bg-gray-200" />;
}
@@ -15,22 +15,26 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
const [selectedProject, setSelectedProject] = useState<undefined | { label: string; value: string }>();
const { data } = trpc.viewer.appBasecamp3.projects.useQuery();
const setProject = trpc.viewer.appBasecamp3.projectMutation.useMutation();
useEffect(() => {
setSelectedProject({
value: data?.projects.currentProject,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
label: data?.projects?.find((project: any) => project.id === data?.currentProject)?.name,
});
setProjects(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data?.projects?.map((project: any) => {
return {
value: project.id,
label: project.name,
};
})
);
}, [data]);
useEffect(
function refactorMeWithoutEffect() {
setSelectedProject({
value: data?.projects.currentProject,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
label: data?.projects?.find((project: any) => project.id === data?.currentProject)?.name,
});
setProjects(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data?.projects?.map((project: any) => {
return {
value: project.id,
label: project.name,
};
})
);
},
[data]
);
return (
<AppCard
+3 -3
View File
@@ -34,7 +34,7 @@ export const InstallAppButtonWithoutPlanCheck = (
onClick: () => {
mutation.mutate({ type: props.type });
},
loading: mutation.isLoading,
loading: mutation.isPending,
})}
</>
);
@@ -56,10 +56,10 @@ export const InstallAppButton = (
disableInstall?: boolean;
} & InstallAppButtonProps
) => {
const { isLoading: isUserLoading, data: user } = trpc.viewer.me.useQuery();
const { isPending: isUserLoading, data: user } = trpc.viewer.me.useQuery();
const router = useRouter();
const proProtectionElementRef = useRef<HTMLDivElement | null>(null);
const { isLoading: isTeamPlanStatusLoading, hasTeamPlan } = useHasTeamPlan();
const { isPending: isTeamPlanStatusLoading, hasTeamPlan } = useHasTeamPlan();
useEffect(() => {
const el = proProtectionElementRef.current;
@@ -11,7 +11,7 @@ export default function InstallAppButton(props: InstallAppButtonProps) {
onClick() {
mutation.mutate("");
},
loading: mutation.isLoading,
loading: mutation.isPending,
})}
</>
);
@@ -9,7 +9,7 @@ export default function InstallAppButton(props: InstallAppButtonProps) {
onClick() {
mutation.mutate("");
},
loading: mutation.isLoading,
loading: mutation.isPending,
})}
</>
);
@@ -23,15 +23,15 @@ export const SearchDialog = (props: ISearchDialog) => {
const [nextOffset, setNextOffset] = useState<number>(0);
const [keyword, setKeyword] = useState<string>("");
const { isOpenDialog, setIsOpenDialog } = props;
const [isLoading, setIsLoading] = useState(false);
const [isPending, setIsPending] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [selectedMode, setSelectedMode] = useState<Mode>(MODE_SEARCH);
const searchGiphy = async (keyword: string, offset: number) => {
if (isLoading) {
if (isPending) {
return;
}
setIsLoading(true);
setIsPending(true);
setErrorMessage("");
const res = await fetch("/api/integrations/giphy/search", {
method: "POST",
@@ -53,15 +53,15 @@ export const SearchDialog = (props: ISearchDialog) => {
setErrorMessage("No Result found");
}
}
setIsLoading(false);
setIsPending(false);
return null;
};
const getGiphyByUrl = async (url: string) => {
if (isLoading) {
if (isPending) {
return;
}
setIsLoading(true);
setIsPending(true);
setErrorMessage("");
const res = await fetch("/api/integrations/giphy/get", {
method: "POST",
@@ -81,7 +81,7 @@ export const SearchDialog = (props: ISearchDialog) => {
setErrorMessage("No Result found");
}
}
setIsLoading(false);
setIsPending(false);
return null;
};
@@ -139,14 +139,14 @@ export const SearchDialog = (props: ISearchDialog) => {
}}
/>
</div>
<Button type="submit" tabIndex={-1} color="secondary" loading={isLoading}>
<Button type="submit" tabIndex={-1} color="secondary" loading={isPending}>
{t("search")}
</Button>
</form>
{gifImage && (
<div className="flex flex-col items-center space-x-2 space-y-2 pt-3 rtl:space-x-reverse">
<div className="bg-subtle flex w-full items-center justify-center">
{isLoading ? (
{isPending ? (
<div className="flex h-[200px] w-full items-center justify-center bg-gray-400 pb-3 pt-3">
<svg
className={classNames("mx-4 h-5 w-5 animate-spin", "text-inverted dark:text-emphasis")}
@@ -182,7 +182,7 @@ export const SearchDialog = (props: ISearchDialog) => {
size="sm"
color="secondary"
type="button"
loading={isLoading}
loading={isPending}
onClick={() => searchGiphy(keyword, nextOffset)}>
Shuffle
</Button>
@@ -59,7 +59,7 @@ export default function MakeSetup({ inviteLink }: InferGetServerSidePropsType<ty
setNewApiKeys({ ...newApiKeys, [teamId || ""]: apiKey });
}
if (integrations.isLoading) {
if (integrations.isPending) {
return <div className="bg-emphasis absolute z-50 flex h-screen w-full items-center" />;
}
@@ -27,7 +27,7 @@ export default function PayPalSetup() {
},
});
if (integrations.isLoading) {
if (integrations.isPending) {
return <div className="absolute z-50 flex h-screen w-full items-center bg-gray-200" />;
}
@@ -147,7 +147,7 @@ function NewFormDialog({ appUrl }: { appUrl: string }) {
</div>
<DialogFooter showDivider className="mt-12">
<DialogClose />
<Button loading={mutation.isLoading} data-testid="add-form" type="submit">
<Button loading={mutation.isPending} data-testid="add-form" type="submit">
{t("continue")}
</Button>
</DialogFooter>
@@ -234,7 +234,7 @@ function Dialogs({
<RoutingFormEmbedDialog />
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<ConfirmationDialogContent
isLoading={deleteMutation.isLoading}
isPending={deleteMutation.isPending}
variety="danger"
title={t("delete_form")}
confirmBtnText={t("delete_form_action")}
@@ -264,12 +264,12 @@ const actionsCtx = createContext({
_delete: {
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onAction: (_arg: { routingForm: RoutingForm | null }) => {},
isLoading: false,
isPending: false,
},
toggle: {
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onAction: (_arg: { routingForm: RoutingForm | null; checked: boolean }) => {},
isLoading: false,
isPending: false,
},
});
@@ -332,7 +332,7 @@ export function FormActionsProvider({ appUrl, children }: { appUrl: string; chil
setDeleteDialogOpen(true);
setDeleteDialogFormId(routingForm.id);
},
isLoading: false,
isPending: false,
},
toggle: {
onAction: ({ routingForm, checked }) => {
@@ -344,7 +344,7 @@ export function FormActionsProvider({ appUrl, children }: { appUrl: string; chil
disabled: !checked,
});
},
isLoading: toggleMutation.isLoading,
isPending: toggleMutation.isPending,
},
}}>
{children}
@@ -446,7 +446,7 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
},
_delete: {
onClick: () => _delete.onAction({ routingForm }),
loading: _delete.isLoading,
loading: _delete.isPending,
},
create: {
onClick: () => openModal({ action: "new", target: "" }),
@@ -479,7 +479,7 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
</div>
);
},
loading: toggle.isLoading,
loading: toggle.isPending,
},
};
@@ -65,7 +65,7 @@ const Actions = ({
}: {
form: RoutingFormWithResponseCount;
mutation: {
isLoading: boolean;
isPending: boolean;
};
}) => {
const { t } = useLocale();
@@ -218,7 +218,7 @@ const Actions = ({
</FormActionsDropdown>
</div>
<VerticalDivider />
<Button data-testid="update-form" loading={mutation.isLoading} type="submit" color="primary">
<Button data-testid="update-form" loading={mutation.isPending} type="submit" color="primary">
{t("save")}
</Button>
</div>
@@ -518,7 +518,7 @@ function SingleForm({ form, appUrl, Page }: SingleFormComponentProps) {
}
export default function SingleFormWrapper({ form: _form, ...props }: SingleFormComponentProps) {
const { data: form, isLoading } = trpc.viewer.appRoutingForms.formQuery.useQuery(
const { data: form, isPending } = trpc.viewer.appRoutingForms.formQuery.useQuery(
{ id: _form.id },
{
initialData: _form,
@@ -527,7 +527,7 @@ export default function SingleFormWrapper({ form: _form, ...props }: SingleFormC
);
const { t } = useLocale();
if (isLoading) {
if (isPending) {
// It shouldn't be possible because we are passing the data from SSR to it as initialData. So, no need for skeleton here
return null;
}
@@ -34,7 +34,7 @@ type QueryBuilderUpdatedConfig = typeof QueryBuilderInitialConfig & { fields: Co
const Result = ({ formId, jsonLogicQuery }: { formId: string; jsonLogicQuery: JsonLogicQuery | null }) => {
const { t } = useLocale();
const { isLoading, status, data, isFetching, error, isFetchingNextPage, hasNextPage, fetchNextPage } =
const { isPending, status, data, isFetching, error, isFetchingNextPage, hasNextPage, fetchNextPage } =
trpc.viewer.appRoutingForms.report.useInfiniteQuery(
{
formId: formId,
@@ -57,7 +57,7 @@ const Result = ({ formId, jsonLogicQuery }: { formId: string; jsonLogicQuery: Js
const headers = useRef<string[] | null>(null);
if (!isLoading && !data) {
if (!isPending && !data) {
return <div>Error loading report {error?.message} </div>;
}
headers.current = (data?.pages && data?.pages[0]?.headers) || headers.current;
@@ -81,7 +81,7 @@ const Result = ({ formId, jsonLogicQuery }: { formId: string; jsonLogicQuery: Js
</th>
))}
</tr>
{!isLoading &&
{!isPending &&
data?.pages.map((page) => {
return page.responses?.map((responses, rowIndex) => {
const isLastRow = page.responses.length - 1 === rowIndex;
@@ -113,7 +113,7 @@ const Result = ({ formId, jsonLogicQuery }: { formId: string; jsonLogicQuery: Js
});
})}
</table>
{isLoading ? <div className="text-default p-2">{t("loading")}</div> : ""}
{isPending ? <div className="text-default p-2">{t("loading")}</div> : ""}
{hasNextPage && (
<Button
type="button"
@@ -153,7 +153,7 @@ function RoutingForm({ form, profile, ...restProps }: Props) {
<div className="mt-4 flex justify-end space-x-2 rtl:space-x-reverse">
<Button
className="dark:bg-darkmodebrand dark:text-darkmodebrandcontrast dark:hover:border-darkmodebrandcontrast dark:border-transparent"
loading={responseMutation.isLoading}
loading={responseMutation.isPending}
type="submit"
color="primary">
{t("submit")}
+1 -1
View File
@@ -35,7 +35,7 @@ export interface InstallAppButtonProps {
renderProps: ButtonProps & {
/** Tells that the default render component should be used */
useDefaultComponent?: boolean;
isLoading?: boolean;
isPending?: boolean;
}
) => JSX.Element;
onChanged?: () => unknown;
@@ -44,7 +44,7 @@ const wipeMyCalAction = async (props: IWipeMyCalAction) => {
export const ConfirmDialog = (props: IConfirmDialogWipe) => {
const { t } = useLocale();
const { isOpenDialog, setIsOpenDialog } = props;
const [isLoading, setIsLoading] = useState(false);
const [isPending, setIsPending] = useState(false);
const today = dayjs();
const initialDate = today.startOf("day");
const endDate = today.endOf("day");
@@ -52,9 +52,9 @@ export const ConfirmDialog = (props: IConfirmDialogWipe) => {
const utils = trpc.useContext();
const rescheduleApi = useMutation(
async () => {
setIsLoading(true);
const rescheduleApi = useMutation({
mutationFn: async () => {
setIsPending(true);
try {
const result = await wipeMyCalAction({
initialDate: initialDate.toISOString(),
@@ -68,14 +68,12 @@ export const ConfirmDialog = (props: IConfirmDialogWipe) => {
showToast(t("unexpected_error_try_again"), "error");
// @TODO: notify
}
setIsLoading(false);
setIsPending(false);
},
{
async onSettled() {
await utils.viewer.bookings.invalidate();
},
}
);
async onSettled() {
await utils.viewer.bookings.invalidate();
},
});
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
@@ -104,7 +102,7 @@ export const ConfirmDialog = (props: IConfirmDialogWipe) => {
<Button
color="primary"
data-testid="send_request"
disabled={isLoading}
disabled={isPending}
onClick={async () => {
try {
rescheduleApi.mutate();
@@ -13,7 +13,7 @@ interface IWipeMyCalActionButtonProps {
const WipeMyCalActionButton = (props: IWipeMyCalActionButtonProps) => {
const { bookingsEmpty, bookingStatus } = props;
const [openDialog, setOpenDialog] = useState(false);
const { isSuccess, isLoading, data } = trpc.viewer.integrations.useQuery({
const { isSuccess, isPending, data } = trpc.viewer.integrations.useQuery({
variant: "other",
onlyInstalled: undefined,
});
@@ -27,7 +27,7 @@ const WipeMyCalActionButton = (props: IWipeMyCalActionButtonProps) => {
return (
<>
{data && isSuccess && !isLoading && credentialId && (
{data && isSuccess && !isPending && credentialId && (
<div className="mb-4">
<ConfirmDialog isOpenDialog={openDialog} setIsOpenDialog={setOpenDialog} />
<Button color="primary" onClick={() => setOpenDialog(true)} data-testid="wipe-today-button">
@@ -60,7 +60,7 @@ export default function ZapierSetup(props: IZapierSetupProps) {
setNewApiKeys({ ...newApiKeys, [teamId || ""]: apiKey });
}
if (integrations.isLoading) {
if (integrations.isPending) {
return <div className="bg-emphasis absolute z-50 flex h-screen w-full items-center" />;
}
+2 -2
View File
@@ -270,7 +270,7 @@ const AdminAppsListContainer = () => {
const { t } = useLocale();
const category = searchParams?.get("category") || AppCategories.calendar;
const { data: apps, isLoading } = trpc.viewer.appsRouter.listLocal.useQuery(
const { data: apps, isPending } = trpc.viewer.appsRouter.listLocal.useQuery(
{ category },
{ enabled: searchParams !== null }
);
@@ -291,7 +291,7 @@ const AdminAppsListContainer = () => {
const handleModelOpen = (data: EditModalState) => setModalState({ ...data });
if (isLoading) return <SkeletonLoader />;
if (isPending) return <SkeletonLoader />;
if (!apps || apps.length === 0) {
return (
+4 -4
View File
@@ -207,7 +207,7 @@ const BookerComponent = ({
} = useCalendars();
useEffect(() => {
if (event.isLoading) return setBookerState("loading");
if (event.isPending) return setBookerState("loading");
if (!selectedDate) return setBookerState("selecting_date");
if (!selectedTimeslot) return setBookerState("selecting_time");
return setBookerState("booking");
@@ -399,7 +399,7 @@ const BookerComponent = ({
<BookerSection
area="meta"
className="max-w-screen flex w-full flex-col md:w-[var(--booker-meta-width)]">
<EventMeta event={event.data} isLoading={event.isLoading} />
<EventMeta event={event.data} isPending={event.isPending} />
{layout !== BookerLayouts.MONTH_VIEW &&
!(layout === "mobile" && bookerState === "booking") && (
<div className="mt-auto px-5 py-3 ">
@@ -434,7 +434,7 @@ const BookerComponent = ({
visible={layout === BookerLayouts.WEEK_VIEW}
className="border-subtle sticky top-0 ml-[-1px] h-full md:border-l"
{...fadeInLeft}>
<LargeCalendar extraDays={extraDays} schedule={schedule.data} isLoading={schedule.isLoading} />
<LargeCalendar extraDays={extraDays} schedule={schedule.data} isLoading={schedule.isPending} />
</BookerSection>
<BookerSection
@@ -456,7 +456,7 @@ const BookerComponent = ({
extraDays={extraDays}
limitHeight={layout === BookerLayouts.MONTH_VIEW}
schedule={schedule?.data}
isLoading={schedule.isLoading}
isLoading={schedule.isPending}
seatsPerTimeSlot={event.data?.seatsPerTimeSlot}
showAvailableSeatsCount={event.data?.seatsShowAvailabilityCount}
/>
@@ -63,7 +63,7 @@ export const BookEventForm = ({
}, [eventType]);
if (eventQuery.isError) return <Alert severity="warning" message={t("error_booking_event")} />;
if (eventQuery.isLoading || !eventQuery.data) return <FormSkeleton />;
if (eventQuery.isPending || !eventQuery.data) return <FormSkeleton />;
if (!timeslot)
return (
<EmptyScreen
@@ -27,7 +27,7 @@ export const DatePicker = ({
return (
<DatePickerComponent
isLoading={schedule.isLoading}
isPending={schedule.isPending}
onChange={(date: Dayjs | null) => {
setSelectedDate(date === null ? date : date.format("YYYY-MM-DD"));
}}
@@ -24,10 +24,10 @@ const TimezoneSelect = dynamic(
export const EventMeta = ({
event,
isLoading,
isPending,
}: {
event: useEventReturnType["data"];
isLoading: useEventReturnType["isLoading"];
isPending: useEventReturnType["isPending"];
}) => {
const { setTimezone, timeFormat, timezone } = useTimePreferences();
const selectedDuration = useBookerStore((state) => state.selectedDuration);
@@ -40,7 +40,6 @@ export const EventMeta = ({
shallow
);
const { i18n, t } = useLocale();
const embedUiConfig = useEmbedUiConfig();
const isEmbed = useIsEmbed();
const hideEventTypeDetails = isEmbed ? embedUiConfig.hideEventTypeDetails : false;
@@ -66,12 +65,12 @@ export const EventMeta = ({
return (
<div className="relative z-10 p-6" data-testid="event-meta">
{isLoading && (
{isPending && (
<m.div {...fadeInUp} initial="visible" layout>
<EventMetaSkeleton />
</m.div>
)}
{!isLoading && !!event && (
{!isPending && !!event && (
<m.div {...fadeInUp} layout transition={{ ...fadeInUp.transition, delay: 0.3 }}>
<EventMembers
schedulingType={event.schedulingType}
@@ -74,7 +74,7 @@ export const LargeCalendar = ({
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
<Calendar
isLoading={isLoading}
isPending={isLoading}
availableTimeslots={availableSlots}
startHour={0}
endHour={23}
@@ -1,6 +1,6 @@
import { useMutation } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import { useRef, useState } from "react";
import { useRef, useState, useEffect } from "react";
import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client";
import dayjs from "@calcom/dayjs";
@@ -74,27 +74,33 @@ export const useBookings = ({ event, hashedLink, bookingForm }: IUseBookings) =>
enabled: !!bookingId && !hasInstantMeetingTokenExpired,
refetchInterval: 2000,
refetchIntervalInBackground: true,
onSuccess: (data) => {
try {
showToast(t("something_went_wrong_on_our_end"), "error");
const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse(
data.booking?.metadata || {}
)?.videoCallUrl;
if (locationVideoCallUrl) {
router.push(locationVideoCallUrl);
} else {
showToast(t("something_went_wrong_on_our_end"), "error");
}
} catch (err) {
showToast(t("something_went_wrong_on_our_end"), "error");
}
},
}
);
useEffect(
function refactorMeWithoutEffect() {
const data = _instantBooking.data;
if (!data) return;
try {
showToast(t("something_went_wrong_on_our_end"), "error");
const createBookingMutation = useMutation(createBooking, {
const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse(
data.booking?.metadata || {}
)?.videoCallUrl;
if (locationVideoCallUrl) {
router.push(locationVideoCallUrl);
} else {
showToast(t("something_went_wrong_on_our_end"), "error");
}
} catch (err) {
showToast(t("something_went_wrong_on_our_end"), "error");
}
},
[_instantBooking.data]
);
const createBookingMutation = useMutation({
mutationFn: createBooking,
onSuccess: (responseData) => {
const { uid, paymentUid } = responseData;
const fullName = getFullName(bookingForm.getValues("responses.name"));
@@ -141,7 +147,8 @@ export const useBookings = ({ event, hashedLink, bookingForm }: IUseBookings) =>
},
});
const createInstantBookingMutation = useMutation(createInstantBooking, {
const createInstantBookingMutation = useMutation({
mutationFn: createInstantBooking,
onSuccess: (responseData) => {
updateQueryParam("bookingId", responseData.bookingId);
setExpiryTime(responseData.expires);
@@ -153,7 +160,8 @@ export const useBookings = ({ event, hashedLink, bookingForm }: IUseBookings) =>
},
});
const createRecurringBookingMutation = useMutation(createRecurringBooking, {
const createRecurringBookingMutation = useMutation({
mutationFn: createRecurringBooking,
onSuccess: async (responseData) => {
const booking = responseData[0] || {};
const { uid } = booking;
@@ -253,10 +261,10 @@ export const useBookings = ({ event, hashedLink, bookingForm }: IUseBookings) =>
// A redirect is triggered on mutation success, so keep the loading state while it is happening.
const loadingStates = {
creatingBooking: createBookingMutation.isLoading || createBookingMutation.isSuccess,
creatingBooking: createBookingMutation.isPending || createBookingMutation.isSuccess,
creatingRecurringBooking:
createRecurringBookingMutation.isLoading || createRecurringBookingMutation.isSuccess,
creatingInstantBooking: createInstantBookingMutation.isLoading,
createRecurringBookingMutation.isPending || createRecurringBookingMutation.isSuccess,
creatingInstantBooking: createInstantBookingMutation.isPending,
};
return {
@@ -1,5 +1,6 @@
import { useSession } from "next-auth/react";
import { useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { shallow } from "zustand/shallow";
import { useTimePreferences } from "@calcom/features/bookings/lib";
@@ -30,7 +31,7 @@ export const useCalendars = () => {
shallow
);
const { data: overlayBusyDates } = trpc.viewer.availability.calendarOverlay.useQuery(
const { data: overlayBusyDates, isError } = trpc.viewer.availability.calendarOverlay.useQuery(
{
loggedInUsersTz: timezone || "Europe/London",
dateFrom: selectedDate,
@@ -42,13 +43,18 @@ export const useCalendars = () => {
},
{
enabled: !!session && set.size > 0 && switchEnabled,
onError: () => {
clearSet();
},
}
);
const { data, isLoading } = trpc.viewer.connectedCalendars.useQuery(undefined, {
useEffect(
function refactorMeWithoutEffect() {
if (!isError) return;
clearSet();
},
[isError]
);
const { data, isPending } = trpc.viewer.connectedCalendars.useQuery(undefined, {
enabled: !!calendarSettingsOverlay || Boolean(searchParams?.get("overlayCalendar")),
});
@@ -56,7 +62,7 @@ export const useCalendars = () => {
overlayBusyDates,
isOverlayCalendarEnabled: switchEnabled,
connectedCalendars: data?.connectedCalendars || [],
loadingConnectedCalendar: isLoading,
loadingConnectedCalendar: isPending,
onToggleCalendar: () => {
utils.viewer.availability.calendarOverlay.reset();
},
@@ -1,5 +1,5 @@
import { useSession } from "next-auth/react";
import { Fragment, useState } from "react";
import { Fragment, useMemo } from "react";
import {
FilterCheckboxFieldsContainer,
@@ -36,24 +36,24 @@ export const EventTypeFilter = () => {
const { data: user } = useSession();
const { data: query, pushItemToKey, removeItemByKeyAndValue, removeAllQueryParams } = useFilterQuery();
const [groupedEventTypes, setGroupedEventTypes] = useState<GroupedEventTypeState>();
const eventTypes = trpc.viewer.eventTypes.listWithTeam.useQuery(undefined, {
onSuccess: (data) => {
// Will be handled up the tree to redirect
// Group event types by team
const grouped = groupBy<IEventTypeFilter>(
data.filter((el) => el.team),
(item) => item?.team?.name || ""
); // Add the team name
const individualEvents = data.filter((el) => !el.team);
// push indivdual events to the start of grouped array
setGroupedEventTypes(
individualEvents.length > 0 ? { user_own_event_types: individualEvents, ...grouped } : grouped
);
},
enabled: !!user,
});
const groupedEventTypes: GroupedEventTypeState | null = useMemo(() => {
const data = eventTypes.data;
if (!data) {
return null;
}
// Will be handled up the tree to redirect
// Group event types by team
const grouped = groupBy<IEventTypeFilter>(
data.filter((el) => el.team),
(item) => item?.team?.name || ""
); // Add the team name
const individualEvents = data.filter((el) => !el.team);
// push indivdual events to the start of grouped array
return individualEvents.length > 0 ? { user_own_event_types: individualEvents, ...grouped } : grouped;
}, [eventTypes.data]);
if (!eventTypes.data) return null;
const isEmpty = eventTypes.data.length === 0;
@@ -30,8 +30,8 @@ export const VerifyCodeDialog = ({
isUserSessionRequiredToVerify?: boolean;
}) => {
const { t } = useLocale();
// Not using the mutation isLoading flag because after verifying we submit the underlying org creation form
const [isLoading, setIsLoading] = useState(false);
// Not using the mutation isPending flag because after verifying we submit the underlying org creation form
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState("");
const [value, setValue] = useState("");
const [hasVerified, setHasVerified] = useState(false);
@@ -49,11 +49,11 @@ export const VerifyCodeDialog = ({
const verifyCodeMutationUserSessionRequired = trpc.viewer.organizations.verifyCode.useMutation({
onSuccess: (data) => {
setIsLoading(false);
setIsPending(false);
onSuccess(data);
},
onError: (err) => {
setIsLoading(false);
setIsPending(false);
setHasVerified(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
@@ -63,11 +63,11 @@ export const VerifyCodeDialog = ({
const verifyCodeMutationUserSessionNotRequired = trpc.viewer.auth.verifyCodeUnAuthenticated.useMutation({
onSuccess: (data) => {
setIsLoading(false);
setIsPending(false);
onSuccess(data);
},
onError: (err) => {
setIsLoading(false);
setIsPending(false);
setHasVerified(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
@@ -77,7 +77,7 @@ export const VerifyCodeDialog = ({
const verifyCode = useCallback(() => {
setError("");
setIsLoading(true);
setIsPending(true);
if (isUserSessionRequiredToVerify) {
verifyCodeMutationUserSessionRequired.mutate({
code: value,
@@ -102,10 +102,10 @@ export const VerifyCodeDialog = ({
// trim the input value because "react-digit-input" creates a string of the given length,
// even when some digits are missing. And finally we use regex to check if the value consists
// of 6 non-empty digits.
if (hasVerified || error || isLoading || !/^\d{6}$/.test(value.trim())) return;
if (hasVerified || error || isPending || !/^\d{6}$/.test(value.trim())) return;
verifyCode();
}, [error, isLoading, value, verifyCode, hasVerified]);
}, [error, isPending, value, verifyCode, hasVerified]);
useEffect(() => setValue(""), [isOpenDialog]);
@@ -149,7 +149,7 @@ export const VerifyCodeDialog = ({
)}
<DialogFooter>
<DialogClose />
<Button type="submit" onClick={verifyCode} loading={isLoading}>
<Button type="submit" onClick={verifyCode} loading={isPending}>
{t("submit")}
</Button>
</DialogFooter>
+13 -21
View File
@@ -22,14 +22,8 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
const [checkedInternal, setCheckedInternal] = useState(isChecked);
const utils = trpc.useContext();
const { t } = useLocale();
const mutation = useMutation<
unknown,
unknown,
{
isOn: boolean;
}
>(
async ({ isOn }: { isOn: boolean }) => {
const mutation = useMutation({
mutationFn: async ({ isOn }: { isOn: boolean }) => {
const body = {
integration: type,
externalId: externalId,
@@ -60,24 +54,22 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
}
}
},
{
async onSettled() {
await utils.viewer.integrations.invalidate();
await utils.viewer.connectedCalendars.invalidate();
},
onError() {
setCheckedInternal(false);
showToast(`Something went wrong when toggling "${title}"`, "error");
},
}
);
async onSettled() {
await utils.viewer.integrations.invalidate();
await utils.viewer.connectedCalendars.invalidate();
},
onError() {
setCheckedInternal(false);
showToast(`Something went wrong when toggling "${title}"`, "error");
},
});
return (
<div className={classNames("my-2 flex flex-row items-center")}>
<div className="flex pl-2">
<Switch
id={externalId}
checked={checkedInternal}
disabled={mutation.isLoading}
disabled={mutation.isPending}
onCheckedChange={async (isOn: boolean) => {
setCheckedInternal(isOn);
await mutation.mutate({ isOn });
@@ -93,7 +85,7 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
{t("adding_events_to")}
</span>
)}
{mutation.isLoading && <RotateCw className="text-muted h-4 w-4 animate-spin ltr:ml-1 rtl:mr-1" />}
{mutation.isPending && <RotateCw className="text-muted h-4 w-4 animate-spin ltr:ml-1 rtl:mr-1" />}
</div>
);
};
+3 -3
View File
@@ -36,7 +36,7 @@ export type DatePickerProps = {
/** allows adding classes to the container */
className?: string;
/** Shows a small loading spinner next to the month name */
isLoading?: boolean;
isPending?: boolean;
/** used to query the multiple selected dates */
eventSlug?: string;
};
@@ -206,7 +206,7 @@ const Days = ({
<div key={day === null ? `e-${idx}` : `day-${day.format()}`} className="relative w-full pt-[100%]">
{day === null ? (
<div key={`e-${idx}`} />
) : props.isLoading ? (
) : props.isPending ? (
<button
className="bg-muted text-muted absolute bottom-0 left-0 right-0 top-0 mx-auto flex w-full items-center justify-center rounded-sm border-transparent text-center font-medium opacity-50"
key={`e-${idx}`}
@@ -226,7 +226,7 @@ const Days = ({
</div>
))}
{!props.isLoading && includedDates && includedDates?.length === 0 && (
{!props.isPending && includedDates && includedDates?.length === 0 && (
<NoAvailabilityOverlay month={month} nextMonthButton={nextMonthButton} />
)}
</>
@@ -11,7 +11,7 @@ import { Check } from "@calcom/ui/components/icon";
interface Props {
onChange: (value: { externalId: string; integration: string }) => void;
isLoading?: boolean;
isPending?: boolean;
hidePlaceholder?: boolean;
/** The external Id of the connected calendar */
destinationCalendar?: DestinationCalendar | null;
@@ -49,7 +49,7 @@ const OptionComponent = ({ ...props }: OptionProps<Option>) => {
const DestinationCalendarSelector = ({
onChange,
isLoading,
isPending,
value,
hidePlaceholder,
hideAdvancedText,
@@ -173,7 +173,7 @@ const DestinationCalendarSelector = ({
externalId,
});
}}
isLoading={isLoading}
isLoading={isPending}
value={selectedOption}
components={{ SingleValue: SingleValueComponent, Option: OptionComponent }}
isMulti={false}
@@ -43,7 +43,7 @@ DatePicker component offers a complete and customizable element for the user to
minDate: dayjs("2023-07-23").utc(),
maxDate: dayjs("2023-08-30").utc(),
selected: dayjs("2023-08-30").utc(),
isLoading: false,
isPending: false,
onChange: (newDate) => console.log(newDate),
onMonthChange: (newMonth) => console.log(newMonth),
}}
@@ -58,7 +58,7 @@ DatePicker component offers a complete and customizable element for the user to
control: "date"
}
}}>
{({ weekStart, excludedDates, onChange, onMonthChange, minDate, maxDate, selected, isLoading }) => (
{({ weekStart, excludedDates, onChange, onMonthChange, minDate, maxDate, selected, isPending }) => (
<VariantsTable titles={["Default"]} columnMinWidth={150}>
<VariantRow variant="Default">
<DatePicker
@@ -69,7 +69,7 @@ DatePicker component offers a complete and customizable element for the user to
onChange={onChange}
onMonthChange={onMonthChange}
selected={dayjs(selected)}
isLoading={isLoading}
isPending={isPending}
/>
</VariantRow>
</VariantsTable>
@@ -58,7 +58,7 @@ export function Calendar(props: CalendarComponentProps) {
} as React.CSSProperties // This can't live in the css file because it's a dynamic value and css variable gets super
}>
{hideHeader !== true && <SchedulerHeading />}
{props.isLoading && <Spinner />}
{props.isPending && <Spinner />}
<div
ref={container}
className="bg-default dark:bg-muted relative isolate flex h-full flex-auto flex-col">
@@ -121,6 +121,6 @@ export type CalendarState = {
hideHeader?: boolean;
};
export type CalendarComponentProps = CalendarPublicActions & CalendarState & { isLoading?: boolean };
export type CalendarComponentProps = CalendarPublicActions & CalendarState & { isPending?: boolean };
export type CalendarStoreProps = CalendarComponentProps & CalendarPrivateActions;
@@ -82,7 +82,7 @@ const ApiKeyListItem = ({
<DropdownItem
type="button"
color="destructive"
disabled={deleteApiKey.isLoading}
disabled={deleteApiKey.isPending}
onClick={() =>
deleteApiKey.mutate({
id: apiKey.id,
@@ -43,7 +43,7 @@ export const AboutOrganizationForm = () => {
form={aboutOrganizationFormMethods}
className="space-y-5"
handleSubmit={(v) => {
if (!updateOrganizationMutation.isLoading) {
if (!updateOrganizationMutation.isPending) {
setServerErrorMessage(null);
updateOrganizationMutation.mutate({ ...v, orgId });
}
@@ -109,7 +109,7 @@ export const AboutOrganizationForm = () => {
<div className="flex">
<Button
disabled={
aboutOrganizationFormMethods.formState.isSubmitting || updateOrganizationMutation.isLoading
aboutOrganizationFormMethods.formState.isSubmitting || updateOrganizationMutation.isPending
}
color="primary"
EndIcon={ArrowRight}
@@ -132,7 +132,7 @@ export const AddNewTeamsForm = () => {
<Button
StartIcon={Plus}
color="secondary"
disabled={createTeamsMutation.isLoading}
disabled={createTeamsMutation.isPending}
onClick={handleCounterIncrease}
aria-label={t("add_a_team")}
className="my-1">
@@ -143,7 +143,7 @@ export const AddNewTeamsForm = () => {
EndIcon={ArrowRight}
color="primary"
className="mt-6 w-full justify-center"
disabled={!formState.isValid || createTeamsMutation.isLoading || createTeamsMutation.isSuccess}
disabled={!formState.isValid || createTeamsMutation.isPending || createTeamsMutation.isSuccess}
onClick={handleFormSubmit}>
{t("continue")}
</Button>
@@ -80,7 +80,7 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
form={newOrganizationFormMethods}
id="createOrg"
handleSubmit={(v) => {
if (!createOrganizationMutation.isLoading) {
if (!createOrganizationMutation.isPending) {
setServerErrorMessage(null);
createOrganizationMutation.mutate(v);
}
@@ -188,7 +188,7 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
<div className="flex space-x-2 rtl:space-x-reverse">
<Button
disabled={
newOrganizationFormMethods.formState.isSubmitting || createOrganizationMutation.isLoading
newOrganizationFormMethods.formState.isSubmitting || createOrganizationMutation.isPending
}
color="primary"
EndIcon={ArrowRight}
@@ -61,7 +61,7 @@ export const SetPasswordForm = () => {
<Form
form={setPasswordFormMethods}
handleSubmit={(v) => {
if (!setPasswordMutation.isLoading) {
if (!setPasswordMutation.isPending) {
setServerErrorMessage(null);
setPasswordMutation.mutate({ newPassword: v.password });
}
@@ -97,7 +97,7 @@ export const SetPasswordForm = () => {
<div className="flex">
<Button
disabled={setPasswordFormMethods.formState.isSubmitting || setPasswordMutation.isLoading}
disabled={setPasswordFormMethods.formState.isSubmitting || setPasswordMutation.isPending}
color="primary"
EndIcon={ArrowRight}
type="submit"
@@ -44,7 +44,7 @@ export default function OtherTeamList(props: Props) {
key={team?.id as number}
team={team}
onActionSelect={(action: string) => selectAction(action, team?.id as number)}
isLoading={deleteTeamMutation.isLoading}
isPending={deleteTeamMutation.isPending}
hideDropdown={hideDropdown}
setHideDropdown={setHideDropdown}
/>
@@ -24,7 +24,7 @@ interface Props {
team: RouterOutputs["viewer"]["organizations"]["listOtherTeams"][number];
key: number;
onActionSelect: (text: string) => void;
isLoading?: boolean;
isPending?: boolean;
hideDropdown: boolean;
setHideDropdown: (value: boolean) => void;
}
@@ -140,7 +140,7 @@ export default function OtherTeamListItem(props: Props) {
variety="danger"
title={t("disband_team")}
confirmBtnText={t("confirm_disband_team")}
isLoading={props.isLoading}
isPending={props.isPending}
onConfirm={() => {
props.onActionSelect("disband");
}}>
@@ -1,5 +1,3 @@
import { useState } from "react";
import SkeletonLoaderTeamList from "@calcom/ee/teams/components/SkeletonloaderTeamList";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
@@ -10,21 +8,15 @@ import OtherTeamList from "./OtherTeamList";
export function OtherTeamsListing() {
const { t } = useLocale();
const [errorMessage, setErrorMessage] = useState("");
const { data: teams, isPending, error } = trpc.viewer.organizations.listOtherTeams.useQuery();
const { data: teams, isLoading } = trpc.viewer.organizations.listOtherTeams.useQuery(undefined, {
onError: (e) => {
setErrorMessage(e.message);
},
});
if (isLoading) {
if (isPending) {
return <SkeletonLoaderTeamList />;
}
return (
<>
{!!errorMessage && <Alert severity="error" title={errorMessage} />}
{!!error && <Alert severity="error" title={error.message} />}
{teams && teams.length > 0 ? (
<OtherTeamList teams={teams} />
@@ -98,7 +98,7 @@ const OrgForm = ({
required
{...form.register("metadata.orgAutoAcceptEmail")}
/>
<Button type="submit" color="primary" loading={mutation.isLoading}>
<Button type="submit" color="primary" loading={mutation.isPending}>
{t("save")}
</Button>
</Form>
@@ -1,7 +1,7 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
@@ -107,7 +107,7 @@ const OrgAppearanceView = ({
calVideoLogo: newLogo,
});
}}
disabled={mutation.isLoading}
disabled={mutation.isPending}
imageSrc={currentOrg?.calVideoLogo ?? undefined}
uploadInstruction={t("cal_video_logo_upload_instruction")}
triggerButtonColor={currentOrg?.calVideoLogo ? "secondary" : "primary"}
@@ -115,7 +115,7 @@ const OrgAppearanceView = ({
{currentOrg?.calVideoLogo && (
<Button
color="destructive"
disabled={mutation.isLoading}
disabled={mutation.isPending}
onClick={() => {
mutation.mutate({
calVideoLogo: null,
@@ -190,7 +190,7 @@ const OrgAppearanceView = ({
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("disable_cal_branding", { appName: APP_NAME })}
disabled={mutation?.isLoading}
disabled={mutation?.isPending}
description={t("removes_cal_branding", { appName: APP_NAME })}
checked={hideBrandingValue}
onCheckedChange={(checked) => {
@@ -212,13 +212,18 @@ const OrgAppearanceView = ({
const OrgAppearanceViewWrapper = () => {
const router = useRouter();
const { t } = useLocale();
const { data: currentOrg, isLoading } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
onError: () => {
router.push("/settings");
},
});
const { data: currentOrg, isPending, error } = trpc.viewer.organizations.listCurrent.useQuery();
if (isLoading) {
useEffect(
function refactorMeWithoutEffect() {
if (error) {
router.push("/settings");
}
},
[error]
);
if (isPending) {
return <AppearanceSkeletonLoader title={t("appearance")} description={t("appearance_org_description")} />;
}
@@ -1,6 +1,7 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
@@ -50,14 +51,23 @@ const OrgGeneralView = () => {
const { t } = useLocale();
const router = useRouter();
const { data: currentOrg, isLoading } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
onError: () => {
router.push("/settings");
},
});
const {
data: currentOrg,
isPending,
error,
} = trpc.viewer.organizations.listCurrent.useQuery(undefined, {});
const { data: user } = trpc.viewer.me.useQuery();
if (isLoading) return <SkeletonLoader title={t("general")} description={t("general_description")} />;
useEffect(
function refactorMeWithoutEffect() {
if (error) {
router.push("/settings");
}
},
[error]
);
if (isPending) return <SkeletonLoader title={t("general")} description={t("general_description")} />;
if (!currentOrg) {
return null;
}
@@ -1,9 +1,10 @@
"use client";
// import { debounce } from "lodash";
import { keepPreviousData } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useState, useEffect } from "react";
import MemberInvitationModal from "@calcom/ee/teams/components/MemberInvitationModal";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -71,20 +72,21 @@ const MembersView = () => {
// const [queryToFetch, setQueryToFetch] = useState<string | undefined>("");
const limit = 20;
const [showMemberInvitationModal, setShowMemberInvitationModal] = useState<boolean>(false);
const [members, setMembers] = useState<Members>([]);
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
enabled: !!session.data?.user?.org,
});
const { data: team, isLoading: isTeamLoading } = trpc.viewer.organizations.getOtherTeam.useQuery(
const {
data: team,
isPending: isTeamLoading,
error: otherTeamError,
} = trpc.viewer.organizations.getOtherTeam.useQuery(
{ teamId },
{
enabled: !Number.isNaN(teamId),
onError: () => {
router.push("/settings");
},
}
);
const { data: orgMembersNotInThisTeam, isLoading: isOrgListLoading } =
const { data: orgMembersNotInThisTeam, isPending: isOrgListLoading } =
trpc.viewer.organizations.getMembers.useQuery(
{
teamIdToExclude: teamId,
@@ -95,24 +97,40 @@ const MembersView = () => {
}
);
const { fetchNextPage, isFetchingNextPage, hasNextPage } =
trpc.viewer.organizations.listOtherTeamMembers.useInfiniteQuery(
{ teamId, limit },
{
onSuccess: (data) => {
const flatData = data?.pages?.flatMap((page) => page.rows) as Members;
setMembers(flatData);
},
enabled: !Number.isNaN(teamId),
onError: () => {
router.push("/settings");
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
keepPreviousData: true,
}
);
const {
fetchNextPage,
isFetchingNextPage,
hasNextPage,
error: otherMembersError,
data,
} = trpc.viewer.organizations.listOtherTeamMembers.useInfiniteQuery(
{ teamId, limit },
{
enabled: !Number.isNaN(teamId),
getNextPageParam: (lastPage) => lastPage.nextCursor,
placeholderData: keepPreviousData,
}
);
const isLoading = isTeamLoading || isOrgListLoading;
useEffect(
function refactorMeWithoutEffect() {
if (otherMembersError || otherTeamError) {
router.push("/settings");
}
},
[otherMembersError, otherTeamError]
);
useEffect(
function refactorMeWithoutEffect() {
if (data) {
router.push("/settings");
}
},
[data]
);
const isPending = isTeamLoading || isOrgListLoading;
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation({
onSuccess: () => {
utils.viewer.organizations.getMembers.invalidate();
@@ -147,7 +165,7 @@ const MembersView = () => {
)
}
/>
{!isLoading && (
{!isPending && (
<>
<div>
<>
@@ -163,7 +181,7 @@ const MembersView = () => {
placeholder={`${t("search")}...`}
/> */}
<MembersList
members={members}
members={data?.pages?.flatMap((page) => page.rows) ?? []}
team={team}
fetchNextPage={fetchNextPage}
hasNextPage={hasNextPage}
@@ -180,7 +198,7 @@ const MembersView = () => {
</div>
{showMemberInvitationModal && team && (
<MemberInvitationModal
isLoading={inviteMemberMutation.isLoading}
isPending={inviteMemberMutation.isPending}
isOpen={showMemberInvitationModal}
orgMembers={orgMembersNotInThisTeam}
teamId={team.id}
@@ -5,7 +5,7 @@ import type { Prisma } from "@prisma/client";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useLayoutEffect } from "react";
import { useState, useLayoutEffect, useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
@@ -18,7 +18,6 @@ import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import objectKeys from "@calcom/lib/objectKeys";
import slugify from "@calcom/lib/slugify";
import turndown from "@calcom/lib/turndownService";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { SkeletonContainer, SkeletonText } from "@calcom/ui";
import {
@@ -81,26 +80,39 @@ const OtherTeamProfileView = () => {
});
const params = useParamsWithFallback();
const teamId = Number(params.id);
const { data: team, isLoading } = trpc.viewer.organizations.getOtherTeam.useQuery(
const {
data: team,
isPending,
error: teamError,
} = trpc.viewer.organizations.getOtherTeam.useQuery(
{ teamId: teamId },
{
enabled: !Number.isNaN(teamId),
onError: () => {
router.push("/settings");
},
onSuccess: (team: RouterOutputs["viewer"]["organizations"]["getOtherTeam"]) => {
if (team) {
form.setValue("name", team.name || "");
form.setValue("slug", team.slug || "");
form.setValue("logo", team.logo || "");
form.setValue("bio", team.bio || "");
if (team.slug === null && (team?.metadata as Prisma.JsonObject)?.requestedSlug) {
form.setValue("slug", ((team?.metadata as Prisma.JsonObject)?.requestedSlug as string) || "");
}
}
},
}
);
useEffect(
function refactorMeWithoutEffect() {
if (teamError) {
router.push("/settings");
}
},
[teamError]
);
useEffect(
function refactorMeWithoutEffect() {
if (team) {
form.setValue("name", team.name || "");
form.setValue("slug", team.slug || "");
form.setValue("logo", team.logo || "");
form.setValue("bio", team.bio || "");
if (team.slug === null && (team?.metadata as Prisma.JsonObject)?.requestedSlug) {
form.setValue("slug", ((team?.metadata as Prisma.JsonObject)?.requestedSlug as string) || "");
}
}
},
[team]
);
// This page can only be accessed by team admins (owner/admin)
const isAdmin = true;
@@ -157,7 +169,7 @@ const OtherTeamProfileView = () => {
return (
<>
<Meta title={t("profile")} description={t("profile_team_description")} />
{!isLoading ? (
{!isPending ? (
<>
{isAdmin ? (
<Form
@@ -249,7 +261,7 @@ const OtherTeamProfileView = () => {
/>
</div>
<p className="text-default mt-2 text-sm">{t("team_description")}</p>
<Button color="primary" className="mt-8" type="submit" loading={mutation.isLoading}>
<Button color="primary" className="mt-8" type="submit" loading={mutation.isPending}>
{t("update")}
</Button>
{IS_TEAM_BILLING_ENABLED &&
@@ -4,7 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import type { Prisma } from "@prisma/client";
import { LinkIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState, useLayoutEffect } from "react";
import { useState, useLayoutEffect, useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
@@ -79,13 +79,22 @@ const OrgProfileView = () => {
document.body.focus();
}, []);
const { data: currentOrganisation, isLoading } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
onError: () => {
router.push("/settings");
},
});
const {
data: currentOrganisation,
isPending,
error,
} = trpc.viewer.organizations.listCurrent.useQuery(undefined, {});
if (isLoading || !orgBranding || !currentOrganisation) {
useEffect(
function refactorMeWithoutEffect() {
if (error) {
router.push("/settings");
}
},
[error]
);
if (isPending || !orgBranding || !currentOrganisation) {
return <SkeletonLoader title={t("profile")} description={t("profile_org_description")} />;
}
@@ -286,7 +295,7 @@ const OrgProfileForm = ({ defaultValues }: { defaultValues: FormValues }) => {
<p className="text-default mt-2 text-sm">{t("org_description")}</p>
</div>
<SectionBottomActions align="end">
<Button color="primary" type="submit" loading={mutation.isLoading} disabled={isDisabled}>
<Button color="primary" type="submit" loading={mutation.isPending} disabled={isDisabled}>
{t("update")}
</Button>
</SectionBottomActions>
@@ -1,5 +1,3 @@
import { useState } from "react";
import ConnectionInfo from "@calcom/ee/sso/components/ConnectionInfo";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import OIDCConnection from "@calcom/features/ee/sso/components/OIDCConnection";
@@ -22,23 +20,15 @@ const SkeletonLoader = ({ title, description }: { title: string; description: st
};
export default function SSOConfiguration({ teamId }: { teamId: number | null }) {
const [errorMessage, setErrorMessage] = useState("");
const { t } = useLocale();
const { data: connection, isLoading } = trpc.viewer.saml.get.useQuery(
{ teamId },
{
onError: (err) => {
setErrorMessage(err.message);
},
}
);
const { data: connection, isPending, error } = trpc.viewer.saml.get.useQuery({ teamId });
if (isLoading) {
if (isPending) {
return <SkeletonLoader title={t("sso_configuration")} description={t("sso_configuration_description")} />;
}
if (errorMessage) {
if (error) {
return (
<>
<Meta
@@ -46,7 +36,7 @@ export default function SSOConfiguration({ teamId }: { teamId: number | null })
description={t("sso_configuration_description")}
borderInShellHeader={true}
/>
<Alert severity="warning" message={t(errorMessage)} className="mt-4" />
<Alert severity="warning" message={t(error.message)} className="mt-4" />
</>
);
}
@@ -19,14 +19,7 @@ const SAMLSSO = () => {
const teamId = Number(params.id);
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
{ teamId },
{
onError: () => {
router.push("/settings");
},
}
);
const { data: team, isPending, error } = trpc.viewer.teams.get.useQuery({ teamId });
useEffect(() => {
if (!HOSTED_CAL_FEATURES) {
@@ -34,7 +27,15 @@ const SAMLSSO = () => {
}
}, []);
if (isLoading) {
useEffect(
function refactorMeWithoutEffect() {
if (error) {
router.push("/settings");
}
},
[error]
);
if (isPending) {
return <SkeletonLoader />;
}
@@ -166,7 +166,7 @@ export default function HelpMenuItem({ onHelpItemSelect }: HelpMenuItemProps) {
<div className="my-2 flex justify-end">
<Button
disabled={disableSubmit}
loading={mutation.isLoading}
loading={mutation.isPending}
onClick={async () => {
if (rating && comment) {
await sendFeedback(rating, comment);
@@ -79,7 +79,7 @@ export const AddNewTeamMembersForm = ({
const [memberInviteModal, setMemberInviteModal] = useState(showDialog);
const [inviteLinkSettingsModal, setInviteLinkSettingsModal] = useState(false);
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery({ teamId, isOrg }, { enabled: !!teamId });
const { data: team, isPending } = trpc.viewer.teams.get.useQuery({ teamId, isOrg }, { enabled: !!teamId });
const { data: orgMembersNotInThisTeam } = trpc.viewer.organizations.getMembers.useQuery(
{
teamIdToExclude: teamId,
@@ -126,12 +126,12 @@ export const AddNewTeamMembersForm = ({
{isOrg ? t("add_org_members") : t("add_team_member")}
</Button>
</div>
{isLoading ? (
{isPending ? (
<SkeletonButton />
) : (
<>
<MemberInvitationModal
isLoading={inviteMemberMutation.isLoading}
isPending={inviteMemberMutation.isPending}
isOpen={memberInviteModal}
orgMembers={orgMembersNotInThisTeam}
teamId={teamId}
@@ -199,7 +199,7 @@ export const AddNewTeamMembersForm = ({
EndIcon={!orgBranding || isOrg ? ArrowRight : undefined}
color="primary"
className="w-full justify-center"
disabled={publishTeamMutation.isLoading}
disabled={publishTeamMutation.isPending}
onClick={() => {
let uri = `/settings/teams/${teamId}/profile`;
if (isOrg) {
@@ -71,7 +71,7 @@ export const CreateANewTeamForm = () => {
<Form
form={newTeamFormMethods}
handleSubmit={(v) => {
if (!createTeamMutation.isLoading) {
if (!createTeamMutation.isPending) {
setServerErrorMessage(null);
createTeamMutation.mutate(v);
}
@@ -95,7 +95,7 @@ export const CreateANewTeamForm = () => {
<TextField
disabled={
/* E2e is too fast and it tries to fill this way before the form is ready */
!isLocaleReady || createTeamMutation.isLoading
!isLocaleReady || createTeamMutation.isPending
}
className="mt-2"
placeholder="Acme Inc."
@@ -146,14 +146,14 @@ export const CreateANewTeamForm = () => {
<div className="flex space-x-2 rtl:space-x-reverse">
<Button
disabled={createTeamMutation.isLoading}
disabled={createTeamMutation.isPending}
color="secondary"
href={returnToParam}
className="w-full justify-center">
{t("cancel")}
</Button>
<Button
disabled={newTeamFormMethods.formState.isSubmitting || createTeamMutation.isLoading}
disabled={newTeamFormMethods.formState.isSubmitting || createTeamMutation.isPending}
color="primary"
EndIcon={ArrowRight}
type="submit"
@@ -26,14 +26,14 @@ const DisableTeamImpersonation = ({
},
});
const [allowImpersonation, setAllowImpersonation] = useState(!query.data?.disableImpersonation ?? true);
if (query.isLoading) return <></>;
if (query.isPending) return <></>;
return (
<>
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("user_impersonation_heading")}
disabled={disabled || mutation?.isLoading}
disabled={disabled || mutation?.isPending}
description={t("team_impersonation_description")}
checked={allowImpersonation}
onCheckedChange={(_allowImpersonation) => {
@@ -76,14 +76,14 @@ export function GoogleWorkspaceInviteButton(
}}
className="w-full justify-center gap-2"
StartIcon={UsersIcon}
loading={mutation.isLoading}>
loading={mutation.isPending}>
{t("import_from_google_workspace")}
</Button>
</Tooltip>
<Tooltip content="Remove workspace connection">
<Button
color="secondary"
loading={removeConnectionMutation.isLoading}
loading={removeConnectionMutation.isPending}
StartIcon={XIcon}
onClick={() => {
removeConnectionMutation.mutate();
@@ -34,7 +34,7 @@ const MakeTeamPrivateSwitch = ({
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("make_team_private")}
disabled={disabled || mutation?.isLoading}
disabled={disabled || mutation?.isPending}
description={t("make_team_private_description")}
checked={isTeamPrivate}
onCheckedChange={(checked) => {
@@ -41,7 +41,7 @@ type MemberInvitationModalProps = {
teamId: number;
members?: PendingMember[];
token?: string;
isLoading?: boolean;
isPending?: boolean;
disableCopyLink?: boolean;
isOrg?: boolean;
};
@@ -428,7 +428,7 @@ export default function MemberInvitationModal(props: MemberInvitationModalProps)
{t("cancel")}
</Button>
<Button
loading={props.isLoading || createInviteMutation.isLoading}
loading={props.isPending || createInviteMutation.isPending}
type="submit"
color="primary"
className="me-2 ms-2"
@@ -22,7 +22,7 @@ interface Props {
export default function TeamAvailabilityTimes(props: Props) {
const { t } = useLocale();
const { data, isLoading } = trpc.viewer.teams.getMemberAvailability.useQuery(
const { data, isPending } = trpc.viewer.teams.getMemberAvailability.useQuery(
{
teamId: props.teamId,
memberId: props.memberId,
@@ -35,7 +35,7 @@ export default function TeamAvailabilityTimes(props: Props) {
}
);
const slots = !isLoading
const slots = !isPending
? getSlots({
frequency: props.frequency,
inviteeDate: props.selectedDate,
@@ -50,13 +50,13 @@ export default function TeamAvailabilityTimes(props: Props) {
return (
<div className={classNames("min-w-60 flex-grow pl-0", props.className)}>
{props.HeaderComponent}
{isLoading && slots.length === 0 && <SkeletonLoader />}
{!isLoading && slots.length === 0 ? (
{isPending && slots.length === 0 && <SkeletonLoader />}
{!isPending && slots.length === 0 ? (
<div className="flex flex-col items-center justify-center pt-4">
<span className="text-subtle text-sm">{t("no_available_slots")}</span>
</div>
) : (
<>{!isLoading && <p className="text-default mb-3 text-sm">{t("time_available")}</p>}</>
<>{!isPending && <p className="text-default mb-3 text-sm">{t("time_available")}</p>}</>
)}
<div className="max-h-[390px] overflow-scroll">
{slots.map((slot) => (
@@ -54,7 +54,7 @@ export default function TeamInviteList(props: Props) {
key={team?.id as number}
team={team}
onActionSelect={(action: string) => selectAction(action, team?.id as number)}
isLoading={deleteTeamMutation.isLoading}
isPending={deleteTeamMutation.isPending}
hideDropdown={hideDropdown}
setHideDropdown={setHideDropdown}
/>
@@ -27,7 +27,7 @@ interface Props {
};
key: number;
onActionSelect: (text: string) => void;
isLoading?: boolean;
isPending?: boolean;
hideDropdown: boolean;
setHideDropdown: (value: boolean) => void;
}
@@ -49,7 +49,7 @@ export default function TeamList(props: Props) {
key={team?.id as number}
team={team}
onActionSelect={(action: string) => selectAction(action, team?.id as number)}
isLoading={deleteTeamMutation.isLoading}
isPending={deleteTeamMutation.isPending}
hideDropdown={hideDropdown}
setHideDropdown={setHideDropdown}
/>
@@ -49,7 +49,7 @@ interface Props {
team: RouterOutputs["viewer"]["teams"]["list"][number];
key: number;
onActionSelect: (text: string) => void;
isLoading?: boolean;
isPending?: boolean;
hideDropdown: boolean;
setHideDropdown: (value: boolean) => void;
}
@@ -125,7 +125,7 @@ export default function TeamListItem(props: Props) {
onExit={() => {
setOpenMemberInvitationModal(false);
}}
isLoading={inviteMemberMutation.isLoading}
isPending={inviteMemberMutation.isPending}
onSubmit={(values, resetFields) => {
inviteMemberMutation.mutate(
{
@@ -322,7 +322,7 @@ export default function TeamListItem(props: Props) {
variety="danger"
title={t("disband_team")}
confirmBtnText={t("confirm_disband_team")}
isLoading={props.isLoading}
isPending={props.isPending}
onConfirm={() => {
props.onActionSelect("disband");
}}>
@@ -20,13 +20,9 @@ export function TeamsListing() {
const router = useRouter();
const [inviteTokenChecked, setInviteTokenChecked] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const { data, isLoading } = trpc.viewer.teams.list.useQuery(undefined, {
const { data, isPending, error } = trpc.viewer.teams.list.useQuery(undefined, {
enabled: inviteTokenChecked,
onError: (e) => {
setErrorMessage(e.message);
},
});
const { data: user } = trpc.viewer.me.useQuery();
@@ -88,13 +84,13 @@ export function TeamsListing() {
else setInviteTokenChecked(true);
}, [router, inviteMemberByToken, setInviteTokenChecked, token]);
if (isLoading || !inviteTokenChecked) {
if (isPending || !inviteTokenChecked) {
return <SkeletonLoaderTeamList />;
}
return (
<>
{!!errorMessage && <Alert severity="error" title={errorMessage} />}
{!!error && <Alert severity="error" title={error.message} />}
{invites.length > 0 && (
<div className="bg-subtle mb-6 rounded-md p-5">
@@ -1,7 +1,7 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import BrandColorsForm from "@calcom/features/ee/components/BrandColorsForm";
@@ -151,7 +151,7 @@ const ProfileView = ({ team }: ProfileViewProps) => {
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("disable_cal_branding", { appName: APP_NAME })}
disabled={mutation?.isLoading}
disabled={mutation?.isPending}
description={t("removes_cal_branding", { appName: APP_NAME })}
checked={hideBrandingValue}
onCheckedChange={(checked) => {
@@ -163,7 +163,7 @@ const ProfileView = ({ team }: ProfileViewProps) => {
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("hide_book_a_team_member")}
disabled={mutation?.isLoading}
disabled={mutation?.isPending}
description={t("hide_book_a_team_member_description", { appName: APP_NAME })}
checked={hideBookATeamMember ?? false}
onCheckedChange={(checked) => {
@@ -188,16 +188,18 @@ const ProfileViewWrapper = () => {
const { t } = useLocale();
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
{ teamId: Number(params.id) },
{
onError: () => {
const { data: team, isPending, error } = trpc.viewer.teams.get.useQuery({ teamId: Number(params.id) });
useEffect(
function refactorMeWithoutEffect() {
if (error) {
router.push("/settings");
},
}
}
},
[error]
);
if (isLoading)
if (isPending)
return (
<AppearanceSkeletonLoader title={t("appearance")} description={t("appearance_team_description")} />
);
@@ -2,7 +2,7 @@
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useState, useEffect } from "react";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -94,7 +94,7 @@ const MembersView = () => {
enabled: !!session.data?.user?.org,
});
const { data: orgMembersNotInThisTeam, isLoading: isOrgListLoading } =
const { data: orgMembersNotInThisTeam, isPending: isOrgListLoading } =
trpc.viewer.organizations.getMembers.useQuery(
{
teamIdToExclude: teamId,
@@ -105,17 +105,26 @@ const MembersView = () => {
}
);
const { data: team, isLoading: isTeamsLoading } = trpc.viewer.teams.get.useQuery(
const {
data: team,
isPending: isTeamsLoading,
error: teamError,
} = trpc.viewer.teams.get.useQuery(
{ teamId },
{
enabled: !!teamId,
onError: () => {
router.push("/settings");
},
}
);
useEffect(
function refactorMeWithoutEffect() {
if (teamError) {
router.push("/settings");
}
},
[teamError]
);
const isLoading = isOrgListLoading || isTeamsLoading;
const isPending = isOrgListLoading || isTeamsLoading;
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation();
@@ -149,7 +158,7 @@ const MembersView = () => {
)
}
/>
{!isLoading && (
{!isPending && (
<>
<div>
{team && (
@@ -190,7 +199,7 @@ const MembersView = () => {
</div>
{showMemberInvitationModal && team && (
<MemberInvitationModal
isLoading={inviteMemberMutation.isLoading}
isPending={inviteMemberMutation.isPending}
isOpen={showMemberInvitationModal}
orgMembers={orgMembersNotInThisTeam}
members={team.members}
@@ -5,7 +5,7 @@ import type { Prisma } from "@prisma/client";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useLayoutEffect, useState } from "react";
import { useLayoutEffect, useState, useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
@@ -93,16 +93,25 @@ const ProfileView = () => {
document.body.focus();
}, []);
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
const {
data: team,
isPending,
error,
} = trpc.viewer.teams.get.useQuery(
{ teamId, includeTeamLogo: true },
{
enabled: !!teamId,
onError: () => {
router.push("/settings");
},
}
);
useEffect(
function refactorMeWithoutEffect() {
if (error) {
router.push("/settings");
}
},
[error]
);
const isAdmin =
team && (team.membership.role === MembershipRole.OWNER || team.membership.role === MembershipRole.ADMIN);
@@ -142,7 +151,7 @@ const ProfileView = () => {
});
}
if (isLoading) {
if (isPending) {
return <SkeletonLoader title={t("profile")} description={t("profile_team_description")} />;
}
@@ -405,7 +414,7 @@ const TeamProfileForm = ({ team }: TeamProfileFormProps) => {
<p className="text-default mt-2 text-sm">{t("team_description")}</p>
</div>
<SectionBottomActions align="end">
<Button color="primary" type="submit" loading={mutation.isLoading} disabled={isDisabled}>
<Button color="primary" type="submit" loading={mutation.isPending} disabled={isDisabled}>
{t("update")}
</Button>
{IS_TEAM_BILLING_ENABLED &&
@@ -1,3 +1,4 @@
import { keepPreviousData } from "@tanstack/react-query";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -76,7 +77,7 @@ function UsersTableBare() {
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
keepPreviousData: true,
placeholderData: keepPreviousData,
refetchOnWindowFocus: false,
}
);
@@ -57,9 +57,9 @@ function exclude<UserType, Key extends keyof UserType>(user: UserType, keys: Key
/** Reusable logic that checks for admin permissions and if the requested user exists */
//const authedAdminWithUserMiddleware = middleware();
const authedAdminProcedureWithRequestedUser = authedAdminProcedure.use(async ({ ctx, next, rawInput }) => {
const authedAdminProcedureWithRequestedUser = authedAdminProcedure.use(async ({ ctx, next, getRawInput }) => {
const { prisma } = ctx;
const parsed = userIdSchema.safeParse(rawInput);
const parsed = userIdSchema.safeParse(await getRawInput());
if (!parsed.success) throw new TRPCError({ code: "BAD_REQUEST", message: "User id is required" });
const { userId: id } = parsed.data;
const user = await prisma.user.findUnique({ where: { id } });
@@ -1,5 +1,5 @@
import { useRouter } from "next/navigation";
import { useState, Suspense } from "react";
import { useState, Suspense, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
@@ -64,18 +64,21 @@ const useRecordingDownload = () => {
},
{
enabled: !!recordingId,
cacheTime: 0,
gcTime: 0,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: false,
onSuccess: (data) => {
if (data && data.download_link) {
window.location.href = data.download_link;
}
},
}
);
useEffect(
function refactorMeWithoutEffect() {
if (data && data.download_link) {
window.location.href = data.download_link;
}
},
[data]
);
return {
setRecordingId: (newRecordingId: string) => {
// may be a way to do this by default, but this is easy enough.
@@ -157,7 +160,7 @@ export const ViewRecordingsDialog = (props: IViewRecordingsDialog) => {
const { t, i18n } = useLocale();
const { isOpenDialog, setIsOpenDialog, booking, timeFormat } = props;
const { hasTeamPlan, isLoading: isTeamPlanStatusLoading } = useHasTeamPlan();
const { hasTeamPlan, isPending: isTeamPlanStatusLoading } = useHasTeamPlan();
const roomName =
booking?.references?.find((reference: PartialReference) => reference.type === "daily_video")?.meetingId ??
@@ -40,7 +40,7 @@ export const DeleteDialog = (props: IDeleteDialog) => {
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
<ConfirmationDialogContent
isLoading={deleteMutation.isLoading}
isPending={deleteMutation.isPending}
variety="danger"
title={t("delete_workflow")}
confirmBtnText={t("confirm_delete_workflow")}
@@ -82,7 +82,7 @@ export default function EmptyScreen(props: { isFilteredView: boolean }) {
subtitle={t("new_workflow_subtitle").toUpperCase()}
createFunction={(teamId?: number) => createMutation.mutate({ teamId })}
buttonText={t("create_workflow")}
isLoading={createMutation.isLoading}
isPending={createMutation.isPending}
/>
</div>
</div>
@@ -205,7 +205,7 @@ function EventWorkflowsTab(props: Props) {
t("locked_fields_admin_description"),
t("locked_fields_member_description")
);
const { data, isLoading } = trpc.viewer.workflows.list.useQuery({
const { data, isPending } = trpc.viewer.workflows.list.useQuery({
teamId: eventType.team?.id,
userId: !isChildrenManagedEventType ? eventType.userId || undefined : undefined,
});
@@ -231,7 +231,7 @@ function EventWorkflowsTab(props: Props) {
);
setSortedWorkflows(activeWorkflows.concat(disabledWorkflows));
}
}, [isLoading]);
}, [isPending]);
const createMutation = trpc.viewer.workflows.create.useMutation({
onSuccess: async ({ workflow }) => {
@@ -252,7 +252,7 @@ function EventWorkflowsTab(props: Props) {
return (
<LicenseRequired>
{!isLoading ? (
{!isPending ? (
<>
{isManagedEventType && (
<Alert
@@ -288,7 +288,7 @@ function EventWorkflowsTab(props: Props) {
target="_blank"
color="secondary"
onClick={() => createMutation.mutate({ teamId: eventType.team?.id })}
loading={createMutation.isLoading}>
loading={createMutation.isPending}>
{t("create_workflow")}
</Button>
}
@@ -43,7 +43,7 @@ export default function WorkflowDetailsPage(props: Props) {
const [reload, setReload] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const { data, isLoading } = trpc.viewer.eventTypes.getByViewer.useQuery();
const { data, isPending } = trpc.viewer.eventTypes.getByViewer.useQuery();
const eventTypeOptions = useMemo(
() =>
@@ -138,7 +138,7 @@ export default function WorkflowDetailsPage(props: Props) {
<MultiSelectCheckboxes
options={allEventTypeOptions}
isDisabled={props.readOnly}
isLoading={isLoading}
isLoading={isPending}
className="w-full md:w-64"
setSelected={setSelectedEventTypes}
selected={selectedEventTypes}
@@ -614,7 +614,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
<Button
color="secondary"
className="-ml-[3px] h-[36px] min-w-fit py-0 sm:block sm:rounded-bl-none sm:rounded-tl-none "
disabled={verifyPhoneNumberMutation.isLoading || props.readOnly}
disabled={verifyPhoneNumberMutation.isPending || props.readOnly}
onClick={() => {
verifyPhoneNumberMutation.mutate({
phoneNumber: form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || "",
@@ -64,7 +64,7 @@ function WorkflowsPage() {
createFunction={(teamId?: number) => {
createMutation.mutate({ teamId });
}}
isLoading={createMutation.isLoading}
isPending={createMutation.isPending}
disableMobileButton={true}
onlyShowWithNoTeams={true}
/>
@@ -79,7 +79,7 @@ function WorkflowsPage() {
<CreateButtonWithTeamsList
subtitle={t("new_workflow_subtitle").toUpperCase()}
createFunction={(teamId?: number) => createMutation.mutate({ teamId })}
isLoading={createMutation.isLoading}
isPending={createMutation.isPending}
disableMobileButton={true}
onlyShowWithTeams={true}
/>
@@ -109,7 +109,7 @@ function WorkflowPage() {
data: workflow,
isError,
error,
isLoading,
isPending,
} = trpc.viewer.workflows.get.useQuery(
{ id: +workflowId },
{
@@ -129,7 +129,7 @@ function WorkflowPage() {
MembershipRole.MEMBER;
useEffect(() => {
if (workflow && !isLoading) {
if (workflow && !isPending) {
if (workflow.userId && workflow.activeOn.find((active) => !!active.eventType.teamId)) {
setIsMixedEventType(true);
}
@@ -179,7 +179,7 @@ function WorkflowPage() {
form.setValue("activeOn", activeOn || []);
setIsAllDataLoaded(true);
}
}, [isLoading]);
}, [isPending]);
const updateMutation = trpc.viewer.workflows.update.useMutation({
onSuccess: async ({ workflow }) => {
@@ -269,7 +269,7 @@ function WorkflowPage() {
CTA={
!readOnly && (
<div>
<Button data-testid="save-workflow" type="submit" loading={updateMutation.isLoading}>
<Button data-testid="save-workflow" type="submit" loading={updateMutation.isPending}>
{t("save")}
</Button>
</div>
+1 -1
View File
@@ -221,7 +221,7 @@ const EmailEmbed = ({ eventType, username }: { eventType?: EventType; username:
<CollapsibleContent>
<div className="text-default text-sm">{t("select_date")}</div>
<DatePicker
isLoading={schedule.isLoading}
isPending={schedule.isPending}
onChange={(date: Dayjs | null) => {
setSelectedDate(date === null ? date : date.format("YYYY-MM-DD"));
}}
@@ -81,7 +81,7 @@ export function BulkEditDefaultConferencingModal(props: { open: boolean; setOpen
utils.viewer.getUsersDefaultConferencingApp.invalidate();
}}
/>
<Button type="submit" color="primary" loading={updateLocationsMutation.isLoading}>
<Button type="submit" color="primary" loading={updateLocationsMutation.isPending}>
{t("update")}
</Button>
</DialogFooter>
@@ -305,7 +305,7 @@ export default function CreateEventTypeDialog({
</div>
<DialogFooter showDivider>
<DialogClose />
<Button type="submit" loading={createMutation.isLoading}>
<Button type="submit" loading={createMutation.isPending}>
{t("continue")}
</Button>
</DialogFooter>
@@ -161,7 +161,7 @@ const DuplicateDialog = () => {
</div>
<DialogFooter showDivider className="mt-10">
<DialogClose />
<Button type="submit" loading={duplicateMutation.isLoading}>
<Button type="submit" loading={duplicateMutation.isPending}>
{t("continue")}
</Button>
</DialogFooter>
@@ -10,13 +10,13 @@ export function FilterResults({
emptyScreen,
children,
}: {
queryRes: { isLoading: boolean; data: { totalCount: number; filtered: unknown[] } | undefined };
queryRes: { isPending: boolean; data: { totalCount: number; filtered: unknown[] } | undefined };
SkeletonLoader: React.FC;
noResultsScreen: React.ReactNode;
emptyScreen: React.ReactNode;
children: React.ReactNode;
}) {
if (queryRes.isLoading) return <SkeletonLoader />;
if (queryRes.isPending) return <SkeletonLoader />;
if (!queryRes.data?.totalCount) return <>{emptyScreen}</>;
return queryRes.data?.totalCount ? (
+1 -1
View File
@@ -7,7 +7,7 @@ import type { AppFlags } from "../config";
*
* Entries consist of the feature flag name as the key and the resolved variant's value as the value.
*/
export type Flags = AppFlags;
export type Flags = Partial<AppFlags>;
/**
* Allows you to access the flags from context
+6 -6
View File
@@ -1,12 +1,12 @@
import type { AppFlags } from "@calcom/features/flags/config";
import { trpc } from "@calcom/trpc/react";
export function useFlags() {
const initialData: Partial<AppFlags> = process.env.NEXT_PUBLIC_IS_E2E
? { "managed-event-types": true, organizations: true, teams: true }
: {};
export function useFlags(): Partial<AppFlags> {
const query = trpc.viewer.features.map.useQuery(undefined, {
initialData: process.env.NEXT_PUBLIC_IS_E2E
? { "managed-event-types": true, organizations: true, teams: true }
: undefined,
placeholderData: {},
initialData,
});
return query.data ?? ({} as AppFlags);
return query.data ?? {};
}
+2 -2
View File
@@ -7,8 +7,8 @@ export async function getFeatureFlagMap(prisma: PrismaClient) {
orderBy: { slug: "asc" },
cacheStrategy: { swr: 300, ttl: 300 },
});
return flags.reduce<AppFlags>((acc, flag) => {
return flags.reduce((acc, flag) => {
acc[flag.slug as keyof AppFlags] = flag.enabled;
return acc;
}, {} as AppFlags);
}, {} as Partial<AppFlags>);
}
@@ -16,7 +16,7 @@ export const AverageEventDurationChart = () => {
const [startDate, endDate] = dateRange;
const { selectedTeamId: teamId, selectedUserId } = filter;
const initialConfigIsReady = !!(initialConfig?.teamId || initialConfig?.userId || initialConfig?.isAll);
const { data, isSuccess, isLoading } = trpc.viewer.insights.averageEventDuration.useQuery(
const { data, isSuccess, isPending } = trpc.viewer.insights.averageEventDuration.useQuery(
{
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
@@ -35,7 +35,7 @@ export const AverageEventDurationChart = () => {
}
);
if (isLoading) return <LoadingInsight />;
if (isPending) return <LoadingInsight />;
if (!isSuccess || !startDate || !endDate || (!teamId && !selectedUserId)) return null;
const isNoData = (data && data.length === 0) || data.every((item) => item["Average"] === 0);
@@ -18,7 +18,7 @@ export const BookingKPICards = () => {
const { selectedTeamId: teamId } = filter;
const { data, isSuccess, isLoading } = trpc.viewer.insights.eventsByStatus.useQuery(
const { data, isSuccess, isPending } = trpc.viewer.insights.eventsByStatus.useQuery(
{
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
@@ -59,7 +59,7 @@ export const BookingKPICards = () => {
},
];
if (isLoading) {
if (isPending) {
return <LoadingKPICards categories={categories} />;
}
@@ -29,7 +29,7 @@ export const BookingStatusLineChart = () => {
const {
data: eventsTimeLine,
isSuccess,
isLoading,
isPending,
} = trpc.viewer.insights.eventsTimeline.useQuery(
{
timeView: selectedTimeView,
@@ -49,7 +49,7 @@ export const BookingStatusLineChart = () => {
}
);
if (isLoading) return <LoadingInsight />;
if (isPending) return <LoadingInsight />;
if (!isSuccess) return null;
@@ -14,7 +14,7 @@ export const LeastBookedTeamMembersTable = () => {
const { dateRange, selectedEventTypeId, selectedTeamId: teamId, isAll, initialConfig } = filter;
const [startDate, endDate] = dateRange;
const { data, isSuccess, isLoading } = trpc.viewer.insights.membersWithLeastBookings.useQuery(
const { data, isSuccess, isPending } = trpc.viewer.insights.membersWithLeastBookings.useQuery(
{
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
@@ -31,7 +31,7 @@ export const LeastBookedTeamMembersTable = () => {
}
);
if (isLoading) return <LoadingInsight />;
if (isPending) return <LoadingInsight />;
if (!isSuccess || !startDate || !endDate || !teamId) return null;
@@ -15,7 +15,7 @@ export const MostBookedTeamMembersTable = () => {
const [startDate, endDate] = dateRange;
const { selectedTeamId: teamId } = filter;
const { data, isSuccess, isLoading } = trpc.viewer.insights.membersWithMostBookings.useQuery(
const { data, isSuccess, isPending } = trpc.viewer.insights.membersWithMostBookings.useQuery(
{
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
@@ -32,7 +32,7 @@ export const MostBookedTeamMembersTable = () => {
}
);
if (isLoading) return <LoadingInsight />;
if (isPending) return <LoadingInsight />;
if (!isSuccess || !startDate || !endDate || !teamId) return null;
@@ -14,7 +14,7 @@ export const PopularEventsTable = () => {
const [startDate, endDate] = dateRange;
const { selectedTeamId: teamId } = filter;
const { data, isSuccess, isLoading } = trpc.viewer.insights.popularEventTypes.useQuery(
const { data, isSuccess, isPending } = trpc.viewer.insights.popularEventTypes.useQuery(
{
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
@@ -32,7 +32,7 @@ export const PopularEventsTable = () => {
}
);
if (isLoading) return <LoadingInsight />;
if (isPending) return <LoadingInsight />;
if (!isSuccess || !startDate || !endDate || (!teamId && !selectedUserId)) return null;
@@ -11,7 +11,7 @@ const Download = () => {
const { t } = useLocale();
const { data, isLoading } = trpc.viewer.insights.rawData.useQuery(
const { data, isPending } = trpc.viewer.insights.rawData.useQuery(
{
startDate: filter.dateRange[0].toISOString(),
endDate: filter.dateRange[1].toISOString(),
@@ -60,7 +60,7 @@ const Download = () => {
<Button
EndIcon={FileDownIcon}
color="secondary"
{...(isLoading && { loading: isLoading })}
{...(isPending && { loading: isPending })}
className="self-end sm:self-baseline">
{t("download")}
</Button>
@@ -17,8 +17,8 @@ const UserBelongsToTeamInput = z.object({
isAll: z.boolean().optional(),
});
const userBelongsToTeamProcedure = authedProcedure.use(async ({ ctx, next, rawInput }) => {
const parse = UserBelongsToTeamInput.safeParse(rawInput);
const userBelongsToTeamProcedure = authedProcedure.use(async ({ ctx, next, getRawInput }) => {
const parse = UserBelongsToTeamInput.safeParse(await getRawInput());
if (!parse.success) {
throw new TRPCError({ code: "BAD_REQUEST" });
}
@@ -39,6 +39,7 @@ const userBelongsToTeamProcedure = authedProcedure.use(async ({ ctx, next, rawIn
where: membershipWhereConditional,
});
let isOwnerAdminOfParentTeam = false;
// Probably we couldn't find a membership because the user is not a direct member of the team
// So that would mean ctx.user.organization is present
if ((parse.data.isAll && ctx.user.organizationId) || (!membership && ctx.user.organizationId)) {
@@ -56,19 +57,17 @@ const userBelongsToTeamProcedure = authedProcedure.use(async ({ ctx, next, rawIn
if (!membershipOrg) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
...ctx,
user: {
...ctx.user,
isOwnerAdminOfParentTeam: true,
},
},
});
isOwnerAdminOfParentTeam = true;
}
return next();
return next({
ctx: {
user: {
...ctx.user,
isOwnerAdminOfParentTeam,
},
},
});
});
const UserSelect = {
@@ -85,7 +85,7 @@ export function NewScheduleButton({
/>
<DialogFooter>
<DialogClose />
<Button type="submit" loading={createMutation.isLoading}>
<Button type="submit" loading={createMutation.isPending}>
{t("continue")}
</Button>
</DialogFooter>
@@ -37,7 +37,7 @@ export function ScheduleListItem({
}) {
const { t, i18n } = useLocale();
const { data, isLoading } = trpc.viewer.availability.schedule.get.useQuery({ scheduleId: schedule.id });
const { data, isPending } = trpc.viewer.availability.schedule.get.useQuery({ scheduleId: schedule.id });
return (
<li key={schedule.id}>
@@ -87,7 +87,7 @@ export function ScheduleListItem({
StartIcon={MoreHorizontal}
/>
</DropdownMenuTrigger>
{!isLoading && data && (
{!isPending && data && (
<DropdownMenuContent>
<DropdownMenuItem className="min-w-40 focus:ring-muted">
{!schedule.isDefault && (
@@ -109,7 +109,7 @@ const BookerLayoutFields = ({
isOuterBorder,
}: BookerLayoutFieldsProps) => {
const { t } = useLocale();
const { isLoading: isUserLoading, data: user } = useMeQuery();
const { isPending: isUserLoading, data: user } = useMeQuery();
const [isOverridingSettings, setIsOverridingSettings] = useState(false);
const disableFields = showUserSettings && !isOverridingSettings;
@@ -9,7 +9,7 @@ import { Dialog, DialogClose, DialogContent, DialogFooter, showToast } from "@ca
export default function TimezoneChangeDialog() {
const { t } = useLocale();
const { data: user, isLoading } = trpc.viewer.me.useQuery();
const { data: user, isPending } = trpc.viewer.me.useQuery();
const utils = trpc.useContext();
const userTz = user?.timeZone;
const currentTz = dayjs.tz.guess() || "Europe/London";
@@ -42,10 +42,10 @@ export default function TimezoneChangeDialog() {
const [open, setOpen] = useState(false);
useEffect(() => {
const tzDifferent =
!isLoading && dayjs.tz(undefined, currentTz).utcOffset() !== dayjs.tz(undefined, userTz).utcOffset();
!isPending && dayjs.tz(undefined, currentTz).utcOffset() !== dayjs.tz(undefined, userTz).utcOffset();
const showDialog = tzDifferent && !document.cookie.includes("calcom-timezone-dialog=1");
setOpen(!IS_VISUAL_REGRESSION_TESTING && showDialog);
}, [currentTz, isLoading, userTz]);
}, [currentTz, isPending, userTz]);
// save cookie to not show again
function onCancel(maxAge: number, toast: boolean) {
+2 -2
View File
@@ -200,10 +200,10 @@ function useRedirectToOnboardingIfNeeded() {
type allBannerProps = { [Key in BannerType]: BannerTypeProps[Key]["data"] };
const useBanners = () => {
const { data: getUserTopBanners, isLoading } = trpc.viewer.getUserTopBanners.useQuery();
const { data: getUserTopBanners, isPending } = trpc.viewer.getUserTopBanners.useQuery();
const { data: userSession } = useSession();
if (isLoading || !userSession) return null;
if (isPending || !userSession) return null;
const isUserInactiveAdmin = userSession?.user.role === "INACTIVE_ADMIN";
const userImpersonatedByUID = userSession?.user.impersonatedBy?.id;
+2 -2
View File
@@ -3,10 +3,10 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge } from "@calcom/ui";
export function TeamInviteBadge() {
const { isLoading, listInvites } = useTeamInvites();
const { isPending, listInvites } = useTeamInvites();
const { t } = useLocale();
if (isLoading || !listInvites || listInvites.length === 0) return null;
if (isPending || !listInvites || listInvites.length === 0) return null;
return <Badge variant="default">{t("invite_team_notifcation_badge")}</Badge>;
}
@@ -75,12 +75,12 @@ export function AvailabilityEditSheet(props: Props) {
const { t } = useLocale();
const utils = trpc.useContext();
const { data: hasEditPermission, isLoading: loadingPermissions } =
const { data: hasEditPermission, isPending: loadingPermissions } =
trpc.viewer.teams.hasEditPermissionForUser.useQuery({
memberId: userId,
});
const { data, isLoading } = trpc.viewer.availability.schedule.getScheduleByUserId.useQuery({
const { data, isPending } = trpc.viewer.availability.schedule.getScheduleByUserId.useQuery({
userId: userId,
});
@@ -133,7 +133,7 @@ export function AvailabilityEditSheet(props: Props) {
disabled={!hasEditPermission || !data?.hasDefaultSchedule}
className="w-full justify-center"
type="submit"
loading={updateMutation.isLoading}
loading={updateMutation.isPending}
form="availability-form">
{t("save")}
</Button>
@@ -146,7 +146,7 @@ export function AvailabilityEditSheet(props: Props) {
})}
</SheetTitle>
</SheetHeader>
{!data?.hasDefaultSchedule && !isLoading && hasEditPermission && (
{!data?.hasDefaultSchedule && !isPending && hasEditPermission && (
<div className="my-2">
<Alert severity="warning" title={t("view_only_edit_availability_not_onboarded")} />
</div>
@@ -1,3 +1,4 @@
import { keepPreviousData } from "@tanstack/react-query";
import type { ColumnDef } from "@tanstack/react-table";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import { useMemo, useRef, useCallback, useEffect, useState } from "react";
@@ -62,7 +63,7 @@ export function AvailabilitySliderTable() {
const [editSheetOpen, setEditSheetOpen] = useState(false);
const [selectedUser, setSelectedUser] = useState<SliderUser | null>(null);
const { data, isLoading, fetchNextPage, isFetching } = trpc.viewer.availability.listTeam.useInfiniteQuery(
const { data, isPending, fetchNextPage, isFetching } = trpc.viewer.availability.listTeam.useInfiniteQuery(
{
limit: 10,
loggedInUsersTz: dayjs.tz.guess() || "Europe/London",
@@ -71,7 +72,7 @@ export function AvailabilitySliderTable() {
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
keepPreviousData: true,
placeholderData: keepPreviousData,
}
);
@@ -203,7 +204,7 @@ export function AvailabilitySliderTable() {
setSelectedUser(row.original);
}}
data={flatData}
isLoading={isLoading}
isPending={isPending}
// tableOverlay={<HoverOverview />}
onScroll={(e) => fetchMoreOnBottomReached(e.target as HTMLDivElement)}
/>
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more