-
Hi Observablers! I am experimenting with local storage for data persistence, and am having trouble correctly using Mutable in Framework. When I define inputs to swap data that are hard-coded into my notebook, I can see the mutable value changing on button press and apparently working fine: display(state_data) let state_data = Mutable ({})
function swap_data(data) {
state_data.value = data;
} However if I add another function to first check whether there's an existing data object in localStorage, my application breaks. When separating the code block and writing the localStorage copy of state_data to the mutable with state_data.value, my inputs reading state_data are blank, and my mutable value is an object within an object. However I cannot write directly to state_data, as I get const ephemeral_state = (function() {
const ephemeral_state = localStorage.getItem('state_data');
return ephemeral_state !== null && ephemeral_state !== 'null'
? state_data.value = JSON.parse(ephemeral_state)
: state_data.value = template_data;
})(); If I try to combine this code block into the cell with the mutable definition and I try directly writing to state_data, my inputs stop loading the data and the swap function doesn't work. If I try to write to state_data.value, then I get the error Here's a copy of a Framework project where I am trying to make this work: The index file is here: https://github.com/aaronkyle/data-persistence/blob/master/src/index.md I have gotten the mutable state_data to work correctly in the notebook context here: https://observablehq.com/@aaronkyle/data-mutation-and-persistence Any tips for how to make this function correctly in Framework? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
When If you want to assign the value of A common pattern is to use const age = Mutable(28);
const setAge = (a) => age.value = a; Then you can call If your goal is to initialize the value of const state_data = Mutable(JSON.parse(localStorage.getItem("state_data")) ?? template_data); |
Beta Was this translation helpful? Give feedback.
-
Thank you, Mike! I appreciate your time and clarifications. I got the pattern working and have updated the repo. :) |
Beta Was this translation helpful? Give feedback.
When
state_data
is aMutable
, you can never refer tostate_data.value
outside of the code block that declaresstate_data
. You can only refer tostate_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 (asswap_data
does) and use that. Likewise if you want to “peek” at the value ofstate_data
non-reactively (i.e., from a code block where you don’t want the code to re-run wheneverstate_data
changes), you need to expose a getter function.A common pattern is to use
Mutable
like React’suseState
hook:Then you can call
setAge
whenev…