Store Connections
Overview
Store connections in neutrix let you sync multiple stores together. This helps you:
- Coordinate state changes between stores
- Create reactive relationships between different parts of your app
- Maintain consistency across multiple domains
Basic Usage
Store connections are defined by specifying a source store, a target store, a condition when changes should occur, and what changes to make.
Single connection
import { createNeutrixStore, connectStore } from 'neutrix';
const userStore = createNeutrixStore({
isLoggedIn: false,
user: null
});
const uiStore = createNeutrixStore({
theme: 'light',
sidebarOpen: true
});
connectStore({
source: userStore.store, // or userStore if hook-based
target: uiStore.store,
when: (source) => !source.get('isLoggedIn'),
then: (target) => {
target.set('sidebarOpen', false);
}
});
Note: If you used a hook-based store (const useUserStore = createNeutrixStore(...)
), you can access the core store via useUserStore.store
as shown.
Multiple Connections
For more complex scenarios, you can connect multiple stores with different rules using connectStores
:
import { createNeutrixStore, connectStores } from 'neutrix';
const cartStore = createNeutrixStore({ items: [], total: 0 });
const notificationStore = createNeutrixStore({ messages: [] });
const uiStore = createNeutrixStore({ showBanner: false });
connectStores([
// Cart -> Notifications connection
{
source: cartStore.store,
target: notificationStore.store,
when: (source) => source.get('items').length > 0,
then: (target) => {
target.set('messages', [
...target.get('messages'),
{ type: 'info', text: 'Items in cart' }
]);
}
},
// Cart -> UI connection
{
source: cartStore.store,
target: uiStore.store,
when: (source) => source.get('total') > 100,
then: (target) => {
target.set('showBanner', true);
}
}
]);
Features
1. Immediate Execution
Use the immediate flag to run the connection logic immediately on setup:
connectStore({
source: settingsStore,
target: uiStore,
when: (source) => source.get('darkMode'),
then: (target) => {
target.set('theme', 'dark');
},
immediate: true // immediately executes
});
2. Cleanup
connectStore
or connectStores
returns a function to disconnect:
const disconnect = connectStore({
source: storeA,
target: storeB,
when: condition,
then: action
});
disconnect();
Final Notes:
For a hook-based store (
const useStore = createNeutrixStore(...)
), you typically reference.store
when passing it toconnectStore
orconnectStores
.If you used a provider-based approach (
{ store, Provider, useStore }
), pass store directly.