-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
index.js
38 lines (33 loc) 路 1.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import React, { useState, useContext, createContext } from "react";
export default function createStore(store = {}) {
const storeUtils = Object.keys(store).reduce((o, key) => {
const fieldCapitalized = `${key[0].toUpperCase()}${key.slice(
1,
key.length
)}`;
const context = createContext(store[key]);
return {
...o,
contexts: [...(o.contexts || []), { context, key }],
[`use${fieldCapitalized}`]: () => useContext(context)
};
}, {});
storeUtils.Provider = ({ children }) => {
const Empty = ({ children }) => children;
const Component = storeUtils.contexts
.map(({ context, key }) => ({ children }) => {
const ctx = useState(store[key]);
return <context.Provider value={ctx}>{children}</context.Provider>;
})
.reduce(
(RestProviders, Provider) => ({ children }) => (
<Provider>
<RestProviders>{children}</RestProviders>
</Provider>
),
Empty
);
return <Component>{children}</Component>;
};
return storeUtils;
}