✨(frontend) create utils function for valtio
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.
This commit is contained in:
committed by
aleb_the_flash
parent
46934a84d1
commit
5b76ea492b
28
src/frontend/src/utils/valtio.ts
Normal file
28
src/frontend/src/utils/valtio.ts
Normal file
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user