Skip to content

Commit

Permalink
doc: Query spy follows encoding
Browse files Browse the repository at this point in the history
Using a hack around the serializer to apply the same
encoding as the hooks would in the URL.
  • Loading branch information
franky47 committed Jun 26, 2024
1 parent 733a835 commit d748e60
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions packages/docs/src/app/playground/(demos)/_components/query-spy.tsx
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][]
)
}

0 comments on commit d748e60

Please sign in to comment.