Last active
June 16, 2021 13:32
-
-
Save arthyn/ec0bf8275da941c970792d0eb53b4197 to your computer and use it in GitHub Desktop.
Last "external" route tracking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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