Typed query hook#6034
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
|
|
||
| // push item to existing key | ||
| function pushItemToKey<J extends SchemaKeys>( | ||
| key: J, |
There was a problem hiding this comment.
You can filter this to only get the keys that rep arrays
There was a problem hiding this comment.
I honestly couldnt get this working - I was trying the ArrayKeys type above but was getting an error about not being able to set J to typeof
Maybe @zomars has more TS knowledge to debug this
zomars
left a comment
There was a problem hiding this comment.
Pretty impressive @sean-brydon will need a little bit of more time to review properly
…into util/typed-query
| export const queryNumberArray = z | ||
| .string() | ||
| .or(z.number()) | ||
| .or(z.array(z.number())) | ||
| .transform((a) => { | ||
| if (typeof a === "string") return a.split(",").map((a) => Number(a)); | ||
| if (Array.isArray(a)) return a; | ||
| return [a]; | ||
| }); |
There was a problem hiding this comment.
Support number arrays as a final "type" but input can be string so we can parse it into a number array
query params come in as strings before being parsed
| const search = new URLSearchParams(newValue).toString(); | ||
| router.replace({ query: search }, undefined, { shallow: true }); |
There was a problem hiding this comment.
Had to do this to prevent duplicate values Nextjs actually recommends you construct query params this way
| let parsedQuery: InferedSchema = useMemo(() => { | ||
| return {} as InferedSchema; | ||
| }, []); |
There was a problem hiding this comment.
Preventing infinite renders
| if (parsedQuerySchema.success) parsedQuery = parsedQuerySchema.data; | ||
| else if (!parsedQuerySchema.success) console.error(parsedQuerySchema.error); |
There was a problem hiding this comment.
Safe parse! No crash if the user breaks things
# Conflicts: # apps/website
zomars
left a comment
There was a problem hiding this comment.
Merry Xmas @sean-brydon 🙏🏽
| export const schema = z.object({ | ||
| teamIds: queryNumberArray.optional(), | ||
| userIds: queryNumberArray.optional(), | ||
| status: z.enum(["upcoming", "recurring", "past", "cancelled", "unconfirmed"]), | ||
| eventTypeIds: queryNumberArray.optional(), | ||
| }); |
There was a problem hiding this comment.
Already fixed this in a cleanup commit
A hook that allows you to have type safe router queries. This was a nightmare - was working on something a lot messier than this for booking limits and decided to spend some time cleaning it up and learning a thing or two about conditional generics
Pass in a schema to the hook that you would like to keep type safe

e.g.
results will be fully typesafe





Setting values
remove by key
push item to key
Remove by key and value