I'm planning to write a Visual Studio Code extension and it need to save some information for example a counter. The user can press a shortcut to increase or decrease the counter and the value of the counter will be saved some where. Next time when the user starts Visual Studio Code, the extension can load the counter's last value. My question is, where is the proper place to store this info?
When you have a global state that you want to see across all your VSCODE windows, you can use the globalState
from the extension's context.
I used this code in my extension to store a string
:
async function activate (context) {
const state = stateManager(context)
const {
lastPaletteTitleApplied
} = state.read()
await state.write({
lastPaletteTitleApplied: 'foo bar'
})
}
function stateManager (context) {
return {
read,
write
}
function read () {
return {
lastPaletteTitleApplied: context.globalState.get('lastPaletteApplied')
}
}
async function write (newState) {
await context.globalState.update('lastPaletteApplied', newState.lastPaletteTitleApplied)
}
}
You're probably looking for the Memento
API. The ExtensionContext
has two different memento instances you can access:
workspaceState
A memento object that stores state in the context of the currently opened workspace.
globalState
A memento object that stores state independent of the current opened workspace.
Both survive VSCode updates to my knowledge.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With