Skip to content

Commit

Permalink
Merge pull request #101 from shipt/include-useStore-hook
Browse files Browse the repository at this point in the history
useStore hook returned on Store ref
  • Loading branch information
rkyle35242 authored May 24, 2022
2 parents 31d62bf + 404ba04 commit 19148fc
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion osmosis/src/setupStore.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable react/prop-types */
import React, { createContext } from 'react';
import React, { createContext, useContext } from 'react';

let _defaultConfig = { proxyEnabled: true, legacyReturnStoreAsArray: false };

Expand All @@ -19,11 +19,18 @@ export const configureSetupStore = config => {
* @property {boolean} proxyEnabled - Determines if the store setup should use proxies internally for the store ref, only if proxies are supported
*/

/**
* @template T
* @callback useStore
* @returns {T}
*/

/**
* @template T
* @typedef Store
* @property {React.Context<T>} Context - The React Context for the store
* @property {Object} Provider - The higher order component provider for the store
* @property {useStore<T>} useStore - Returns result of useContext(Context)
*/

/**
Expand All @@ -50,6 +57,7 @@ const setupStore = (useCustomHook, config = {}) => {
let store = useCustomHook(props);
if (!!store.Context) throw new Error("'Context' property is protected and cannot exist on a store object");
if (!!store.Provider) throw new Error("'Provider' property is protected and cannot exist on a store object");
if (!!store.useStore) throw new Error("'useStore' property is protected and cannot exist on a store object");

if (storeProxy) {
if (storeKey) {
Expand Down Expand Up @@ -78,18 +86,22 @@ const setupStore = (useCustomHook, config = {}) => {
return Wrapper;
};

const useStore = () => useContext(StoreContext);

if (!!Proxy && config.proxyEnabled) {
storeProxy = new Proxy(storeProxyObject, {
get: (target, property) => {
if (property === 'Context') return StoreContext;
if (property === 'Provider') return withStoreContext;
if (property === 'useStore') return target.ref[property] ?? useStore;
return target.ref[property];
},
set: (target, property, value) => (target.ref[property] = value)
});
} else {
storeRef.Context = StoreContext;
storeRef.Provider = withStoreContext;
storeRef.useStore = useStore;
}

return storeProxy || storeRef;
Expand Down

0 comments on commit 19148fc

Please sign in to comment.