Last active
May 19, 2019 14:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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