UNPKG

zippy-store

Version:

A lightweight and versatile global state management solution designed for seamless integration in both JavaScript and React applications. Provides a simple and efficient way to manage shared state across components and even in non-React JavaScript environ

43 lines 2.25 kB
/* eslint-disable @typescript-eslint/no-explicit-any */ import { useEffect, useRef, useState } from "react"; import store from "./store"; // Function to create a store for a given storeKey const create = (storeKey, stateAndActionsFn, persist = false) => { //creating initial store for the given storeKey (shared store) const { dispatch } = store.createStore(storeKey, stateAndActionsFn, persist); // Explicitly type createStore call return (selector) => { const { current: uuid } = useRef(Symbol()); // Initialize state with only the selected keys if selector is provided const [state, setState] = useState(() => { const storeState = store.getState(storeKey); // Explicitly type getState call return selector ? selector(storeState) : storeState; // Non-null assertion is safe after check }); useEffect(() => { // Callback function to update state when store changes const cb = (newState) => { // Only update the state for the keys being listened to if selector is provided const newStateWithSelector = selector ? selector(Object.assign(Object.assign({}, state), newState)) : Object.assign(Object.assign({}, state), newState); const stateToUpdate = {}; for (const key in state) { if (state[key] !== newStateWithSelector[key]) { stateToUpdate[key] = newStateWithSelector[key]; } } // Update state only if there are changes if (Object.keys(stateToUpdate).length) { setState((prevState) => (Object.assign(Object.assign({}, prevState), stateToUpdate))); } }; // Register the callback for this instance const unsubscribe = store.subscribe(storeKey, cb); // Cleanup function to remove the callback when component unmounts return () => { unsubscribe(); }; }, [state, uuid, selector]); // Return both state and actions for usage return Object.assign({ dispatch }, state); }; }; export default create; //# sourceMappingURL=create.js.map