Skip to content

Commit

Permalink
Use history API to notify about routing updates
Browse files Browse the repository at this point in the history
  • Loading branch information
typeofweb committed Feb 13, 2024
1 parent 6527b0e commit 0f41453
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 19 deletions.
1 change: 1 addition & 0 deletions src/app-bridge/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ function createNotificationAction(payload: NotificationPayload): NotificationAct

export type UpdateRoutingPayload = {
newRoute: string;
replace?: boolean;
};

export type UpdateRouting = ActionWithId<"updateRouting", UpdateRoutingPayload>;
Expand Down
56 changes: 37 additions & 19 deletions src/app-bridge/next/route-propagator.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,55 @@
/**
* Use .js extension to avoid broken builds with ESM
*/
import * as NextRouter from "next/router.js";
import { useEffect } from "react";
import { useCallback, useEffect } from "react";

import { actions } from "../actions";
import { useAppBridge } from "../app-bridge-provider";

const { useRouter } = NextRouter;

/**
* Synchronizes app inner state (inside iframe) with dashboard routing, so app's route can be restored after refresh
*/
export const useRoutePropagator = () => {
const { appBridge, appBridgeState } = useAppBridge();
const router = useRouter();

const updateRouting = useCallback((url: string | URL | null | undefined, replace: boolean) => {
if (!url || !appBridge) {
return;
}

appBridge
.dispatch(
actions.UpdateRouting({
newRoute: url.toString(),
replace,
})
)
.catch(() => {
console.error("Error dispatching action");
});
}, []);

useEffect(() => {
if (!appBridgeState?.ready ?? !appBridge) {
return;
}

router.events.on("routeChangeComplete", (url) => {
appBridge
?.dispatch(
actions.UpdateRouting({
newRoute: url,
})
)
.catch(() => {
console.error("Error dispatching action");
});
});
useEffect(() => {
const originalPushState = window.history.pushState.bind(window.history);
window.history.pushState = function pushState(data, unused, url) {
const result = originalPushState.call(this, data, unused, url);
updateRouting(url, false);
return result;
};
const originalReplaceState = window.history.replaceState.bind(window.history);
window.history.replaceState = function replaceState(data, unused, url) {
const result = originalReplaceState.call(this, data, unused, url);
updateRouting(url, true);
return result;
};

return () => {
window.history.pushState = originalPushState;
window.history.replaceState = originalReplaceState;
};
}, [updateRouting]);
}, [appBridgeState, appBridge]);
};

Expand Down

0 comments on commit 0f41453

Please sign in to comment.