Small correction to localStorage example in documentation
jlapointe opened this issue · 2 comments
Hi Adam! This is a small thing but it tripped me up for a while.
In the S readme file, the example code provided for integrating localStorage is as follows:
if (localStorage.todos) // load stored todos on start
todos(JSON.parse(localStorage.todos).map(Todo));
S(() => // store todos whenever they change
localStorage.todos = JSON.stringify(todos()));
However, JSON.stringify(todos())
results in an array of empty objects.
The correct code taken from the functioning CodePen example is:
if (localStorage.todos) // load stored todos on start
todos(JSON.parse(localStorage.todos).map(Todo));
S(() => // store todos whenever they change
localStorage.todos = JSON.stringify(todos().map(t =>
({ title: t.title(), done: t.done() }))
));
It would be super handy if the first syntax just worked automagically, but I don't know whether that's possible/feasible.
Thanks for the report, and thanks @shimaore for the PRs!
Yeah, the example used to work, because it used to be the case that all data signals got a .toJSON()
method so that they could be JSONized transparently. That was removed a version back, though, because it turned out that it caused a noticeable performance regression in some cases. It made a lot of codepaths polymorphic: sometimes they got a plain function, sometimes a function (a data signal) that had a toJSON()
method added.
Instead, in my own code, I now explicitly specify signals that I want to be jsonable by using a little jsonable(<signal>)
utility which adds the .toJSON() method just to those signals:
// add a .toJSON() to a signal so that it will serialize its value to JSON
export function jsonable<T extends () => any>(obs : T) : T {
(obs as any).toJSON = toJSON;
return obs;
}
function toJSON(this : () => any) {
var json = this();
// if we shadowed the value's own toJSON, call it now
if (json && json.toJSON) json = json.toJSON();
return json;
}
So, for instance, the old code would work if we did:
var Todo = t => ({ // our Todo constructor
title: jsonable(S.data(t.title)), // properties are data signals
done: jsonable(S.data(t.done))
}),
todos = jsonable(SArray([])), // our array of todos
Sorry I hadn't updated the README and for the trouble that gave you, but thanks for bringing it to my attention!
Ahh I see, thanks for the solution!