How to access App Bridge outside of a React component

Tourist
3 0 0

Hi,

 

I'm trying to pull some service dependencies that need app bridge out of their present home in React components and into a Redux action. To do this, I need access to app bridge outside of react component, while still being able to use things like AppProvider/Provider as the base of my React hierarchy.

Unfortunately, the app bridge seems to be wired up automatically inside of the AppProvider (from @shopify/polaris) or Provider (from @shopify/app-bridge-react) components. I can instantiate the app bridge like this:

 

import { createApp } from '@shopify/app-bridge';

const app = createApp({
  apiKey: apiKey,
  shopOrigin: shopOrigin,
});

but there appears to be no way to inject this into a Provider component for the rest of the react app. I need to be able to access the app bridge so I can do oauth calls in a redux action.

0 Likes
Shopify Staff
Shopify Staff
9 1 4

Hi kbrooks,

 

You can try doing this to provide your own app instance:

 

import { createApp } from '@shopify/app-bridge';
import {Context} from '@shopify/app-bridge-react';

const app = createApp({
  apiKey: apiKey,
  shopOrigin: shopOrigin,
});

function MyApp() {
  return (
    <Context.Provider value={app}>
      <MyComponent />
    </Provider>
  );
}

One thing to note is when creating your own app instance you need to ensure that the `window` is accessible. Calling `createApp` while doing server side rendering will not work.

 

Cheers,

 

Trish

1 Like
Highlighted
Tourist
3 0 0

I tried using this approach with AppProvider from polaris 3.21.1 (I wasn't able to use Context.Provider like you suggested because AppProvider is required)

import React from 'react';
import thunk from 'redux-thunk';
import ReactDOM from 'react-dom';
import App from './App';
import { AppProvider } from '@shopify/polaris';
import { Provider } from 'react-redux';
import createApp, { getShopOrigin } from '@shopify/app-bridge';
import { applyMiddleware, createStore } from 'redux';
import { appReducer } from './reducers';

const store = createStore(appReducer, applyMiddleware(thunk));

export const app = createApp({
  apiKey: __API_KEY__,
  shopOrigin: getShopOrigin(),
});

ReactDOM.render(
  <AppProvider value={app}>
    <Provider store={store}>
      <Card title="test card">Test card body<Card/>
    </Provider>
  </AppProvider>,
  document.getElementById('snap-shopify-root')
 

But I encountered the error

Uncaught Error {name: "AppBridgeError", message: "APP::ERROR::INVALID_CONFIG: Provided apiKey `54593…ect. Expecting `59baf1db005fd5b5927de8968e578ca0`", action: {…}, type: "APP::ERROR::INVALID_CONFIG", stack: "AppBridgeError: APP::ERROR::INVALID_CONFIG: Provid…ect. Expecting `59baf1db005fd5b5927de8968e578ca0`"}

I believe this is due to passing in a custom app to the AppProvider. How can I resolve this?

0 Likes
Tourist
3 0 0

Ok that last issue was actually due to me messing up my configuration

0 Likes