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

52 lines (48 loc) 2.14 kB
'use strict'; var React = require('react'); var redux = require('redux'); var store_index = require('../../store/index.js'); var useHostContext = require('../../hooks/useHostContext.js'); require('@shopify/app-bridge-core/actions/Error'); var withFeature = require('../../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.useHostContext(); var app = context.app, addReducer = context.addReducer, store = context.store; React.useEffect(function () { addReducer({ key: key, reducer: reducer, initialState: initialState }); }, [addReducer, initialState, key, reducer]); var localActions = React.useMemo(function () { return redux.bindActionCreators(actions, app.dispatch); }, [app, actions]); var _a = React.useState(store.getState()[store_index.APP_BRIDGE_KEY][key]), localStore = _a[0], setLocalStore = _a[1]; withFeature.useSetFeatureApi(feature, localActions); React.useEffect(function () { return store.subscribe(function () { var localStore = store.getState()[store_index.APP_BRIDGE_KEY][key]; setLocalStore(function (currentLocalStore) { if (JSON.stringify(localStore) === JSON.stringify(currentLocalStore)) { return currentLocalStore; } return localStore; }); }); }, [store]); return [localStore, localActions]; } exports.useFeature = useFeature;