Skip to content

Combining mutable with a check of localStorage? #1818

Answered by mbostock
aaronkyle asked this question in Q&A
Discussion options

You must be logged in to vote

When state_data is a Mutable, you can never refer to state_data.value outside of the code block that declares state_data. You can only refer to state_data.value within the declaring code block.

If you want to assign the value of state_data outside the code block, you need to expose a setter function (as swap_data does) and use that. Likewise if you want to “peek” at the value of state_data non-reactively (i.e., from a code block where you don’t want the code to re-run whenever state_data changes), you need to expose a getter function.

A common pattern is to use Mutable like React’s useState hook:

const age = Mutable(28);
const setAge = (a) => age.value = a;

Then you can call setAge whenev…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by aaronkyle
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants