Creating perma-link for reasonreact app

reasonreact

#1

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?


#2

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


#3

Thanks for your response. That all makes sense. Do you have any library recommendations for doing the (de-)serialization?


#4

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.


#5

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)?


#6

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"
};
  1. serialize it to a string:
let json = data |>  Js.Json.stringify
  1. to make sure the string is safe for url, I need to apply a base64 on the result string:
let base64 = json |> toBase64
  1. 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


#7

Thanks, this is great. I’m interested in an implementation of toBase64 unless that’s a function which is in Belt or something.


#8

For browser, there is atob and btoa . For Node.js, you should be able to do that with the Buffer API


#9

Thanks for all your help :slight_smile: