Skip to content

Commit

Permalink
feat(toolkit): add popstate event trigger to location hooks
Browse files Browse the repository at this point in the history
- Add `triggerPopstate` function to `useLocation` and `useSearchParams` hooks
- Update `createLocationStore` to expose `triggerPopstateEvent` function
- This allows triggering a popstate event manually
  • Loading branch information
Ryan-Zayne committed Nov 12, 2024
1 parent c62a034 commit 247e617
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 5 deletions.
9 changes: 9 additions & 0 deletions .changeset/thin-lobsters-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@zayne-labs/toolkit": patch
---

feat(toolkit): add popstate event trigger to location hooks

- Add `triggerPopstate` function to `useLocation` and `useSearchParams` hooks
- Update `createLocationStore` to expose `triggerPopstateEvent` function
- This allows triggering a popstate event manually
1 change: 0 additions & 1 deletion packages/toolkit/src/core/createLocationStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ const createLocationStore = (options: LocationStoreOptions = {}) => {
push,
replace,
subscribe,

triggerPopstateEvent,
};

Expand Down
23 changes: 19 additions & 4 deletions packages/toolkit/src/react/hooks/useLocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,32 @@ import type { SelectorFn } from "@/type-helpers";
import { useConstant } from "./useConstant";
import { useStore } from "./useStore";

type LocationStore = ReturnType<typeof createLocationStore>;

type UseLocationResult<TSlice> = [
state: TSlice,
setState: {
push: LocationStore["push"];
replace: LocationStore["replace"];
triggerPopstate: LocationStore["triggerPopstateEvent"];
},
];

const useLocation = <TSlice = LocationState>(
selector: SelectorFn<LocationState, TSlice> = (store) => store as TSlice
) => {
const locationStore = useConstant(() => createLocationStore());

const stateSlice = useStore(locationStore as never, selector);

return [stateSlice, { push: locationStore.push, replace: locationStore.replace }] as [
state: TSlice,
setState: { push: typeof locationStore.push; replace: typeof locationStore.replace },
];
return [
stateSlice,
{
push: locationStore.push,
replace: locationStore.replace,
triggerPopstate: locationStore.triggerPopstateEvent,
},
] as UseLocationResult<TSlice>;
};

export { useLocation };
2 changes: 2 additions & 0 deletions packages/toolkit/src/react/hooks/useSearchParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ const useSearchParams = <TSearchParams extends URLSearchParamsInit>(
setSearch[action](`?${params.toString()}`);
};

setSearchParams.triggerPopstate = setSearch.triggerPopstate;

return [searchParams, setSearchParams] as const;
};

Expand Down

0 comments on commit 247e617

Please sign in to comment.