Skip to content

Commit

Permalink
Use localStorage to share the list between methods
Browse files Browse the repository at this point in the history
  • Loading branch information
mmaymo committed Dec 12, 2024
1 parent 4cfbc4a commit 2964415
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 16 deletions.
41 changes: 41 additions & 0 deletions resources/js/blocks/availableGatewaysStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const DEFAULT_STATE = {
cachedAvailableGateways: {},
};

const actions = {
setAvailableGateways(country, currency, gateways) {
return {
type: 'SET_AVAILABLE_GATEWAYS',
country,
currency,
gateways,
};
},
};

const reducer = (state = DEFAULT_STATE, action) => {
switch (action.type) {
case 'SET_AVAILABLE_GATEWAYS':
return {
...state,
cachedAvailableGateways: {
...state.cachedAvailableGateways,
[`${action.currency}-${action.country}`]: action.gateways,
},
};
default:
return state;
}
};

const selectors = {
getAvailableGateways(state) {
return state.cachedAvailableGateways || {};
},
};

wp.data.registerStore('mollie/available-gateways', {
reducer,
actions,
selectors,
});
54 changes: 40 additions & 14 deletions resources/js/blocks/molliePaymentMethod.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,41 @@
let cachedAvailableGateways = {};

function loadCachedAvailableGateways() {
const storedData = localStorage.getItem('cachedAvailableGateways');
if (storedData) {
try {
cachedAvailableGateways = JSON.parse(storedData);
} catch (e) {
console.warn('Error parsing cachedAvailableGateways from localStorage:', e);
cachedAvailableGateways = {};
}
}
}

function saveCachedAvailableGateways() {
localStorage.setItem('cachedAvailableGateways', JSON.stringify(cachedAvailableGateways));
}

loadCachedAvailableGateways();
function setAvailableGateways(country, currencyCode, data) {
cachedAvailableGateways = {
...cachedAvailableGateways,
...data
};
saveCachedAvailableGateways();
}
function useMollieAvailableGateways(billing, currencyCode, cartTotal, filters, ajaxUrl, jQuery, item) {
const country = billing.country;
const code = currencyCode;
const value = cartTotal;
const [localGateways, setLocalGateways] = wp.element.useState(cachedAvailableGateways);


wp.element.useEffect(() => {
if (!country || !item) return;
const currencyCode = code;
const cartTotal = value;
const currentFilterKey = currencyCode + "-" + filters.paymentLocale + "-" + country;
const currentFilterKey = currencyCode + "-" + country;
if (cachedAvailableGateways.hasOwnProperty(currentFilterKey)) {
setLocalGateways(cachedAvailableGateways);
return;
}
jQuery.ajax({
Expand All @@ -23,23 +46,22 @@ function useMollieAvailableGateways(billing, currencyCode, cartTotal, filters, a
currentGateway: item,
currency: currencyCode,
billingCountry: country,
cartTotal: cartTotal,
cartTotal,
paymentLocale: filters.paymentLocale
},
success: (response) => {
cachedAvailableGateways = { ...cachedAvailableGateways, ...response.data };
setLocalGateways(cachedAvailableGateways);
const { extensionCartUpdate } = window.wc.blocksCheckout;
//I just need to trigger a refresh of the checkout page
extensionCartUpdate({ namespace: 'mollie-payments-for-woocommerce', data: {} });
setAvailableGateways(country, currencyCode, response.data);
const cartTotals = wp.data.select('wc/store/cart').getCartTotals();
// Dispatch them again to trigger a re-render:
wp.data.dispatch('wc/store/cart').setCartData({...cartTotals});
},
error: (jqXHR, textStatus, errorThrown) => {
console.warn('Failed to fetch available gateways:', textStatus, errorThrown);
},
});
}, [billing, currencyCode, filters.paymentLocale, ajaxUrl, jQuery, item]);

return localGateways;
return cachedAvailableGateways;
}

// Component that runs the hook but does not render anything.
Expand Down Expand Up @@ -347,8 +369,6 @@ const Label = ({ item, filters, ajaxUrl, jQuery }) => {
};

const molliePaymentMethod = (useEffect, ajaxUrl, filters, gatewayData, availableGateways, item, jQuery, requiredFields, isCompanyFieldVisible, isPhoneFieldVisible) =>{
cachedAvailableGateways = availableGateways


document.addEventListener('mollie_components_ready_to_submit', function () {
onSubmitLocal()
Expand All @@ -358,6 +378,12 @@ const molliePaymentMethod = (useEffect, ajaxUrl, filters, gatewayData, available
document.documentElement.dispatchEvent(creditCardSelected);
}
}

// On first load, if availableGateways is not empty, store it
if (_.isEmpty(cachedAvailableGateways) && !_.isEmpty(availableGateways)) {
cachedAvailableGateways = availableGateways;
saveCachedAvailableGateways();
}
return {
name: item.name,
label:<Label
Expand All @@ -383,10 +409,10 @@ const molliePaymentMethod = (useEffect, ajaxUrl, filters, gatewayData, available
if (cartTotals <= 0) {
return true
}

loadCachedAvailableGateways();
const currencyCode = cartTotals?.currency_code;
const country = billingData?.country;
const currentFilterKey = currencyCode + "-" + filters.paymentLocale + "-" + country;
const currentFilterKey = currencyCode + "-" + country;

creditcardSelectedEvent();
if (!cachedAvailableGateways.hasOwnProperty(currentFilterKey)) {
Expand Down
2 changes: 1 addition & 1 deletion src/Assets/MollieCheckoutBlocksSupport.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public static function gatewayDataForWCBlocks(Data $dataService, array $gatewayI
&& isset($filters['locale'])
&& isset($filters['billingCountry'])
) {
$filterKey = "{$filters['amount']['currency']}-{$filters['locale']}-{$filters['billingCountry']}";
$filterKey = "{$filters['amount']['currency']}-{$filters['billingCountry']}";
foreach ($availableGateways as $key => $gateway) {
$availablePaymentMethods[$filterKey][$key] = $gateway->paymentMethod()->getProperty('id');
}
Expand Down
2 changes: 1 addition & 1 deletion src/BlockService/CheckoutBlockService.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public function availableGateways()
$availableGateways = WC()->payment_gateways()->get_available_payment_gateways();
$availableGateways = $this->removeNonMollieGateway($availableGateways);
$availableGateways = $this->maybeRemoveVoucher($availableGateways);
$filterKey = "{$filters['amount']['currency']}-{$filters['locale']}-{$filters['billingCountry']}";
$filterKey = "{$filters['amount']['currency']}-{$filters['billingCountry']}";
foreach ($availableGateways as $key => $gateway) {
$availablePaymentMethods[$filterKey][$key] = $gateway->paymentMethod()->getProperty('id');
}
Expand Down

0 comments on commit 2964415

Please sign in to comment.