UNPKG

@shopify/app-bridge-host

Version:

App Bridge Host contains components and middleware to be consumed by the app's host, as well as the host itself. The middleware and `Frame` component are responsible for facilitating communication between the client and host, and used to act on actions se

50 lines (47 loc) 2.08 kB
import { useEffect, useMemo, useState } from 'react'; import { bindActionCreators } from 'redux'; import { APP_BRIDGE_KEY } from '../../store/index.js'; import { useHostContext } from '../../hooks/useHostContext.js'; import '@shopify/app-bridge-core/actions/Error'; import { useSetFeatureApi } from '../../withFeature.js'; /** * Accepts a {@link @shopify/app-bridge-host/store/reducers/embeddedApp/ | Feature} Object * and returns the feature's local store and actions in an array. * * @remarks * Custom hook to add a feature's reducer and then make its actions and store available. * This is the hooks solution to `withFeature`, useful when there's a need to access * multiple features' local store and local action without the need to create multiple * components. * * @public * * @param feature - feature to access * @returns The feature's local store and actions */ function useFeature(feature) { var actions = feature.actions, key = feature.key, reducer = feature.reducer, initialState = feature.initialState; var context = useHostContext(); var app = context.app, addReducer = context.addReducer, store = context.store; useEffect(function () { addReducer({ key: key, reducer: reducer, initialState: initialState }); }, [addReducer, initialState, key, reducer]); var localActions = useMemo(function () { return bindActionCreators(actions, app.dispatch); }, [app, actions]); var _a = useState(store.getState()[APP_BRIDGE_KEY][key]), localStore = _a[0], setLocalStore = _a[1]; useSetFeatureApi(feature, localActions); useEffect(function () { return store.subscribe(function () { var localStore = store.getState()[APP_BRIDGE_KEY][key]; setLocalStore(function (currentLocalStore) { if (JSON.stringify(localStore) === JSON.stringify(currentLocalStore)) { return currentLocalStore; } return localStore; }); }); }, [store]); return [localStore, localActions]; } export { useFeature };