import create from 'zustand';
import createContext from 'zustand/context';
import { persist } from 'zustand/middleware';
let store;
const initialState = {
loading: false,
cart: {
cartItems: {},
invoiceData: {},
count: 0,
},
};
const zustandContext = createContext();
export const Provider = zustandContext.Provider;
// An example of how to get types
/** @type {import('zustand/index').UseStore<typeof initialState>} */
export const useStore = zustandContext.useStore;
export const initializeStore = (preloadedState = {}) => {
return create(
persist(
(set, get) => ({
...initialState,
...preloadedState,
updateCart: (cartData) => {
set({
cart: cartData,
});
},
setLoading: (val) => {
set({
loading: val,
});
},
modifyCart: (product, qty, type) => {
const cartData = get().cart;
// cart operations
set({
cart: tmpCartData,
});
},
}),
{
name: 'cartData',
}
)
);
};
export function useCreateStore(initialState) {
const [cartData, setCartData] = useState(null);
const [userCart, setCart] = useLocalStorage('cartData', {});
const { state: { cart = {} } = {} } = userCart;
if (typeof window === 'undefined') {
return () => initializeStore(initialState);
}
store = store ?? initializeStore(initialState);
useLayoutEffect(() => {
if (initialState && store) {
store.setState({
...store.getState(),
...initialState,
});
}
}, [initialState]);
useLayoutEffect(() => {
(async () => {
store.setState({
...store.getState(),
cart: { ...cart },
loading: true,
});
})();
}, []);
return () => store;
}
此代码的灵感来自 Zusand 文档以及 NextJS 和 Zusand 样板。我需要将此数据与浏览器的本地存储同步。但是,在 modifyCart 中调用 'set' 方法会导致无限渲染。我还没有找到足够的文档。我应该如何调试这样的问题?