@wener/console
Version:
Base console UI toolkit
43 lines (42 loc) • 1.37 kB
JavaScript
import { createElement, createContext as reactCreateContext, useContext, useMemo, useRef } from "react";
import { useStore } from "zustand";
/**
* v4 移除
*
* @see https://github.com/pmndrs/zustand/discussions/1180
*/ export function createStoreContext() {
const ZustandContext = reactCreateContext(undefined);
const Provider = ({ createStore, children })=>{
const storeRef = useRef();
if (!storeRef.current) {
storeRef.current = createStore();
}
return createElement(ZustandContext.Provider, {
value: storeRef.current
}, children);
};
const useContextStore = (selector, equalityFn)=>{
const store = useContext(ZustandContext);
if (!store) {
throw new Error('Seems like you have not used zustand provider as an ancestor.');
}
return useStore(store, selector, equalityFn);
};
const useStoreApi = ()=>{
const store = useContext(ZustandContext);
if (!store) {
throw new Error('Seems like you have not used zustand provider as an ancestor.');
}
return useMemo(()=>({
...store
}), [
store
]);
};
return {
Provider,
useStore: useContextStore,
useStoreApi
};
}
//# sourceMappingURL=createStoreContext.js.map