Gathering detailed insights and metrics for @codewithdan/observable-store-extensions
Gathering detailed insights and metrics for @codewithdan/observable-store-extensions
Gathering detailed insights and metrics for @codewithdan/observable-store-extensions
Gathering detailed insights and metrics for @codewithdan/observable-store-extensions
Observable Store provides a simple way to manage state in Angular, React, Vue.js and other front-end applications.
npm install @codewithdan/observable-store-extensions
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
638 Stars
578 Commits
121 Forks
27 Watching
3 Branches
9 Contributors
Updated on 01 Oct 2024
Minified
Minified + Gzipped
TypeScript (91.56%)
HTML (5.05%)
JavaScript (2.03%)
CSS (0.68%)
SCSS (0.68%)
Cumulative downloads
Total Downloads
Last day
-20.9%
102
Compared to previous day
Last week
3.2%
652
Compared to previous week
Last month
20.5%
2,720
Compared to previous month
Last year
-8.7%
28,030
Compared to previous year
2
2
Observable Store is a front-end state management library that provides a simple yet powerful way to manage state in front-end applications. Front-end state management has become so complex that many of us spend more hours working on the state management code than on the rest of the application. Observable Store has one overall goal - "keep it simple".
The goal of observable store is to provide a small, simple, and consistent way to manage state in any front-end application (Angular, React, Vue.js or any other) while achieving many of the key goals offered by more complex state management solutions. While many front-end frameworks/libraries provide state management functionality, many can be overly complex and are only useable with the target framework/library. Observable Store is simple and can be used with any front-end JavaScript codebase.
Here's a simple example of getting started using Observable Store. Note that if you're using TypeScript you can provide additional details about the store state by using an interface or class (additional examples of that can be found below).
Install the Observable Store package:
npm install @codewithdan/observable-store
Install RxJS - a required peer dependency if your project doesn't already reference it:
npm install rxjs
Create a class that extends ObservableStore
. Optionally pass settings into super()
in your class's constructor (view Observable Store settings). While this shows a pure JavaScript approach, ObservableStore also accepts a generic that represents the store type. See the Angular example below for more details.
1export class CustomersStore extends ObservableStore { 2 3 constructor() { 4 super({ /* add settings here */ }); 5 } 6 7}
Update the store state using setState(state, action)
.
1addCustomerToStore(newCustomer) { 2 this.setState({ customer: newCustomer }, 'add_customer'); 3}
Retrieve store state using getState()
.
1getCustomerFromStore() { 2 this.getState().customer; 3}
Subscribe to store changes in other areas of the application by using the store's stateChanged
observable.
1// Create CustomersStore object or have it injected if platform supports that 2 3init() { 4 this.storeSub = this.customersStore.stateChanged.subscribe(state => { 5 if (state) { 6 this.customer = state.customer; 7 } 8 }); 9} 10 11// Note: Would need to unsubscribe by calling this.storeSub.unsubscribe() 12// as the target object is destroyed
Access store state history in CustomersStore
by calling the stateHistory
property (this assumes that the trackStateHistory
setting is set to true
)
1console.log(this.stateHistory);
Observable Store Global Settings
Open the samples
folder available at the Github repo and follow the instructions provided in the readme file for any of the provided sample projects.
See the samples
folder in the Github repo for examples of using Observable Store with Angular.
Create an Angular application using the Angular CLI or another option.
Install @codewithdan/observable-store
:
npm install @codewithdan/observable-store
Add an interface or model object that represents the shape of the data you'd like to add to your store. Here's an example of an interface to store customer state:
1export interface StoreState { 2 customers: Customer[]; 3 customer: Customer; 4}
Add a service (you can optionally calll it a store if you'd like) that extends ObservableStore
1@Injectable() 2export class CustomersService extends ObservableStore<StoreState> { 3 4}
In the constructor add a call to super()
. The store allows you to turn tracking of store state changes on and off using the trackStateHistory
property. See a list of Observable Store Settings.
1constructor() { 2 super({ trackStateHistory: true }); 3}
Add functions into your service/store to retrieve, store, sort, filter, or perform any actions you'd like. To update the store call setState()
and pass the action that is occuring as well as the store state. To get the state out of the store call getState()
. Note that store data is immutable and getState()
always returns a clone of the store data. Here's a simple example:
1@Injectable() 2export class CustomersService extends ObservableStore<StoreState> { 3 sorterService: SorterService; 4 5 constructor(sorterService: SorterService) { 6 const initialState = { 7 customers: [], 8 customer: null 9 } 10 super({ trackStateHistory: true }); 11 this.setState(initialState, 'INIT_STATE'); 12 this.sorterService = sorterService; 13 } 14 15 get() { 16 const { customers } = this.getState(); 17 if (customers) { 18 return of(customers); 19 } 20 // call server and get data 21 // assume async call here that returns observable 22 return asyncData; 23 } 24 25 add(customer: Customer) { 26 let state = this.getState(); 27 state.customers.push(customer); 28 this.setState({ customers: state.customers }, 'ADD_CUSTOMER'); 29 } 30 31 remove() { 32 let state = this.getState(); 33 state.customers.splice(state.customers.length - 1, 1); 34 this.setState({ customers: state.customers }, 'REMOVE_CUSTOMER'); 35 } 36 37 sort(property: string = 'id') { 38 let state = this.getState(); 39 const sortedState = this.sorterService.sort(state.customers, property); 40 this.setState({ customers: sortedState }, 'SORT_CUSTOMERS'); 41 } 42 43}
While strings are used for actions in the prior examples, you can use string enums (a TypeScript feature) as well if you want to have a set list of actions to choose from:
1 export enum CustomersStoreActions { 2 AddCustomer = 'ADD_CUSTOMER', 3 RemoveCustomer = 'REMOVE_CUSTOMER', 4 GetCustomers = 'GET_CUSTOMERS', 5 SortCustomers = 'SORT_CUSTOMERS' 6 } 7 8 // Example of using the enum in a store 9 add(customer: Customer) { 10 let state = this.getState(); 11 state.customers.push(customer); 12 this.setState({ customers: state.customers }, CustomersStoreActions.AddCustomer); 13 }
If you want to view all of the changes to the store you can access the stateHistory
property:
1console.log(this.stateHistory);
An example of the state history output is shown next:
1// example stateHistory output 2[ 3 { 4 "action": "INIT_STATE", 5 "beginState": null, 6 "endState": { 7 "customers": [ 8 { 9 "id": 1545847909628, 10 "name": "Jane Doe", 11 "address": { 12 "street": "1234 Main St.", 13 "city": "Phoenix", 14 "state": "AZ", 15 "zip": "85258" 16 } 17 } 18 ], 19 "customer": null 20 } 21 }, 22 { 23 "action": "ADD_CUSTOMER", 24 "beginState": { 25 "customers": [ 26 { 27 "id": 1545847909628, 28 "name": "Jane Doe", 29 "address": { 30 "street": "1234 Main St.", 31 "city": "Phoenix", 32 "state": "AZ", 33 "zip": "85258" 34 } 35 } 36 ], 37 "customer": null 38 }, 39 "endState": { 40 "customers": [ 41 { 42 "id": 1545847909628, 43 "name": "Jane Doe", 44 "address": { 45 "street": "1234 Main St.", 46 "city": "Phoenix", 47 "state": "AZ", 48 "zip": "85258" 49 } 50 }, 51 { 52 "id": 1545847921260, 53 "name": "Fred", 54 "address": { 55 "street": "1545847921260 Main St.", 56 "city": "Phoenix", 57 "state": "AZ", 58 "zip": "85258" 59 } 60 } 61 ], 62 "customer": null 63 } 64 } 65]
Any component can be notified of changes to the store state by injecting the store and then subscribing to the stateChanged
observable:
1customers: Customer[]; 2storeSub: Subscription; 3 4constructor(private customersService: CustomersService) { } 5 6ngOnInit() { 7 // If using async pipe (recommend renaming customers to customers$) 8 // this.customers$ = this.customersService.stateChanged; 9 10 // Can subscribe to stateChanged observable of the store 11 this.storeSub = this.customersService.stateChanged.subscribe(state => { 12 if (state) { 13 this.customers = state.customers; 14 } 15 }); 16 17 // Can call service/store to get data directly 18 // It won't fire when the store state changes though in this case 19 //this.storeSub = this.customersService.get().subscribe(custs => this.customers = custs); 20}
You'll of course want to unsubscribe in ngOnDestroy()
(check out SubSink on npm for a nice way to easily subscribe/unsubscribe):
1ngOnDestroy() { 2 if (this.storeSub) { 3 this.storeSub.unsubscribe(); 4 } 5}
See the samples
folder in the Github repo for examples of using Observable Store with React.
Create a React application using the create-react-app
or another option.
Install @codewithdan/observable-store
:
npm install @codewithdan/observable-store
Install RxJS (a required peer dependency):
npm install rxjs
Add a store class (you can call it whatever you'd like) that extends ObservableStore
1export class CustomersStore extends ObservableStore { 2 3}
In the constructor add a call to super()
. The store allows you to turn tracking of store state changes on and off using the trackStateHistory
property. See a list of Observable Store Settings.
1export class CustomersStore extends ObservableStore { 2 constructor() { 3 super({ trackStateHistory: true }); 4 } 5}
Add functions into your service/store to retrieve, store, sort, filter, or perform any actions you'd like. To update the store call setState()
and pass the action that is occuring as well as the store state. To get the state out of the store call getState()
. Note that store data is immutable and getState()
always returns a clone of the store data. Here's a simple example:
1export class CustomersStore extends ObservableStore { 2 3 constructor() { 4 super({ trackStateHistory: true }); 5 } 6 7 fetchCustomers() { 8 // using fetch api here to keep it simple, but any other 9 // 3rd party option will work (Axios, Ky, etc.) 10 return fetch('/customers') 11 .then(response => response.json()) 12 .then(customers => { 13 this.setState({ customers }, 'GET_CUSTOMERS'); 14 return customers; 15 }); 16 } 17 18 getCustomers() { 19 let state = this.getState(); 20 // pull from store cache 21 if (state && state.customers) { 22 return this.createPromise(null, state.customers); 23 } 24 // doesn't exist in store so fetch from server 25 else { 26 return this.fetchCustomers(); 27 } 28 } 29 30 getCustomer(id) { 31 return this.getCustomers() 32 .then(custs => { 33 let filteredCusts = custs.filter(cust => cust.id === id); 34 const customer = (filteredCusts && filteredCusts.length) ? filteredCusts[0] : null; 35 this.setState({ customer }, 'GET_CUSTOMER'); 36 return customer; 37 }); 38 } 39 40 createPromise(err, result) { 41 return new Promise((resolve, reject) => { 42 return err ? reject(err) : resolve(result); 43 }); 44 } 45}
While strings are used for actions in the prior example, you can use an object as well if you want to have a set list of actions to choose from:
1const CustomersStoreActions = { 2 GetCustomers: 'GET_CUSTOMERS', 3 GetCustomer: 'GET_CUSTOMER' 4}; 5 6 // Example of using the enum in a store 7getCustomer(id) { 8 return this.getCustomers() 9 .then(custs => { 10 let filteredCusts = custs.filter(cust => cust.id === id); 11 const customer = (filteredCusts && filteredCusts.length) ? filteredCusts[0] : null; 12 this.setState({ customer }, CustomersStoreActions.GetCustomer); 13 return customer; 14 }); 15}
Export your store. A default export is used here:
1export default new CustomersStore();
If you want to view all of the changes to the store you can access the store's stateHistory
property:
1console.log(this.stateHistory); 2 3// example stateHistory output 4[ 5 { 6 "action": "INIT_STATE", 7 "beginState": null, 8 "endState": { 9 "customers": [ 10 { 11 "id": 1545847909628, 12 "name": "Jane Doe", 13 "address": { 14 "street": "1234 Main St.", 15 "city": "Phoenix", 16 "state": "AZ", 17 "zip": "85258" 18 } 19 } 20 ], 21 "customer": null 22 } 23 }, 24 { 25 "action": "ADD_CUSTOMER", 26 "beginState": { 27 "customers": [ 28 { 29 "id": 1545847909628, 30 "name": "Jane Doe", 31 "address": { 32 "street": "1234 Main St.", 33 "city": "Phoenix", 34 "state": "AZ", 35 "zip": "85258" 36 } 37 } 38 ], 39 "customer": null 40 }, 41 "endState": { 42 "customers": [ 43 { 44 "id": 1545847909628, 45 "name": "Jane Doe", 46 "address": { 47 "street": "1234 Main St.", 48 "city": "Phoenix", 49 "state": "AZ", 50 "zip": "85258" 51 } 52 }, 53 { 54 "id": 1545847921260, 55 "name": "Fred", 56 "address": { 57 "street": "1545847921260 Main St.", 58 "city": "Phoenix", 59 "state": "AZ", 60 "zip": "85258" 61 } 62 } 63 ], 64 "customer": null 65 } 66 } 67]
Import your store into a component:
1import CustomersStore from '../stores/CustomersStore';
Now use your store to access or update data. Any component can be notified of changes to the store state by subscribing to the stateChanged
observable:
1storeSub = null; 2 3componentDidMount() { 4 // ###### CustomersStore ######## 5 // Option 1: Subscribe to store changes 6 // Useful when a component needs to be notified of changes but won't always 7 // call store directly. 8 this.storeSub = CustomersStore.stateChanged.subscribe(state => { 9 if (state) { 10 this.setState({ customers: state.customers }); 11 } 12 }); 13 14 // In this example we trigger getting the customers (code above receives the customers) 15 CustomersStore.getCustomers(); 16 17 // Option 2: Get data directly from store 18 // If a component triggers getting the data it can retrieve it directly rather than subscribing 19 // CustomersStore.getCustomers() 20 // .then(customers => { 21 // .... 22 // }); 23}
You'll want to unsubscribe in componentWillUnmount()
:
1componentWillUnmount() { 2 if (this.storeSub) { 3 this.storeSub.unsubscribe(); 4 } 5}
....
Observable Store provides a simple API that can be used to get/set state, subscribe to store state changes, and access state history. If you're new to TypeScript generics, the T
shown in the APIs below represents your store's state.
Functions | Description |
---|---|
dispatchState(stateChanges: Partial<T>, dispatchGlobalState: boolean = true) : T | Dispatch the store's state without modifying the state. Service state can be dispatched as well as the global store state. If dispatchGlobalState is false then global state will not be dispatched to subscribers (defaults to true ). |
getState(deepCloneReturnedState: boolean = true) : T | Retrieve store's state. If using TypeScript (optional) then the state type defined when the store was created will be returned rather than any . The deepCloneReturnedState boolean parameter (default is true) can be used to determine if the returned state will be deep cloned or not. If set to false, a reference to the store state will be returned and it's up to the user to ensure the state isn't change from outside the store. Setting it to false can be useful in cases where read-only cached data is stored and must be retrieved as quickly as possible without any cloning. |
getStateProperty<TProp>(propertyName: string, deepCloneReturnedState: boolean = true) : TProp | Retrieve a specific property from the store's state which can be more efficient than getState() since only the defined property value will be returned (and cloned) rather than the entire store value. If using TypeScript (optional) then the generic property type used with the function call will be the return type. |
getStateSliceProperty<TProp>(propertyName: string, deepCloneReturnedState: boolean = true): TProp | If a stateSliceSelector has been set, the specific slice will be searched first. Retrieve a specific property from the store's state which can be more efficient than getState() since only the defined property value will be returned (and cloned) rather than the entire store value. If using TypeScript (optional) then the generic property type used with the function call will be the return type. |
logStateAction(state: any, action: string): void | Add a custom state value and action into the state history. Assumes trackStateHistory setting was set on store or using the global settings. |
resetStateHistory(): void | Reset the store's state history to an empty array. |
setState(state: T, action: string, dispatchState: boolean = true, deepCloneState: boolean = true) : T | Set the store state. Pass the state to be updated as well as the action that is occuring. The state value can be a function (see example below). The latest store state is returned and any store subscribers are notified of the state change. The dispatchState parameter can be set to false if you do not want to send state change notifications to subscribers. The deepCloneReturnedState boolean parameter (default is true) can be used to determine if the state will be deep cloned before it is added to the store. Setting it to false can be useful in cases where read-only cached data is stored and must added to the store as quickly as possible without any cloning. |
static addExtension(extension: ObservableStoreExtension) | Used to add an extension into ObservableStore. The extension must implement the ObservableStoreExtension interface. |
static clearState(): void | Clear/null the store state across all services that use it. |
static initializeState(state: any) | Used to initialize the store's state. An error will be thrown if this is called and store state already exists so this should be set when the application first loads. No notifications are sent out to store subscribers when the store state is initialized. |
static resetState(state, dispatchState: boolean = true) | Used to reset the state of the store to a desired value for all services that derive from ObservableStore |
Properties | Description |
---|---|
globalStateChanged: Observable<any> | Subscribe to global store changes i.e. changes in any slice of state of the store. The global store may consist of 'n' slices of state each managed by a particular service. This property notifies of a change in any of the 'n' slices of state. Returns an RxJS Observable containing the current store state. |
globalStateWithPropertyChanges: Observable<StateWithPropertyChanges<any>> | Subscribe to global store changes i.e. changes in any slice of state of the store and also include the properties that changed as well. The global store may consist of 'n' slices of state each managed by a particular service. This property notifies of a change in any of the 'n' slices of state. Upon subscribing to globalStateWithPropertyChanges you will get back an object containing state (which has the current store state) and stateChanges (which has the individual properties/data that were changed in the store). |
stateChanged: Observable<T> | Subscribe to store changes in the particlar slice of state updated by a Service. If the store contains 'n' slices of state each being managed by one of 'n' services, then changes in any of the other slices of state will not generate values in the stateChanged stream. Returns an RxJS Observable containing the current store state (or a specific slice of state if a stateSliceSelector has been specified). |
stateWithPropertyChanges: Observable<StateWithPropertyChanges<T>> | Subscribe to store changes in the particlar slice of state updated by a Service and also include the properties that changed as well. Upon subscribing to stateWithPropertyChanges you will get back an object containing state (which has the current slice of store state) and stateChanges (which has the individual properties/data that were changed in the store). |
stateHistory: StateHistory | Retrieve state history. Assumes trackStateHistory setting was set on the store. |
static allStoreServices: any[] | Provides access to all services that interact with ObservableStore. Useful for extensions that need to be able to access a specific service. |
static globalSettings: ObservableStoreGlobalSettings | get/set global settings throughout the application for ObservableStore. See the Observable Store Settings below for additional information. Note that global settings can only be set once as the application first loads. |
static isStoreInitialized: boolean | Used to determine if the the store's state is currently initialized. This is useful if there are multiple scenarios where the store might have already been initialized such as during unit testing etc or after the store has been cleared. |
Note that TypeScript types are used to describe parameters and return types above. TypeScript is not required to use Observable Store though.
Here's an example of passing a function to setState()
. This allows the previous state to be accessed directly while setting the new state.
1this.setState(prevState => { 2 return { customers: this.sorterService.sort(prevState.customers, property) }; 3}, 'SORT_CUSTOMERS');
Observable Store settings can be passed when the store is initialized (when super() is called in a service). This gives you control over how things work for each service within your application that extends the store.
Setting | Description |
---|---|
trackStateHistory: boolean | Determines if the store's state will be tracked or not (defaults to false). Pass it when initializing the Observable Store (see examples above). When true , you can access the store's state history by calling the stateHistory property. |
logStateChanges: boolean | Log any store state changes to the browser console (defaults to false). |
includeStateChangesOnSubscribe: boolean | DEPRECATED. Returns the store state by default when false (default). Set to true if you want to receive the store state as well as the specific properties/data that were changed when the stateChanged subject emits. Upon subscribing to stateChanged you will get back an object containing state (which has the current store state) and stateChanges (which has the individual properties/data that were changed in the store). Since this is deprecated, use stateWithPropertyChanges or globalStateWithPropertyChanges instead. |
stateSliceSelector: function | Function to select the slice of the store being managed by this particular service. If specified then the specific state slice is returned. If not specified then the total state is returned (defaults to null). |
Example of passing settings to the store:
1export class CustomersStore extends ObservableStore { 2 3 constructor() { 4 super({ /* add settings here */ }); 5 } 6 7}
The stateSliceSelector()
function can be used to return a "slice" of the store state that is managed by a Service to any subscribers. For example, if a CustomersService manages a customers
collection and a selectedCustomer
object you can return only the selectedCustomer
object to subscribers (rather than customers
and selectedCustomer
) by creating a stateSliceSelector()
function.
Define it as you initialize the service when passing a settings
object to super()
in the Service's constructor.
1export class CustomersService extends ObservableStore<StoreState> { 2 constructor() { 3 super({ stateSliceSelector: state => { 4 return { 5 customer: state.selectedCustomer 6 // return other parts of the store here too if desired 7 }; 8 } 9 }); 10 } 11}
You can set the following Observable Store settings globally for the entire application if desired. For details, view the Observable Store Settings section. This allows you to define the settings once and all services that extend Observable Store will automatically pick these settings up. You can override these properties at the service level as well which is nice when you want a particular service to have more logging (as an example) while other services don't.
trackStateHistory
logStateChanges
includeStateChangesOnSubscribe
[DEPRECATED]isProduction
[RESERVED FOR FUTURE USE]Global store settings are defined ONCE when the application first initializes and BEFORE the store has been used:
1ObservableStore.globalSettings = { /* pass settings here */ };
Observable Store now supports extensions. These can be added when the application first loads by calling ObservableStore.addExtension()
.
Redux DevTools Extension
The first built-in extension adds Redux DevTools integration into applications that use Observable Store. The extension can be found in the @codewithdan/observable-store-extensions
package.
Note about Angular 9/Ivy and the Redux DevTools Support
While the code is in place to support it, The Observable Store Redux DevTools currently do not work with Angular 9 and Ivy. Once the findProviders()
API is fully implemented and released by Angular then support will be finalized for the Redux DevTools.
Note about the __devTools
Store Property:
When the Redux DevTools extension is enabled it will add routing information into your store using a property called __devTools
. This property is used to enable the Redux DevTools time travel feature and can be useful for associating different action states with a given route when manually looking at store data using the DevTools. If the Redux DevTools extension is not enabled (such as in production scenarios) then the __devTools
property will not be added into your store.
Integrating Angular with the Redux DevTools
See the example in the samples/angular-store-edits
folder.
Install the extensions package:
npm install @codewithdan/observable-store-extensions
Add the following into main.ts
and ensure that you set trackStateHistory
to true
:
1import { ObservableStore } from '@codewithdan/observable-store'; 2import { ReduxDevToolsExtension } from '@codewithdan/observable-store-extensions'; 3 4... 5 6ObservableStore.globalSettings = { 7 trackStateHistory: true 8}; 9ObservableStore.addExtension(new ReduxDevToolsExtension());
Install the Redux DevTools Extension in your browser, run your Angular application, and open the Redux DevTools extension.
Integrating React with the Redux DevTools
See the example in the samples/react-store
folder.
Install the extensions package:
npm install @codewithdan/observable-store-extensions
Add the history
prop to your router:
1import React from 'react'; 2import { Router, Route, Redirect } from 'react-router-dom'; 3import { createBrowserHistory } from 'history';| 4 5export const history = createBrowserHistory(); 6 7... 8 9const Routes = () => ( 10 <Router history={history}> 11 <div> 12 <!-- Routes go here --> 13 </div> 14 </Router> 15); 16 17export default Routes; 18
Add the following into index.js
and ensure that you set trackStateHistory
to true
and pass the history
object into the ReduxDevToolsExtension
constructor as shown:
1import Routes, { history } from './Routes'; 2import { ObservableStore } from '@codewithdan/observable-store'; 3import { ReduxDevToolsExtension } from '@codewithdan/observable-store-extensions'; 4 5... 6 7ObservableStore.globalSettings = { 8 trackStateHistory: true 9}; 10ObservableStore.addExtension(new ReduxDevToolsExtension({ 11 reactRouterHistory: history 12})); 13 14ReactDOM.render(<Routes />, document.getElementById('root'));
Install the Redux DevTools Extension in your browser, run your React application, and open the Redux DevTools extension.
While you can enable the Redux DevTools extension in production it's normally recommended that you remove it. That can be done through a custom build process or by checking the environment where your code is running.
Angular Example
1import { environment } from './environments/environment'; 2 3if (!environment.production) { 4 ObservableStore.addExtension(new ReduxDevToolsExtension()); 5}
React Example
1if (process.env.NODE_ENV !== 'production') { 2 ObservableStore.addExtension(new ReduxDevToolsExtension({ 3 reactRouterHistory: history 4 })); 5}
Added includeStateChangesOnSubscribe
setting (NOW DEPRECATED in 2+) for cases where a subscriber to stateChanged
wants to get the current state as well as the specific properties/data that were changes in the store. Defaults to false
so prior versions will only receive the current state by default which keeps patched versions compatible in the 1.0.x range.
Set the property to true
if you want to receive the store state as well as the specific properties/data that were changed when the stateChanged
subject emits. Upon subscribing to stateChanged
you will get back an object containing state
(which has the current store state) and stateChanges
(which has the individual properties/data that were changed in the store).
Changed updateState()
to _updateState()
since it's a private function. Remove tsconfig.json
from package.
Moved BehaviorSubject
into ObservableService
class so that if multiple instances of a wrapper around the store are created, subscribers can subscribe to the individual instances.
Added logStateChanges
setting to write out all state changes to the browser console when true. Defaults to false.
Added action to log output when logStateChanges
is true.
Thanks to a great contribution by Mickey Puri you can now globally subscribe to store changes (globalStateChanged
event) and even define state slices (stateSliceSelector
setting).
Merged in another contribution by Mickey Puri to ensure the settings defaults are always applied regardless of how many properties the user passes. Renamed
a settings default property (state_slice_selector
=> stateSliceSelector
). Added editable store example (update/delete functionality) for Angular in the samples
folder.
Minor updates to the readme.
Updated Angular example and added stateSliceSelector()
information in readme
Updated readme
Updated to latest version of RxJS. Removed subsink from the Angular Simple Store demo to just use a normal Subscription for unsubscribing (just to keep it more "native" and require less dependencies).
Internal type additions and tests contributed by @elAndyG (https://github.com/elAndyG).
stateChanged
and the overall API to provide better code help while using Observable Store.ObservableStore.globalSettings
property to allow store settings to be defined once if desired for an entire application rather than per service that uses the store.getState()
and setState()
now clone when the global settings isProduction
property is false (ObservableStore.globalSettings = { isProduction: false }
). When running in production mode no cloning is used in order to enhance performance since mutability issues would've been detected at development time. This technique is used with other store solutions as well. NOTE: isProduction is no longer used. See 2.0.1 below.Due to edge cases cloning is used in development and production. The isProduction
property is left in so builds are not broken, but currently isn't used.
In order to allow stateChanged
to be strongly-typed and also allow state changes with property changes to return a strongly-typed object as well, there are now 4 observable options to choose from when you want to know about changes to the store:
1// access state changes made by a service interacting with the store 2// allows access to slice of store state that service interacts with 3stateChanged: Observable<T> 4 5// access all state changes in the store regardless of where they're 6// made in the app 7globalStateChanged: Observable<any> 8 9// access state changes made by a service interacting with the 10// store and include the properties that were changed 11stateWithPropertyChanges: Observable<StateWithPropertyChanges<T>> 12 13// access all state changes in the store and include the 14// properties that were changed 15globalStateWithPropertyChanges: Observable<StateWithPropertyChanges<any>>
The includeStateChangesOnSubscribe
property is now deprecated since stateWithPropertyChanges
or globalStateWithPropertyChanges
can be used directly.
Thanks to Michael Turbe for the feedback and discussion on these changes.
This version adds a Redux DevTools Extension. A BIG thank you to @brandonroberts (https://github.com/brandonroberts) of NgRx fame for helping get me started integrating with the Redux DevTools.
New APIs:
allStoreServices
property is now available to access all services that extend ObservableStore and interact with the store. Used by the Redux DevTools extension and can be useful for future extensions.addExtension()
function. Used to add the Redux DevTools Extension and any future extensions.@codewithdan/observable-store-extensions
package for the redux devtools support.Minor updates to the Observable Store docs. Fixed a bug in the Redux DevTools extension that would throw an error when the extension wasn't installed or available. Updated readme to discuss how to disable extensions for production scenarios.
Thanks to Matthias Langhard for the feedback and discussion on these changes.
ObservableStore.initializeState()
API.ObservableStore.resetState()
API.resetState()
.Feedback from Severgyn and Luiz Filipe influenced this feature. Thanks folks!
Thanks to trentsteel84 for reporting the issue.
All calls to getState() and setState() clone data now due to edge issues that can arise otherwise with external references. Previously, it would
selectively clone based on dev or prod. All functions that get/set state now provide an optional deepClone
type of boolean property that can be used in cases where
it's not desirable to clone state (large amount of data being added to the store for caching for example).
Added ObservableStore.clearState()
API to null the store across all services that use it.
Added getStateProperty<T>(propName: string)
to retrieve a specific property from the store versus retrieving the entire store
as getState()
does.
Added support for cloning Map and Set objects in the interal cloner service used by Observable Store. Thanks to Chris Andrade for the initial contribution.
External APIs supported turning off cloning but internal APIs still cloned which isn't optimal for people storing a lot of data in the store. Thanks to Steve-RW for asking about it and for the PR that fixed it.
Adds a getStateSliceProperty()
function. Thanks to Connor Smith for the contribution. Added strict=true
support into Observable Store library tsconfig.json files.
Updates to documentation.
Update readme link to Redux DevTools. Thanks to Ravi Mathpal for the information.
New isStoreInitialized
property added. Thanks to Jason Landbridge for the PR!
See the README.md
file in the modules
folder.
No vulnerabilities found.
No security vulnerabilities found.