Skip to content

Commit

Permalink
add getStore
Browse files Browse the repository at this point in the history
  • Loading branch information
wagnercsfilho committed Jul 13, 2020
1 parent 0389f00 commit 52b84a0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
21 changes: 12 additions & 9 deletions src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import React, { createContext, useContext, useEffect } from "react";
import { useImmer } from "use-immer";

const contexts = {};
const stores = {};
const _stores = {};

export const getStore = (key) => {
return _stores[key];
};

function mergeDeep(target, source) {
const isObject = (obj) => obj && typeof obj === "object";
Expand All @@ -30,7 +34,7 @@ function mergeDeep(target, source) {

const StoreHooks = (fn, storeKey, { enableCache, storage }) => {
const [store, setStore] = useImmer(() => {
const _store = fn({ ...stores });
const _store = fn({ getStore });

return {
..._store,
Expand All @@ -39,7 +43,7 @@ const StoreHooks = (fn, storeKey, { enableCache, storage }) => {
.reduce((acc, attr) => {
acc[attr] = (...args) =>
setStore((draft) => {
_store[attr].apply(draft, [...args, { ...stores }]);
_store[attr].apply(draft, [...args, { ..._stores }]);

if (enableCache && storage)
storage.setItem("@store:" + storeKey, JSON.stringify(draft));
Expand Down Expand Up @@ -68,17 +72,14 @@ const StoreHooks = (fn, storeKey, { enableCache, storage }) => {
initCache();
}, []);

stores[storeKey] = store;
return store;
};

const CreateProvider = React.memo(
({ Provider, store, storage, enableCache, children, storeKey }) => {
return (
<Provider value={store(storeKey, { enableCache, storage })}>
{children}
</Provider>
);
_stores[storeKey] = store(storeKey, { enableCache, storage });

return <Provider value={_stores[storeKey]}>{children}</Provider>;
}
);

Expand All @@ -92,10 +93,12 @@ export const StoreProvider = ({ stores, storage, enableCache, children }) => {
return Object.keys(stores).reduce((acc, key) => {
const StoreContext = createContext();
contexts[key] = StoreContext;

return (
<CreateProvider
Provider={StoreContext.Provider}
store={stores[key]}
stores={stores}
storeKey={key}
enableCache={enableCache}
storage={storage}
Expand Down
7 changes: 4 additions & 3 deletions src/stores/todo.store.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Store } from "../lib";

export const TodoStore = Store(({}) => {
export const TodoStore = Store(({ getStore }) => {
return {
todos: [],
add(description, { UserStore }) {
add(description) {
this.todos.push({
id: new Date().getTime(),
description: description + " - from: " + UserStore.currentUser,
description:
description + " - from: " + getStore("UserStore").currentUser,
done: false,
});
},
Expand Down

0 comments on commit 52b84a0

Please sign in to comment.