Object update vs. Object.set

This sentence in the ReScript docs claims that ReScript objects are not update-able: “Disallowed unless the object is a binding that comes from the JavaScript side.”

However, Object.set also exists, which seems like it allows you to update any Object.

What am I missing?

The not update-able means x["foo"] = "bar" kind of update, as shown by this section of the doc: Object | ReScript Language Manual

I always viewed Object.set as kind of a backdoor, since needing to use a function call to update an object is a pretty clear sign to users that they’re off the paved path.

Maybe the wording of the docs could be updated to reduce confusion?

3 Likes

I did feel off the paved path when I found & used Object.set :sweat_smile: I’m trying to use a query-string library and I’ve written the following ReScript binding:

type queryString = {parse: string => Js.Dict.t<string>, stringify: Js.Dict.t<string> => string}
@module("query-string") external queryString: queryString = "default"

type location = {search: string}
@scope("window") @val external location: location = "location"

let params = () => queryString.parse(location.search)

Then at my call site, I’m doing something like

let dict = QueryString.params()
Dict.set(dict, "key", "value")

RescriptReactRouter.push(
  pathString ++ "?" ++ queryString.stringify(queryStringRecord),
)

How can I do something similar without needing Dict.set?

This is actually why we’re differentiating between objects and dicts in ReScript (they’re both compiled to JS objects under the hood), dicts are meant to be used with dynamic keys as you’re doing here so this looks correct.

On this topic, why don’t you use URLSearchParams instead of a plain object for query strings though?

1 Like

Ah, good to know, thanks @tsnobip. I decided against URLSearchParams for some reason but I can’t remember why, so I’ll revisit :slight_smile: Thanks all!

1 Like