-
|
if so, any docs/guides for how to set it up? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
|
In a single island, the React SPA adapter should work fine, the issue we had was to synchronise multiple islands, as there isn't a way to share a common |
Beta Was this translation helpful? Give feedback.
-
|
What if I combine Nuqs with nanostores? |
Beta Was this translation helpful? Give feedback.
-
|
Sorry, not to be the guy, but I just wanna share my own implementation to retrieve and mutate query params on React components with Astro import { F, pipe, S } from "@mobily/ts-belt";
import { useCallback, useEffect, useState } from "react";
import type { z } from "zod";
function onPushState(params: URLSearchParams) {
let pathname = window.location.pathname;
let queryParams = params.toString();
let url = pipe(pathname, (pathname) => {
return pipe(
pathname,
F.ifElse((n) => !!n, S.append(`?${queryParams}`), F.identity),
);
});
window.history.replaceState({}, "", url);
}
export function useQueryParams<
S extends z.ZodSchema,
T = undefined | z.infer<S>,
>(key: string, schema: S, defaultValue?: T) {
let [params, setLocalParams] = useState<z.infer<S> | null>(
defaultValue ?? null,
);
let onChangeParams = useCallback(
(newValue: string | null) => {
let newParams = new URLSearchParams(window.location.search);
if (!newValue) {
newParams.delete(key);
setLocalParams(defaultValue ?? null);
onPushState(newParams);
return;
}
let parsedValue = schema.safeParse(String(newValue));
if (parsedValue.error) {
if (import.meta.env.DEV) {
console.info("Skipped invalid value", newValue);
}
return;
}
setLocalParams(parsedValue.data);
newParams.set(key, newValue);
onPushState(newParams);
},
[key, schema, defaultValue],
);
useEffect(() => {
let updateParams = () => {
let params = new URLSearchParams(window.location.search);
let value = params.get(key);
if (!value) {
if (defaultValue) return setLocalParams(defaultValue);
return setLocalParams(null);
}
let parsedValue = schema.safeParse(value);
if (parsedValue.error) {
if (import.meta.env.DEV) console.info("Skipped invalid value", value);
return;
}
setLocalParams(parsedValue.data);
};
updateParams();
let onPopState = () => updateParams();
window.addEventListener("popstate", onPopState);
return () => window.removeEventListener("popstate", onPopState);
}, [defaultValue, key, schema]);
return [params, onChangeParams] as T extends undefined
? [null | z.infer<S>, typeof onChangeParams]
: [z.infer<S>, typeof onChangeParams];
} |
Beta Was this translation helpful? Give feedback.
In a single island, the React SPA adapter should work fine, the issue we had was to synchronise multiple islands, as there isn't a way to share a common
<NuqsAdapter>context provider across all islands (each island would have to have its own adapter, which isn't great).