Search code examples
local-storagengxs

How to change the default @@STATE key for storage plugin


I use @ngxs/storage-plugin to sync app states into localstorage. The default storage key for serialized states is @@STATE, is there a way to rename the default key?

I noticed when calling NgxsStoragePluginModule.forRoot, I can use key option to change storage key of a slice of states, but it was not working when I try to store the whole states


Solution

  • The key option should have been named path instead. It does not refer to the name of the key used in localStorage. Despite the fact that @@STATE also creates a key in localStorage of the same name.

    The key option is one or more dot notations into the state store. For example;

    interface MyModel { example: string }
    
    @State<MyModel>({
        name: 'app',
        defaults: { example: "Hello World" }
    ) //...
    

    If the key is set to @@STATE then the storage will save

       "@@STATE" : "{app: {example: 'Hello World'}}"
    

    When you change the key it has to point into the state object otherwise it will yield undefined. So we can set key to "example" which would store "Hello World" in localStorage under the key named "example".

    Like this

       "example": "Hello World"
    

    As of now, the value @@STATE is hard coded in the plugin and can not be renamed. It holds special meaning to serialize the entire store. Otherwise, the key must be a dot path into the state object.