From 5b76ea492bf98074ce756621968e6ab85774ab28 Mon Sep 17 00:00:00 2001 From: lebaudantoine Date: Fri, 6 Dec 2024 11:30:06 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8(frontend)=20create=20utils=20function?= =?UTF-8?q?=20for=20valtio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Valtio allows state persistence in local storage, which is necessary for the notification store. In this case, I'll need to persist a `proxyMap`—a utility provided by Valtio to create an observable map. However, since `proxyMap` isn't natively serializable, I'll need to implement two custom functions: one for serialization and another for deserialization (revival). Regarding the file structure, I've named the file `utils/valtio`, but this can be discussed further. The purpose of this file is to centralize common utility functions related to Valtio for better organization and reuse. --- src/frontend/src/utils/valtio.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/frontend/src/utils/valtio.ts diff --git a/src/frontend/src/utils/valtio.ts b/src/frontend/src/utils/valtio.ts new file mode 100644 index 00000000..f32d93d8 --- /dev/null +++ b/src/frontend/src/utils/valtio.ts @@ -0,0 +1,28 @@ +import { proxyMap } from 'valtio/utils' + +/** + * Serializes Map objects into a JSON-friendly format while preserving valtio proxyMap compatibility + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function serializeProxyMap(_: string, value: any) { + if (value instanceof Map) { + return { + dataType: 'Map', + value: Array.from(value.entries()), + } + } + return value +} + +/** + * Custom JSON reviver function for deserializing Map objects and wrapping them in valtio proxyMap + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function deserializeToProxyMap(_: string, value: any) { + if (typeof value === 'object' && value !== null) { + if (value.dataType === 'Map') { + return proxyMap(new Map(value.value)) + } + } + return value +}