Plugins can be imported directly from react-thermals
.
Log store lifecycle events to the console. Helpful for debugging timing or writing plugins.
import { consoleLogger } from 'react-thermals';
// log all store events to console
store.plugin(consoleLogger());
// log all AfterUpdate events to console
store.plugin(consoleLogger({ eventTypes: ['AfterUpdate'] }));
Turn the store into an observable to observe state changes.
import { observable } from 'react-thermals';
const store = createStore(/*...*/);
// turn store into an observable
store.plugin(observable());
store.subscribe(observer);
// observer.next(newState) called AfterUpdate
// observer.error() called on SetterRejection
// observer.complete() called AfterLastUnmount
// or you can simply provide next, error, and complete functions
store.subscribe(next, error, complete);
Read and save all or some store data to localStorage or sessionStorage.
When first component mounts, load state or partial state from localStorage. When state is updated, save state or partial state to localStorage.
import { persistState } from 'react-thermals';
const store = createStore({
query: '',
sort: 'name',
// ...
});
// persist "sort" value to localStorage
store.plugin(
persistState({
storage: localStorage,
fields: ['sort'], // save only "sort" to localStorage
key: 'user-search', // the localStorage key to store under
})
);
Read and save all or some store data to the URL.
When first component mounts, load state or partial state from the URL. When state is updated, save state or partial state to the URL.
import qs from 'qs';
import { syncUrl } from 'react-thermals';
const store = createStore({
query: '', page: 1,
sort: 'name' ,
// ...
});
store.plugin(
syncUrl({
// use history.replaceState to avoid back-button state
replace: true,
// save query and page to URL
schema: {
query: 'string',
page: 'number', // when pulling from URL, parse as Number
},
// OPTIONAL:
// override the default use of URLSearchParams for serializing
// and deserializing
parse: qs.parse,
stringify: qs.stringify,
})
);
Valid schema types:
string and string[]
number
andnumber[]
Date
andDate[]
boolean
andboolean[]
Maintain an undo history and add .undo(), .redo(), .jump(), .jumpTo() methods to the store.
import { undo } from 'react-thermals';
const store = createStore({
/* ... */
});
store.plugin(undo({ maxSize: 20 }));
//...
store.undo();
store.redo();
store.jumpTo(5);
Here is an example plugin that loads and saves user settings.
export default function syncUserSettings({ baseUrl }) {
return function plugin(store) {
store.on('AfterFirstMount', evt => {
fetch(`${baseUrl}/api/user/settings`)
.then(r => r.json())
.then(settings => {
store.mergeState({ settings });
});
});
store.on('AfterUpdate', evt => {
fetch({
method: 'POST',
url: `${baseUrl}/api/user/settings`,
data: evt.data.next.settings,
});
});
};
}