react-nano icon indicating copy to clipboard operation
react-nano copied to clipboard

`router`: A way to prevent `replaceState` and `pushState`

Open silverwind opened this issue 1 year ago • 1 comments

To implement navigation warnings like "Are you sure to leave this unsaved page?" it would be nice if there were a way to prevent replaceState and pushState, ideally in a async fashing.

How about adding a shouldAbortNavigation option to the Router that accepts a function that, if present, is awaited and if it returns true, abort the navigation?

silverwind avatar Feb 21 '24 18:02 silverwind

Hi @silverwind, sorry for the delay. Life kept me very busy.

Sounds like a valid request. Would this API work?

<Router onNavigate={onNavigate} ...>

with:

export type OnNavigateData = {
    from: string;
    to: string;
    type: "push" | "replace";
};
export type OnNavigateFn = (data: OnNavigateData) => Promise<boolean>;

export interface RouterHistory {
    push: (path: string) => Promise<boolean>;
    replace: (path: string) => Promise<boolean>;
}

export interface RouterProps {
    ....
    /**
     * An async callback that will be called on a navigation event.
     * If it resolves to false, the navigation event will be aborted
     */
    onNavigate?: OnNavigateFn;
}

Lusito avatar May 26 '24 17:05 Lusito

Sounds good. I would change the return type to accept both sync and async:

export type OnNavigateFn = (data: OnNavigateData) => Promise<boolean> | boolean;

Implementation should be the same, you just await onNavigateFn.

silverwind avatar Jun 01 '24 14:06 silverwind

A new version has been released.

Lusito avatar Jun 01 '24 22:06 Lusito