Fable/F# - How do I save enums or discriminated unions to the browser?

871 views Asked by At

I can save a string to local browser storage with

Browser.localStorage.setItem(key, str)

but when I try to stringify a discriminated union (e.g. by calling string on it), it comes out as [Object object].

Since the FSharp.Reflection and enum-manipulation functions are not supported in Fable, how can I save and load a DU or enum value (without doing a bunch of extra work for every case)?

1

There are 1 answers

0
Overlord Zurg On BEST ANSWER

Per the Fable docs, you can use the function Fable.Import.JS.JSON.stringify to serialize the DU, and Fable.Import.JS.JSON.parse to deserialize it. This allows it to be saved and loaded from browser localStorage.

There is also a [<StringEnum>] attribute, which I assume makes enums be treated as their string representation, but I did not test it for this use case.