react-rooks
Version:
Store management for React and React Native with simple hooks !
36 lines (35 loc) • 1.3 kB
JavaScript
import * as React from "react";
import Rook from "./rook";
export const createUseRook = (context) => (key) => {
const { store, update } = React.useContext(context);
if (key === undefined) {
// Quand key est undefined, on retourne le store entier et la fonction update
return [store, update];
}
const setValue = (value) => {
if (typeof value === "function") {
const transformValue = value;
update({
[key]: transformValue(store[key]),
});
return;
}
update({
[key]: value,
});
};
return [store[key], setValue];
};
export function createRook({ defaultStore, init, storeReducer, reducers, }) {
const context = React.createContext({});
const CreatedRook = ({ children }) => (React.createElement(Rook, { Provider: context.Provider, storeReducer: storeReducer, reducers: reducers, init: init || ((initStore) => (Object.assign({}, initStore))), defaultStore: (defaultStore || {}) }, children));
const useRook = createUseRook(context);
return [CreatedRook, useRook];
}
export const createStoreRook = (defaultStore, { reducers, storeReducer, } = {}) => {
return createRook({
defaultStore,
reducers,
storeReducer,
});
};