Hey - is there a standard way of adding the ability to permalink a particular snapshot of a reason react app? I’m thinking something like hashing the current state and adding it as a url parameter (along with detecing that parameter on startup)? Is that what https://reasonml.github.io/en/try.html does?
Creating perma-link for reasonreact app
The “try” page makes a hash of the code that’s typed into the editor, which is pretty much all the state that’s needed.
As far as a generalized permalink setup – if you keep all of your state in the top component, then it’s not too hard to serialize that into the url & then parse it on load or onhashchange
Thanks for your response. That all makes sense. Do you have any library recommendations for doing the (de-)serialization?
You need to roll your own. I usually put all information to a json string, base64 then apply some simple compression algorithm to reduce the length. I even created a binary structure to do it in one of my app (then I can convert binary -> base64 -> compression), it’s more space-efficient if you’re dealing with numbers.
Would it be easy for you to post some sample code that does this for one of your apps? Maybe the simpler version (not the binary one)?
Sure. Here is a simplify version of it in pseudo code:
Given I have this data and I want to create permanent link for it:
let data = {
"foo": "bar"
};
- serialize it to a string:
let json = data |> Js.Json.stringify
- to make sure the string is safe for url, I need to apply a base64 on the result string:
let base64 = json |> toBase64
- apply a compression algorithm
let finalPermaLink = base64 |> compress
I personally use lzstring for compression.
And depends on your application, step 3 could happen before step 2 for better compression result.
I hope you’ll get a rough idea how to do this after my answer.
For the binary version, you can use typed array (in JS api) for generating the data, then apply base64 over it
Thanks, this is great. I’m interested in an implementation of toBase64
unless that’s a function which is in Belt or something.
For browser, there is atob and btoa . For Node.js, you should be able to do that with the Buffer API