How to use immer in Rescript?

When there are changes to object in list in objest in list in object, plenty of nested spread operations are written to perform immutable changes.

That makes code really messy and unreadable.

How to use immerjs in Rescript?

1 Like

Can you provide examples of what you consider messy, and one where you’re using Immer?

My knee-jerk reaction is that (ideally) you shouldn’t have to reach for an immutable library when you work in a language where immutability is the default.

And to answer your question, unless Immer does some magic you should be able to create bindings to use it.

I like using immer for a deeply nested structure,

eg: data = {person: {details: { location: { cordinates: {latitude: 4}}}}}

to update this,
instead of
{…data, person: {…data.person, {details … etc

with immer I can just do
data.person.details.location.cordinates.latitude = 5

Got it!

An alternative might be to turn these into domain specific objects, and keep e.g. the person as an aggregate with helper functions to update the data.

I don’t know the status of the lenses-ppx, but could be an option too.


… and for good measure, an example might look something like:

module Coordinates = { ... }
module Location = { ... }

module Person = {

  let updateLocation: (t, Location.t => Location.t) => t

let newPerson =
  person -> Person.updateLocation(location => {
    coords: Coordinates.update(coords, ~lat=newLat, ~lng=newLng),