history#Action TypeScript Examples
The following examples show how to use
history#Action.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocationContext.ts From next-core with GNU General Public License v3.0 | 6 votes |
handleBeforePageLeave(detail: {
location?: Location<PluginHistoryState>;
action?: Action;
}): void {
this.dispatchLifeCycleEvent(
new CustomEvent("page.beforeLeave", {
detail,
}),
this.beforePageLeaveHandlers
);
}
Example #2
Source File: Router.ts From next-core with GNU General Public License v3.0 | 6 votes |
private getBlockMessageBeforePageLave(detail: {
location?: Location<PluginHistoryState>;
action?: Action;
}): string {
const history = getHistory();
const previousMessage = history.getBlockMessage();
this.locationContext?.handleBeforePageLeave(detail);
const message = history.getBlockMessage();
if (!previousMessage && message) {
// Auto unblock only if new block was introduced by `onBeforePageLeave`.
history.unblock();
}
return message;
}
Example #3
Source File: AppContainer.tsx From anthem with Apache License 2.0 | 5 votes |
routeChangeListener = (location: Location, action: Action) => {
// Dispatch relevant actions for routing events.
Analytics.page();
this.props.onRouteChange({ ...location, action });
};
Example #4
Source File: Router.ts From next-core with GNU General Public License v3.0 | 5 votes |
async bootstrap(): Promise<void> {
const history = getHistory();
this.prevLocation = history.location;
this.locationChangeNotify("", history.location.pathname);
history.listen(async (location: PluginLocation, action: Action) => {
let ignoreRendering = false;
const omittedLocationProps: Partial<PluginLocation> = {
hash: null,
state: null,
};
// Omit the "key" when checking whether locations are equal in certain situations.
if (
// When current location is triggered by browser action of hash link.
location.key === undefined ||
// When current location is triggered by browser action of non-push-or-replace,
// such as goBack or goForward,
(action === "POP" &&
// and the previous location was triggered by hash link,
(this.prevLocation.key === undefined ||
// or the previous location specified notify false.
this.prevLocation.state?.notify === false))
) {
omittedLocationProps.key = null;
}
if (
locationsAreEqual(
{ ...this.prevLocation, ...omittedLocationProps },
{ ...location, ...omittedLocationProps }
) ||
(action !== "POP" && location.state?.notify === false)
) {
// Ignore rendering if location not changed except hash, state and optional key.
// Ignore rendering if notify is `false`.
ignoreRendering = true;
}
if (ignoreRendering) {
this.prevLocation = location;
return;
}
this.locationChangeNotify(this.prevLocation.pathname, location.pathname);
this.prevLocation = location;
this.locationContext.handlePageLeave();
this.locationContext.messageDispatcher.reset();
if (this.rendering) {
this.nextLocation = location;
} else {
try {
devtoolsHookEmit("locationChange");
await this.queuedRender(location);
} catch (e) {
handleHttpError(e);
}
}
});
await this.queuedRender(history.location);
this.kernel.firstRendered();
}
Example #5
Source File: index.tsx From react-resource-router with Apache License 2.0 | 4 votes |
actions: AllRouterActions = {
/**
* Bootstraps the store with initial data.
*
*/
bootstrapStore: props => ({ setState, dispatch }) => {
const {
resourceContext,
resourceData,
basePath = '',
routes,
initialRoute,
...initialProps
} = props;
const { history, isStatic } = initialProps;
const routerContext = findRouterContext(
initialRoute ? [initialRoute] : routes,
{ location: history.location, basePath }
);
setState({
...initialProps,
...routerContext,
basePath,
routes,
location: history.location,
action: history.action,
});
getResourceStore().actions.hydrate({ resourceContext, resourceData });
if (!isStatic) {
dispatch(actions.listen());
}
},
/**
* Duplicate method that uses isServerEnvironment instead of removed isStatic prop
* internally. We can remove this when UniversalRouter replaces Router completely.
*/
bootstrapStoreUniversal: props => ({ setState, dispatch }) => {
const {
resourceContext,
resourceData,
basePath = '',
...initialProps
} = props;
const { history, routes } = initialProps;
const routerContext = findRouterContext(routes, {
location: history.location,
basePath,
});
setState({
...initialProps,
...routerContext,
basePath,
location: history.location,
action: history.action,
});
getResourceStore().actions.hydrate({ resourceContext, resourceData });
if (!isServerEnvironment()) {
dispatch(actions.listen());
}
},
/**
* Uses the resource store to request resources for the route.
* Must be dispatched after setting state with the new route context.
*
*/
requestRouteResources: (options = {}) => ({ getState }) => {
const { route, match, query } = getState();
return getResourceStore().actions.requestAllResources(
{
route,
match,
query,
},
options
);
},
prefetchNextRouteResources: (path, nextContext) => ({ getState }) => {
const { routes, basePath, onPrefetch, route, match, query } = getState();
const {
cleanExpiredResources,
requestResources,
getContext: getResourceStoreContext,
} = getResourceStore().actions;
if (!nextContext && !isExternalAbsolutePath(path)) {
const location = parsePath(getRelativePath(path, basePath) as any);
nextContext = findRouterContext(routes, { location, basePath });
}
if (nextContext == null) return;
const nextLocationContext = nextContext;
const nextResources = getResourcesForNextLocation(
{ route, match, query },
nextLocationContext,
getResourceStoreContext()
);
batch(() => {
cleanExpiredResources(nextResources, nextLocationContext);
requestResources(nextResources, nextLocationContext, { prefetch: true });
if (onPrefetch) onPrefetch(nextLocationContext);
});
},
/**
* Starts listening to browser history and sets the unlisten function in state.
* Will request route resources on route change.
*
*/
listen: () => ({ getState, setState }) => {
const { history } = getState();
type LocationUpateV4 = [Location, Action];
type LocationUpateV5 = [{ location: Location; action: Action }];
const stopListening = history.listen(
(...update: LocationUpateV4 | LocationUpateV5) => {
const location = update.length === 2 ? update[0] : update[0].location;
const action = update.length === 2 ? update[1] : update[0].action;
const {
routes,
basePath,
match: currentMatch,
route: currentRoute,
query: currentQuery,
} = getState();
const {
cleanExpiredResources,
requestResources,
getContext: getResourceStoreContext,
} = getResourceStore().actions;
const nextContext = findRouterContext(routes, { location, basePath });
const nextLocationContext = {
route: nextContext.route,
match: nextContext.match,
query: nextContext.query,
};
const nextResources = getResourcesForNextLocation(
{
route: currentRoute,
match: currentMatch,
query: currentQuery,
},
nextLocationContext,
getResourceStoreContext()
);
/* Explicitly batch update
* as we need resources cleaned + route changed + resource fetch started together
* If we do not batch, React might be re-render when route changes but resource
* fetching has not started yet, making the app render with data null */
batch(() => {
cleanExpiredResources(nextResources, nextLocationContext);
setState({
...nextContext,
location,
action,
});
requestResources(nextResources, nextLocationContext, {});
});
}
);
setState({
unlisten: stopListening,
});
},
push: path => ({ getState }) => {
const { history, basePath } = getState();
if (isExternalAbsolutePath(path)) {
window.location.assign(path as string);
} else {
history.push(getRelativePath(path, basePath) as any);
}
},
pushTo: (route, attributes = {}) => ({ getState }) => {
const { history, basePath } = getState();
const location = generateLocationFromPath(route.path, {
...attributes,
basePath,
});
warmupMatchRouteCache(route, location.pathname, attributes.query, basePath);
history.push(location as any);
},
replace: path => ({ getState }) => {
const { history, basePath } = getState();
if (isExternalAbsolutePath(path)) {
window.location.replace(path as string);
} else {
history.replace(getRelativePath(path, basePath) as any);
}
},
replaceTo: (route, attributes = {}) => ({ getState }) => {
const { history, basePath } = getState();
const location = generateLocationFromPath(route.path, {
...attributes,
basePath,
});
warmupMatchRouteCache(route, location.pathname, attributes.query, basePath);
history.replace(location as any);
},
goBack: () => ({ getState }) => {
const { history } = getState();
history.goBack();
},
goForward: () => ({ getState }) => {
const { history } = getState();
history.goForward();
},
registerBlock: blocker => ({ getState }) => {
const { history } = getState();
return history.block(blocker);
},
getContext: () => ({ getState }) => {
const { query, route, match } = getState();
return { query, route, match };
},
getBasePath: () => ({ getState }) => {
const { basePath } = getState();
return basePath;
},
updateQueryParam: (params, updateType = 'push') => ({ getState }) => {
const { query: existingQueryParams, history, location } = getState();
const updatedQueryParams = { ...existingQueryParams, ...params };
// remove undefined keys
Object.keys(updatedQueryParams).forEach(
key =>
updatedQueryParams[key] === undefined && delete updatedQueryParams[key]
);
const existingPath = updateQueryParams(location, existingQueryParams);
const updatedPath = updateQueryParams(
location,
updatedQueryParams as Query
);
if (updatedPath !== existingPath) {
history[updateType](updatedPath);
}
},
updatePathParam: (params, updateType = 'push') => ({ getState }) => {
const {
history,
location,
route: { path },
match: { params: existingPathParams },
basePath,
} = getState();
const pathWithBasePath = basePath + path;
const updatedPathParams = { ...existingPathParams, ...params };
const updatedPath = generatePathUsingPathParams(
pathWithBasePath,
updatedPathParams
);
const updatedLocation = { ...location, pathname: updatedPath };
const existingRelativePath = getRelativeURLFromLocation(location);
const updatedRelativePath = getRelativeURLFromLocation(updatedLocation);
if (updatedRelativePath !== existingRelativePath) {
history[updateType](updatedRelativePath);
}
},
}