forked from PrestaShop/hummingbird
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseData.ts
More file actions
30 lines (26 loc) · 818 Bytes
/
parseData.ts
File metadata and controls
30 lines (26 loc) · 818 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Parse JSON data from data-ps-data attribute
*
* @example
* // HTML: <button data-ps-data='{"id": "123", "name": "Product"}'>
* const data = parseData<{id: string, name: string}>(button);
* // Returns: { id: "123", name: "Product" }
*
* @param element - The HTML element containing data-ps-data attribute
* @returns Parsed data object or null if parsing fails
*/
const parseData = <T>(element: HTMLElement): T | null => {
const {psData} = element.dataset;
if (!psData) return null;
try {
return JSON.parse(psData) as T;
} catch {
console.error('[parseData] Failed to parse data-ps-data:', psData);
return null;
}
};
export default parseData;