Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add stores props in LocationStateProvider #13

Merged
merged 4 commits into from
Sep 15, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 19 additions & 10 deletions packages/location-state-core/src/provider.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,38 @@
import { LocationStateContext } from "./context";
import { StorageStore, Store, URLStore } from "./stores";
import { NavigationSyncer } from "./syncers";

import { Syncer } from "./types";
import { ReactNode, useEffect, useState } from "react";

type Stores = Record<string, Store>;
type CreateStores = (syncer: Syncer) => Stores;
koichik marked this conversation as resolved.
Show resolved Hide resolved

const createDefaultStores: CreateStores = (syncer) => ({
koichik marked this conversation as resolved.
Show resolved Hide resolved
session: new StorageStore(globalThis.sessionStorage),
url: new URLStore(syncer),
});

export function LocationStateProvider({
children,
...props
}: {
syncer?: Syncer;
stores?: Stores | CreateStores;
children: ReactNode;
}) {
const [syncer] = useState(
() => props.syncer ?? new NavigationSyncer(window.navigation),
);
const [contextValue] = useState(() => ({
stores: {
session: new StorageStore(globalThis.sessionStorage),
url: new URLStore(syncer),
},
}));
const [stores] = useState(() => {
if (props.stores) {
return typeof props.stores === "function"
? props.stores(syncer)
: props.stores;
}
return createDefaultStores(syncer);
});
koichik marked this conversation as resolved.
Show resolved Hide resolved

useEffect(() => {
const stores = contextValue.stores;
const abortController = new AbortController();
const { signal } = abortController;
const applyAllStore = (callback: (store: Store) => void) => {
Expand Down Expand Up @@ -51,10 +60,10 @@ export function LocationStateProvider({
);

return () => abortController.abort();
}, [syncer, contextValue.stores]);
}, [syncer, stores]);

return (
<LocationStateContext.Provider value={contextValue}>
<LocationStateContext.Provider value={{ stores }}>
koichik marked this conversation as resolved.
Show resolved Hide resolved
{children}
</LocationStateContext.Provider>
);
Expand Down