Skip to content

Commit 6127790

Browse files
committed
Automatically sync localStorage.setItem to Alpine store
1 parent b7941b0 commit 6127790

1 file changed

Lines changed: 33 additions & 1 deletion

File tree

view/base/templates/script/store/localstorage-store.phtml

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ $sectionConfig = $block->getSectionConfig();
2424
sectionLifetime: <?= (int)$sectionConfig->getSectionDataLifeTime() * 60 ?>,
2525
data: {},
2626
init() {
27+
document.addEventListener('localStorageUpdate', (event) => {
28+
if (event.detail.key !== this.key) {
29+
return;
30+
}
31+
32+
this.data = event.detail.value;
33+
})
34+
2735
const storedData = localStorage.getItem(this.key);
2836
this.data = storedData ? JSON.parse(storedData) : {};
2937

@@ -57,7 +65,7 @@ $sectionConfig = $block->getSectionConfig();
5765
return Math.floor(Date.now() / 1000);
5866
},
5967
save() {
60-
localStorage.setItem(this.key, JSON.stringify(this.data));
68+
localStorage.setItem(this.key, JSON.stringify(this.data), true);
6169
},
6270
refresh(sections, forceNewSectionTimestamp) {
6371
let url = new URL(LOKI_BASE_URL + '/customer/section/load');
@@ -117,4 +125,28 @@ $sectionConfig = $block->getSectionConfig();
117125
}
118126
});
119127
});
128+
129+
const originalLocalStorageSetItem = localStorage.setItem;
130+
localStorage.setItem = function(key, value, skipEvent) {
131+
if (!skipEvent) {
132+
document.dispatchEvent(new CustomEvent('localStorageUpdate', {detail: {key, value}}));
133+
}
134+
135+
originalLocalStorageSetItem.apply(this, [key, value]);
136+
};
137+
138+
function localStorageTestMerge(additionalData) {
139+
if (!additionalData || Object.keys(additionalData).length === 0) {
140+
return;
141+
}
142+
143+
const json = localStorage.getItem('mage-cache-storage');
144+
if (!json) {
145+
return;
146+
}
147+
148+
const data = JSON.parse(json);
149+
const newData = Object.assign({}, data, additionalData);
150+
localStorage.setItem('mage-cache-storage', JSON.stringify(newData));
151+
}
120152
</script>

0 commit comments

Comments
 (0)