generated from chiffre-io/template-library
-
-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Using a hack around the serializer to apply the same encoding as the hooks would in the URL.
- Loading branch information
Showing
1 changed file
with
25 additions
and
5 deletions.
There are no files selected for viewing
30 changes: 25 additions & 5 deletions
30
packages/docs/src/app/playground/(demos)/_components/query-spy.tsx
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,52 @@ | ||
'use client' | ||
|
||
import { useSearchParams } from 'next/navigation' | ||
import { createSerializer } from 'nuqs/server' | ||
import React from 'react' | ||
import { QuerySpySkeleton } from './query-spy.skeleton' | ||
|
||
const serialize = createSerializer({}) | ||
|
||
export function QuerySpy(props: React.ComponentProps<'pre'>) { | ||
const searchParams = useSearchParams() | ||
useSearchParams() // Just using it to trigger re-render on query change | ||
const searchParams = parseQuery( | ||
serialize(new URLSearchParams(location.search), {}).slice(1) // Remove leading '?' | ||
) | ||
|
||
return ( | ||
<QuerySpySkeleton {...props}> | ||
{searchParams.size > 0 && ( | ||
{searchParams.length > 0 && ( | ||
<span className="text-zinc-500"> | ||
? | ||
{Array.from(searchParams.entries()).map(([key, value], i) => ( | ||
{searchParams.map(([key, value], i) => ( | ||
<React.Fragment key={key + i}> | ||
<span className="text-[#005CC5] dark:text-[#79B8FF]">{key}</span>= | ||
<span className="text-[#D73A49] dark:text-[#F97583]"> | ||
{value} | ||
</span> | ||
{i < searchParams.size - 1 && ( | ||
{i < searchParams.length - 1 && ( | ||
<span className="text-zinc-500">&</span> | ||
)} | ||
</React.Fragment> | ||
))} | ||
</span> | ||
)} | ||
{searchParams.size === 0 && ( | ||
{searchParams.length === 0 && ( | ||
<span className="italic text-zinc-500">{'<empty query>'}</span> | ||
)} | ||
</QuerySpySkeleton> | ||
) | ||
} | ||
|
||
function parseQuery(queryString: string): [string, string][] { | ||
const elements = queryString.split('&') | ||
if (elements.length === 0) return [] | ||
return elements.reduce( | ||
(acc, element) => { | ||
if (element === '') return acc | ||
const [key, value] = element.split('=') | ||
return [...acc, [key, value]] | ||
}, | ||
[] as [string, string][] | ||
) | ||
} |