Questions and discussions about using the Shopify CLI and Shopify-built libraries.
Hi,
https://shopify.dev/tools/app-bridge/actions/modal
the DATA action to iframe modal from parent app is working.
from a modal, dispatch a Modal.ActionType.DATA action to app, subscribe to Modal.ActionType.DATA is working.
but, to send data from the app to the modal is not working.
I trying as documentry. but not working.
Any way to figure out where the conflict, if that is the issue, is occurring?
Thanks.
import { Provider } from "@shopify/app-bridge-react/components";
import { useAppBridge } from "@shopify/app-bridge-react";
import * as React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
const MyModal = () => {
const app = useAppBridge();
app.subscribe(Modal.ActionType.DATA, (action) => {
console.log("Received message from app:", action);
});
return <div>myModal</div>;
};
const MyApp = () => {
const app = useAppBridge();
const modalOptions = {
title: "My Modal",
path: "/modal",
};
const myModal = Modal.create(app, modalOptions);
myModal.dispatch(Modal.Action.OPEN);
// NOT WORK DISPATCH TO MODAL
app.dispatch(Modal.data({ message: "hello, my modal" }));
return <div>myApp</div>;
};
export const App = () => {
return (
<Provider config={config}>
<Router>
<Switch>
<Route exact path="/">
<MyApp />
</Route>
<Route exact path="/modal">
<MyModal />
</Route>
</Switch>
</Router>
</Provider>
);
};
Hi!
I faced with with issue too. It doesn't work because app bridge dispatches event before your modal loads. Here is how I resolved the issue:
APP:
app.bridge.subscribe(Modal.ActionType.DATA, ({ action, data }) => {
switch (action) {
case 'CANCEL': {
this.modal.dispatch(Modal.Action.CLOSE);
break;
}
case 'SAVE': {
// SAVE LOGIC HERE
this.modal.dispatch(Modal.Action.CLOSE);
break;
}
case 'LOADED': {
// data you would like to pass to the modal
const data = {};
app.bridge.dispatch(Modal.data(data));
break;
}
default: {
break;
}
}
});
And inside of your modal code you need to dispatch an event on load and subscribe to DATA action.
bridge.dispatch(Modal.data({ action: 'LOADED' }));
bridge.subscribe(Modal.ActionType.DATA, (data) => {
// NOTE THAT IT'S SUBSCRIPTION TO ALL ACTIONS AND YOU NEED ADDITIONAL CHECK HERE
console.log('REVERSED DATA TRANSFER', data);
});
Hope it helps.