Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix / TVOD infinite loop and render optimizations #288

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/containers/AccountModal/AccountModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { addQueryParam, removeQueryParam } from '#src/utils/location';
import FinalizePayment from '#components/FinalizePayment/FinalizePayment';
import WaitingForPayment from '#components/WaitingForPayment/WaitingForPayment';
import UpdatePaymentMethod from '#src/containers/UpdatePaymentMethod/UpdatePaymentMethod';
import useEventCallback from '#src/hooks/useEventCallback';

const PUBLIC_VIEWS = ['login', 'create-account', 'forgot-password', 'reset-password', 'send-confirmation', 'edit-password'];

Expand All @@ -41,20 +42,24 @@ const AccountModal = () => {
} = config;
const isPublicView = viewParam && PUBLIC_VIEWS.includes(viewParam);

const toLogin = useEventCallback(() => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question if we need dependencies on navigate and location?

navigate(addQueryParam(location, 'u', 'login'));
});

const closeHandler = useEventCallback(() => {
navigate(removeQueryParam(location, 'u'));
});

useEffect(() => {
// make sure the last view is rendered even when the modal gets closed
if (viewParam) setView(viewParam);
}, [viewParam]);

useEffect(() => {
if (!!viewParam && !loading && !user && !isPublicView) {
navigate(addQueryParam(location, 'u', 'login'));
toLogin();
}
}, [viewParam, navigate, location, loading, user, isPublicView]);

const closeHandler = () => {
navigate(removeQueryParam(location, 'u'));
};
}, [viewParam, loading, user, isPublicView, toLogin]);

