|
1 |
| -import { usePathname, useRouter, useSearchParams } from 'next/navigation' |
| 1 | +import { useSearchParams } from 'next/navigation' |
| 2 | +import { useCallback } from 'react' |
2 | 3 |
|
3 | 4 | export type LanguageId =
|
4 | 5 | | 'javascript'
|
@@ -26,36 +27,34 @@ const languages = ['javascript', 'python', 'go', 'typescript', 'dart']
|
26 | 27 |
|
27 | 28 | const useLang = () => {
|
28 | 29 | const searchParams = useSearchParams()
|
29 |
| - const router = useRouter() |
30 |
| - const pathname = usePathname() |
31 | 30 |
|
32 | 31 | const queryParamLang = searchParams.get('lang') as LanguageId
|
33 | 32 |
|
34 | 33 | const currentLanguage = languages.includes(queryParamLang)
|
35 | 34 | ? queryParamLang
|
36 | 35 | : languages[0]
|
37 | 36 |
|
38 |
| - const setLanguage = (id: LanguageId) => { |
39 |
| - // Recommended to use the Link component <Link href={`?lang=${id}`} scroll={false} /> |
40 |
| - // Apparently this nonsense is necessary to update the URL. |
41 |
| - // See: https://github.com/vercel/next.js/discussions/47583 |
42 |
| - const currentParams = new URLSearchParams( |
43 |
| - Array.from(searchParams.entries()), |
44 |
| - ) |
| 37 | + const setLanguage = useCallback( |
| 38 | + (id: LanguageId) => { |
| 39 | + // Apparently this nonsense is necessary to update the URL. |
| 40 | + // See: https://github.com/vercel/next.js/discussions/47583 |
| 41 | + const currentParams = new URLSearchParams( |
| 42 | + Array.from(searchParams.entries()), |
| 43 | + ) |
45 | 44 |
|
46 |
| - if (!id) { |
47 |
| - currentParams.delete('lang') |
48 |
| - } else { |
49 |
| - currentParams.set('lang', id) |
50 |
| - } |
| 45 | + if (!id) { |
| 46 | + currentParams.delete('lang') |
| 47 | + } else { |
| 48 | + currentParams.set('lang', id) |
| 49 | + } |
51 | 50 |
|
52 |
| - const search = currentParams.toString() |
53 |
| - const query = search ? `?${search}` : '' |
54 |
| - router.push(`${pathname}${query}`, { |
55 |
| - // Don't return to the top of the page |
56 |
| - scroll: false, |
57 |
| - }) |
58 |
| - } |
| 51 | + const search = currentParams.toString() |
| 52 | + const query = search ? `?${search}` : '' |
| 53 | + |
| 54 | + window.history.pushState(null, '', query) |
| 55 | + }, |
| 56 | + [searchParams], |
| 57 | + ) |
59 | 58 |
|
60 | 59 | return {
|
61 | 60 | languages,
|
|
0 commit comments