Skip to main content

Nesting stores

A component-level store can be nested within the application-level store. This allows tracking component-level state together with application-level state. Should no application-level store exist, a completely new store will be created. This allows you to build your components with Olik, bu without your application-level store.​


Let's begin with the following store:
import {
createStore,
importOlikNestingModule,
importOlikReduxDevtoolsModule
} from 'olik'

importOlikNestingModule()
importOlikReduxDevtoolsModule()

const store = createStore({
name: document.title,
state: { str: '' },
})

Creating a nested store​

To nest a store, you must provide the following arguments when creating it:

  • hostStoreName - If the host store could not found, then your nested store will be registered as a separate store. This allows you to build your components independently of your application.
  • instanceId - This will distinguish multiple instances of the nested store within the container store.
import { createStore } from 'olik'

class MyComponent {

const store = createStore({
name: 'MyComponent',
nestStore: { hostStoreName: document.title, instanceId: 1 },
state: { num: 0 },
})

// You should detach this store from its container when it is no longer being used
onComponentDestroyed = () => this.store.$detachStore()
}

You should now see that your application state has a new property called nested which contains the state for MyComponent.

Demo 🥚