# Local storage and private data

**Loki adds Alpine.js to make it easier for developers to work with various aspects of the frontend. One of the solutions here is to have an Alpine.js store `LokiLocalStorage` filled with a copy of local storage, with which other components, stores and plain JavaScript widgets are able to communicate.**

## Architecture
With Magento, the localStorage item `mage-cache-data` is used to store so-called *private data*, with sections like `cart`, `customer` and `messages`. The Alpine.js store `LokiLocalStorage` is initialised with a copy of this localStorage item. Thanks to this, an Alpine.js component, another store or a plain JavaScript snippet can retrieve a section like `cart` with a call like `Alpine.store('LokiLocalStorage').get('cart')`.

```js
document.addEventListener('alpine:init', () => {
    Alpine.effect(() => {
		const cartSection = Alpine.store('LokiLocalStorage').get('cart');
		console.log('cartSection', cartSection);
	});
});
```

When a section is called upon (`get()`) but it is empty, it's data is automatically fetched again (`refresh()`). This is done with an AJAX call to the URL `customer/section/load`

Each section is normally loaded with a property `data_id` with a timestamp as value. Based upon this timestamp plus a section lifetime, each section automatically expires.

## Methods
- `Alpine.store('LokiLocalStorage').get(sectionName)`: Retrieve a specific section;
- `Alpine.store('LokiLocalStorage').set(sectionName, data)`: Set new data into a section and save it to localStorage;
- `Alpine.store('LokiLocalStorage').refresh(sectionNames)`: Refresh specific sections (comma-separated string);
- `Alpine.store('LokiLocalStorage').remove(sectionName)`: Remove a specific section from localStorage (and cause fetching it again at the next `get()`);
- `Alpine.store('LokiLocalStorage').reset()`: Remove all sections from localStorage (and cause fetching it again at the next `get()`);

> In the Loki Checkout, there is a component `private-data` that is able to retrieve sections automatically and insert them into localStorage without any additional AJAX calls

## JavaScript events
- `loki:init:localstorage-store`: This `document` event is triggered when the store `LokiLocalStorage` is done loading.
