Skip to content

Instantly share code, notes, and snippets.

@arthyn
Last active June 16, 2021 13:32
Show Gist options
  • Save arthyn/ec0bf8275da941c970792d0eb53b4197 to your computer and use it in GitHub Desktop.
Save arthyn/ec0bf8275da941c970792d0eb53b4197 to your computer and use it in GitHub Desktop.
Last "external" route tracking
import { useEffect } from 'react';
import { useLastLocation } from 'react-router-last-location';
import create from 'zustand';
type LocationMap = {
[key: string]: string | undefined;
};
type HistoryStore = {
locations: LocationMap;
setLocation: (location: string, lastLocation: string | undefined) => void;
};
const useHistoryStore = create<HistoryStore>((set) => ({
locations: {},
setLocation: (location, lastLocation) => {
set(() => {
const newState: { locations: LocationMap } = { locations: {} };
newState.locations[location] = lastLocation;
return newState;
});
}
}));
export const useHistoryMemorizer = (location: string) => {
const lastLocation = useLastLocation();
const { backUrl, setUrl } = useHistoryStore((state) => ({
backUrl: state.locations[location],
setUrl: state.setLocation
}));
useEffect(() => {
if (!lastLocation?.pathname.includes(location)) {
setUrl(location, lastLocation?.pathname);
}
});
return backUrl;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment