-
-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Michał Miszczyszyn
committed
Jan 7, 2021
1 parent
e63fb62
commit 05992f8
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
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 |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { useRouter } from 'next/router'; | ||
import { useCallback, useMemo } from 'react'; | ||
import type { InferType, ObjectSchema } from 'yup'; | ||
|
||
const replacementsPattern = /\[([^[\]\s]+)\]/gi; | ||
|
||
export const useSearch = <S extends ObjectSchema<any>>(schema: S) => { | ||
const { pathname, query: routerQuery, push } = useRouter(); | ||
|
||
/** | ||
* Next.js query is different from what we usuallly consider a "query" | ||
* In Next, for the following route /admin/[blogId], the URL /admin/123?isPublic=true | ||
* is considered to have TWO query items: { blogId: 123, isPublic: true } | ||
* What we want instead, is to have params = { blogId: 123 } and query = { isPublic: true } | ||
*/ | ||
const { params, query } = useMemo(() => { | ||
const matches = [...pathname.matchAll(replacementsPattern)]; | ||
const params = Object.fromEntries( | ||
Object.entries(routerQuery).filter(([key]) => | ||
matches.some(([, replacement]) => key === replacement), | ||
), | ||
); | ||
const query = schema.cast( | ||
Object.fromEntries(Object.entries(routerQuery).filter(([key]) => !(key in params))), | ||
) as InferType<S>; | ||
|
||
return { | ||
params, | ||
query, | ||
}; | ||
}, [pathname, routerQuery, schema]); | ||
|
||
console.log({ params, query }); | ||
|
||
const changeQuery = useCallback( | ||
(query: InferType<S>) => { | ||
const filteredQuery = Object.fromEntries( | ||
Object.entries(query).filter(([key]) => !(key in params)), | ||
); | ||
|
||
const result = schema.validateSync(filteredQuery); | ||
|
||
void push({ | ||
query: { | ||
...routerQuery, | ||
...result, | ||
}, | ||
}); | ||
}, | ||
[params, push, routerQuery, schema], | ||
); | ||
|
||
return useMemo(() => ({ changeQuery, params, query }), [params, query, changeQuery]); | ||
}; |