I have the two lines of code below. I also have another function which prints the value to the console to see what the value it is and to add and subtract from the value. I was wondering why the second line of code wouldn’t “override” the stable value as when I “dfx deploy” it keeps the old value of say 150 instead of resetting to 100. I was wondering if there was a way to reset it to 100 whenever I use “dfx deploy” or if it resets every time I use “dfx start”. The reason I was using this was just for testing and learning purposes. I know that if it really didn’t need it to keep the value, I would remove stable.
stable var Val: Float = 100;
Val := 100;
Hey, that is a good question! I understand why it might be confusing.
Stable variables are preserved over upgrades, so redeploying will not override the values of stable variables. This prevents us from loosing data.
If you’d like to change the values of stable variables during an upgrade you should do an explicit migration, like so:
(with migration = func (old : Old) : New = { old with v1 = 123 })
actor MyActor {
stable var v1: Float = 100;
}
where Old
is a record type with stable variables before the upgrade and New
after the upgrade.
Here is a full example to play with.
Try invoking the methods after deployment, then redeploy and see that the stable variable got changed, then try the same without the migration script to see that the stable variable is preserved
I believe you can also use
dfx deploy --mode reinstall
to reinstall all the canisters from fresh, instead of doing upgrades. All previous state will be lost.