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
.
import { useNestedStore } from 'olik-react'
export function MyComponent(props: { id: string }) {
const store = useNestedStore({
name: 'MyComponent',
hostStoreName: document.title,
instanceId: props.id,
state: { num: 0 },
})
return (/* rendered content */)
}
import { createStore } from 'olik'
@Component({ ... })
export class MyComponent implements OnDestroy {
store = createStore({
name: 'MyComponent',
nestStore: { hostStoreName: document.title, instanceId: 1 },
state: { num: 0 },
})
ngOnDestroy() {
// You should detach this store from its container when it is no longer being used
this.store.$detachStore();
}
}
<script lang="ts">
import { createStore } from 'olik';
export let id: number;
const store = createStore({
name: 'MyComponent',
nestStore: { hostStoreName: document.title, instanceId: id },
state: { num: 0 },
});
// You should detach this store from its container when it is no longer being used
onDestroy(() => store.$detachStore())
</script>