const renderForm = () => {
if (!user && loading && !isPublicView) {
Expand Down
80 changes: 47 additions & 33 deletions src/containers/AccountModal/forms/ChooseOffer.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
import React, { useEffect } from 'react';
import React, { useCallback, useEffect } from 'react';
import { mixed, object, SchemaOf } from 'yup';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router';
import shallow from 'zustand/shallow';

import useQueryParam from '../../../hooks/useQueryParam';
import { switchSubscription } from '../../../stores/CheckoutController';
import { useAccountStore } from '../../../stores/AccountStore';

import useOffers from '#src/hooks/useOffers';
import { addQueryParam, removeQueryParam } from '#src/utils/location';
import { useCheckoutStore } from '#src/stores/CheckoutStore';
import LoadingOverlay from '#components/LoadingOverlay/LoadingOverlay';
import ChooseOfferForm from '#components/ChooseOfferForm/ChooseOfferForm';
import useForm, { UseFormOnSubmitHandler } from '#src/hooks/useForm';
import useQueryParam from '#src/hooks/useQueryParam';
import { switchSubscription } from '#src/stores/CheckoutController';
import { useAccountStore } from '#src/stores/AccountStore';
import type { ChooseOfferFormData } from '#types/account';
import type { Subscription } from '#types/subscription';
import useEventCallback from '#src/hooks/useEventCallback';

const determineSwitchDirection = (subscription: Subscription | null) => {
const currentPeriod = subscription?.period;

if (currentPeriod === 'month') {
return 'upgrade';
} else if (currentPeriod === 'year') {
return 'downgrade';
} else {
return 'upgrade'; // Default to 'upgrade' if the period is not 'month' or 'year'
}
};

const ChooseOffer = () => {
const navigate = useNavigate();
Expand All @@ -36,45 +49,46 @@ const ChooseOffer = () => {
offerId: defaultOfferId,
};

const determineSwitchDirection = () => {
const currentPeriod = subscription?.period;
const closeModal = useEventCallback((replace = false) => {
navigate(removeQueryParam(location, 'u'), { replace });
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you need dependencies on navigate and location here and below?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be in a regular useCallback, but not in the useEventCallback.

We've found that when a modal has an effect, memo or callback on the location/navigate properties, all will trigger an update when closing the modal because of the location update.

Because this is hard to discover, we've chosen to wrap these dependant functions with useEventCallback to ensure functions depending will not update unnecessarily (and possibly cause issues).

For example, this useEffect:

useEffect(() => {
    // close auth modal when there are no offers defined in the config
    if (!isLoading && !offers.length) {
      closeModal(true);
    }
  }, [isLoading, offers, closeModal]);

This effect closes the modal (only once) based on the reactive variables isLoading and offers. The closeModal is still considered a reactive variable, but never updates because wrapped in useEventCallback.

The problem without the useEventCallback is that we can't ensure that this effect is only running when isLoading or offers are changed. Because it will also run when location changes (after a navigate).


if (currentPeriod === 'month') {
return 'upgrade';
} else if (currentPeriod === 'year') {
return 'downgrade';
} else {
return 'upgrade'; // Default to 'upgrade' if the period is not 'month' or 'year'
}
};
const toCheckout = useEventCallback(() => {
navigate(addQueryParam(location, 'u', 'checkout'));
});

const chooseOfferSubmitHandler: UseFormOnSubmitHandler<ChooseOfferFormData> = async ({ offerId }, { setSubmitting, setErrors }) => {
const offer = offerId && offersDict[offerId];
const chooseOfferSubmitHandler: UseFormOnSubmitHandler<ChooseOfferFormData> = useCallback(
async ({ offerId }, { setSubmitting, setErrors }) => {
const offer = offerId && offersDict[offerId];

if (!offer) return setErrors({ form: t('choose_offer.offer_not_found') });
if (!offer) return setErrors({ form: t('choose_offer.offer_not_found') });

if (isOfferSwitch) {
const targetOffer = offerSwitches.find((offer) => offer.offerId === offerId);
const targetOfferId = targetOffer?.offerId || '';
if (isOfferSwitch) {
const targetOffer = offerSwitches.find((offer) => offer.offerId === offerId);
const targetOfferId = targetOffer?.offerId || '';

await switchSubscription(targetOfferId, determineSwitchDirection());
navigate(removeQueryParam(location, 'u'));
} else {
const selectedOffer = availableOffers.find((offer) => offer.offerId === offerId) || null;
await switchSubscription(targetOfferId, determineSwitchDirection(subscription));
closeModal();
} else {
const selectedOffer = availableOffers.find((offer) => offer.offerId === offerId) || null;

setOffer(selectedOffer);
updateOffer(selectedOffer);
setSubmitting(false);
navigate(addQueryParam(location, 'u', 'checkout'));
}
};
setOffer(selectedOffer);
updateOffer(selectedOffer);
setSubmitting(false);
toCheckout();
}
},
[availableOffers, closeModal, isOfferSwitch, offerSwitches, offersDict, setOffer, subscription, t, toCheckout, updateOffer],
);

const { handleSubmit, handleChange, setValue, values, errors, submitting } = useForm(initialValues, chooseOfferSubmitHandler, validationSchema);

useEffect(() => {
// close auth modal when there are no offers defined in the config
if (!isLoading && !offers.length) navigate(removeQueryParam(location, 'u'), { replace: true });
}, [isLoading, offers, location, navigate]);
if (!isLoading && !offers.length) {
closeModal(true);
}
}, [isLoading, offers, closeModal]);

useEffect(() => {
if (!isOfferSwitch) setValue('offerId', defaultOfferId);
Expand Down
18 changes: 17 additions & 1 deletion src/hooks/useClientIntegration.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { useMemo } from 'react';

import { useConfigStore } from '#src/stores/ConfigStore';

export enum ClientIntegrations {
Expand All @@ -11,10 +13,24 @@ const useClientIntegration = () => {
} = useConfigStore.getState();

const isJWP = !!integrations.jwp?.clientId;
const isCleeng = !!integrations.cleeng?.id;
const sandbox = isJWP ? integrations.jwp?.useSandbox : integrations.cleeng?.useSandbox;
const client = isJWP ? ClientIntegrations.JWP : ClientIntegrations.CLEENG;
const clientId = isJWP ? integrations.jwp?.clientId : integrations.cleeng?.id;
const clientOffers = isJWP ? [`${integrations.jwp?.assetId}`] : [`${integrations.cleeng?.monthlyOffer}`, `${integrations.cleeng?.yearlyOffer}`];

// prevent infinite updates when `clientOffers` is used in as dependency
const clientOffers = useMemo(() => {
if (isJWP && !!integrations.jwp?.assetId) {
return [`${integrations.jwp.assetId}`];
}

if (isCleeng && integrations.cleeng?.monthlyOffer && integrations.cleeng?.yearlyOffer) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we try to support monthly OR yearly as well?

return [`${integrations.cleeng.monthlyOffer}`, `${integrations.cleeng.yearlyOffer}`];
}

// No offers or JWP/Cleeng TVOD
return [];
}, [isJWP, isCleeng, integrations.jwp, integrations.cleeng]);

return {
sandbox: sandbox ?? true,
Expand Down
3 changes: 3 additions & 0 deletions src/hooks/useEntitlement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ type QueryResult = {
responseData?: GetEntitlementsResponse;
};

const notifyOnChangeProps = ['data' as const, 'isLoading' as const];

/**
* useEntitlement()
*
Expand Down Expand Up @@ -55,6 +57,7 @@ const useEntitlement: UseEntitlement = (playlistItem) => {
queryFn: () => checkoutService?.getEntitlements({ offerId }, sandbox),
enabled: !!playlistItem && !!user && !!offerId && !isPreEntitled,
refetchOnMount: 'always' as const,
notifyOnChangeProps,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason we can't just use string literals here?

Suggested change
notifyOnChangeProps,
['data', 'isLoading'],

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the as const modifiers, the type results in string[] and is not accepted by react-query.

If I use ['data', 'isLoading'] as const the type results in readonly ['data', 'isLoading'] and is also not accepted by react-query.

This does work but is not much cleaner IMHO

const notifyOnChangeProps: QueryObserverOptions['notifyOnChangeProps'] = ['data', 'isLoading'];

})),
);

Expand Down