Skip to content

Instantly share code, notes, and snippets.

@hasparus
Last active May 19, 2019 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasparus/f2e0a2312edb1e5d08fb663263c7cf2f to your computer and use it in GitHub Desktop.
Save hasparus/f2e0a2312edb1e5d08fb663263c7cf2f to your computer and use it in GitHub Desktop.
super hacky devtools for Zustand -- leverage React DevTools to edit your store state
import React, { useEffect, useRef } from 'react';
import { render } from 'react-dom';
type ZustandStore = ReturnType<typeof import('zustand').default>[1];
/**
* @example
* const [useStore, store] = createStore(set => { /* ... */ });
* if (process.env.NODE_ENV === 'development') {
* zustandDevtools.mountStoreSinkDevtool('MyStore', store);
* }
*/
export function mountStoreSinkDevtool(
storeName: string,
store: ZustandStore,
rootElement?: HTMLElement
) {
type StoreState = ReturnType<ZustandStore['getState']>;
const externalUpdates = {
count: 0,
};
const ZustandDevtool: React.FC<StoreState> = props => {
const allUpdatesCount = useRef(externalUpdates.count); // TODO: Simplify these two counters to a boolean
useEffect(() => {
allUpdatesCount.current += 1;
if (allUpdatesCount.current === externalUpdates.count + 1) {
// DevTools update
allUpdatesCount.current -= 1;
store.setState(props);
}
});
return null;
};
(ZustandDevtool as any).displayName = `((${storeName})) devtool`;
if (!rootElement) {
let root = document.getElementById('zustand-hacky-devtools');
if (!root) {
root = document.createElement('div');
root.id = 'zustand-hacky-devtools';
}
document.body.appendChild(root);
// tslint:disable-next-line:no-parameter-reassignment
rootElement = root;
}
const renderDevtool = (state: StoreState) => {
render(<ZustandDevtool {...state} />, rootElement!);
externalUpdates.count += 1;
};
renderDevtool(store.getState());
store.subscribe(renderDevtool);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment