Skip to content
This repository has been archived by the owner on Dec 27, 2023. It is now read-only.

react-router-dom V6 support #176

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions example/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import UseQueryParamCode from '!!raw-loader!./UseQueryParam'
import UseRouteParamCode from '!!raw-loader!./UseRouteParam'
import { Box, Card, CardContent, CardMedia, Typography } from '@material-ui/core'
import React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import { BrowserRouter, Route, Routes } from 'react-router-dom'
import SyntaxHighlighter from 'react-syntax-highlighter'
import CreateLinkWithState from './CreateLinkWithState'
import UseArrayQueryKey from './UseArrayQueryKey'
Expand Down Expand Up @@ -64,9 +64,11 @@ const App = () => {

return (
<BrowserRouter basename='/use-route-as-state/'>
<Switch>
<Route path='/' component={Examples} />
</Switch>
<Routes>
<Route path='/'>
<Examples />
</Route>
</Routes>
</BrowserRouter>
)
}
Expand Down
6 changes: 3 additions & 3 deletions example/src/UseQueryParam.jsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { Box, TextField, Typography } from '@material-ui/core'
import { Box, TextField } from '@material-ui/core'
import React from 'react'
import { useQueryString } from 'use-route-as-state'
import SearchList from './SearchList'

const UseQueryParam = () => {
const [params, updateParams] = useQueryString()
const [params, updateParams] = useQueryString({ qParam: '' })

const onChange = (e) => updateParams({ [e.target.id]: e.target.value })

return <Box display='flex' flexDirection='column'>
<TextField id='qParam' label={`Insert value for 'qParam'`}
value={params.qParam} onChange={onChange} />
<Typography variant='body2'><SearchList search={params.qParam} /></Typography>
<SearchList search={params.qParam} />
</Box>
}

Expand Down
12 changes: 7 additions & 5 deletions example/src/UseRouteParam.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Box, TextField, Typography } from '@material-ui/core'
import React from 'react'
import { Route, Switch, useRouteMatch } from 'react-router-dom'
import { Route, Routes, useRouteMatch } from 'react-router-dom'
import { useRouteParams } from 'use-route-as-state'

const UseRouteParam = () => {
const [params, updateParams] = useRouteParams()
const [params, updateParams] = useRouteParams({ rParam: '' })

const onChange = (e) => updateParams(e.target.value && { [e.target.id]: e.target.value })

Expand All @@ -18,7 +18,9 @@ const UseRouteParam = () => {
export default () => {
const { path } = useRouteMatch()

return <Switch>
<Route path={`${path}:rParam?`} component={UseRouteParam} />
</Switch>
return <Routes>
<Route path={`${path}:rParam?`}>
<UseRouteParam />
</Route>
</Routes>
}
26 changes: 25 additions & 1 deletion example/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1172,6 +1172,13 @@
dependencies:
regenerator-runtime "^0.13.4"

"@babel/runtime@^7.7.6":
version "7.17.9"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.17.9.tgz#d19fbf802d01a8cb6cf053a64e472d42c434ba72"
integrity sha512-lSiBBvodq29uShpWGNbgFdKYNiFDo5/HIYsaCEY9ff4sb10x9jizo2+pRrSyF4jKZCXqgzuqBOQKbUm90gQwJg==
dependencies:
regenerator-runtime "^0.13.4"

"@babel/template@^7.10.4", "@babel/template@^7.16.0", "@babel/template@^7.3.3":
version "7.16.0"
resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.16.0.tgz#d16a35ebf4cd74e202083356fab21dd89363ddd6"
Expand Down Expand Up @@ -5563,6 +5570,13 @@ highlight.js@^10.1.1, highlight.js@~10.7.0:
resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-10.7.3.tgz#697272e3991356e40c3cac566a74eef681756531"
integrity sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==

history@^5.2.0:
version "5.3.0"
resolved "https://registry.yarnpkg.com/history/-/history-5.3.0.tgz#1548abaa245ba47992f063a0783db91ef201c73b"
integrity sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==
dependencies:
"@babel/runtime" "^7.7.6"

hmac-drbg@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1"
Expand Down Expand Up @@ -9318,6 +9332,14 @@ react-refresh@^0.8.3:

"react-router-dom@link:../node_modules/react-router-dom":
version "0.0.0"
uid ""

[email protected]:
version "6.3.0"
resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.3.0.tgz#3970cc64b4cb4eae0c1ea5203a80334fdd175557"
integrity sha512-7Wh1DzVQ+tlFjkeo+ujvjSqSJmkt1+8JO+T5xklPlgrh70y7ogx75ODRW0ThWhY7S+6yEDks8TYrtQe/aoboBQ==
dependencies:
history "^5.2.0"

react-scripts@^4.0.1:
version "4.0.3"
Expand Down Expand Up @@ -9408,6 +9430,7 @@ react-transition-group@^4.4.0:

"react@link:../node_modules/react":
version "0.0.0"
uid ""

read-pkg-up@^7.0.1:
version "7.0.1"
Expand Down Expand Up @@ -11069,7 +11092,8 @@ url@^0.11.0:
querystring "0.2.0"

"use-route-as-state@link:..":
version "0.0.0-development"
version "0.0.0"
uid ""

use@^3.1.0:
version "3.1.1"
Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,16 @@
"@testing-library/react-hooks": "^7.0.0",
"@types/jest": "^26.0.13",
"@types/react": "^17.0.0",
"@types/react-router-dom": "^5.1.5",
"@types/react-router-dom": "^5.2.0",
"@typescript-eslint/eslint-plugin": "^4.1.1",
"@typescript-eslint/parser": "^4.1.1",
"conventional-changelog-eslint": "^3.0.9",
"cross-env": "^7.0.2",
"eslint": "^7.9.0",
"eslint-friendly-formatter": "^4.0.1",
"eslint-plugin-react-hooks": "^4.1.2",
"history": "^4.0.0",
"react": "^17.0.1",
"react-router-dom": "^5.2.0",
"react-router-dom": "^6.3.0",
"react-scripts": "^4.0.1",
"react-test-renderer": "^17.0.1",
"rollup": "^2.26.9",
Expand Down
32 changes: 0 additions & 32 deletions src/deprecated/encodeDecode.ts

This file was deleted.

21 changes: 0 additions & 21 deletions src/deprecated/helpers.ts

This file was deleted.

50 changes: 0 additions & 50 deletions src/deprecated/index.ts

This file was deleted.

1 change: 0 additions & 1 deletion src/deprecated/types.ts

This file was deleted.

15 changes: 8 additions & 7 deletions src/encodeDecode.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useMemo } from "react"
import { useLocation, useRouteMatch } from "react-router-dom"
import { useLocation, useMatch } from "react-router-dom"
import { getQueryParamsAsObject, removeUndefined } from "./helpers"

export const useDecodedLocation = () => {
Expand All @@ -11,24 +11,25 @@ export const useDecodedLocation = () => {
}

export const useDecodedRouteMatch = () => {
const { params, ...rest } = useRouteMatch()
const match = useMatch('*')
const { params, path } = useMemo(() => ({ params: match?.params || {}, path: match?.pathname }), [match])

const decodedParams = useMemo(() => decodeValues(params as Record<string, string>), [params])
const decodedParams = useMemo(() => decodeValues(params), [params])

return { params: decodedParams, ...rest }
return { params: decodedParams, path }
}

export const decodeValues = (obj: Record<string, string>) => {
export const decodeValues = (obj: Record<string, string | undefined>) => {
const data = Object.keys(obj).reduce((acc, key) => {
acc[key] = obj[key] && decodeURIComponent(obj[key] as string)
return acc

}, {} as Record<string, string>)
}, {} as Record<string, string | undefined>)

return data
}

export const encodeValues = <T extends Record<string, string | string[]>>(obj: T) => {
export const encodeValues = <T extends Record<string, string | string[] | undefined>>(obj: T) => {
const data = Object.entries(removeUndefined(obj))
.reduce((acc, [key, value]) => {

Expand Down
23 changes: 11 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import { Dispatch, SetStateAction, useCallback, useMemo } from 'react'
import { generatePath, useHistory } from 'react-router-dom'
import { generatePath, useNavigate } from 'react-router-dom'
import { encodeValues, useDecodedLocation, useDecodedRouteMatch } from './encodeDecode'
import { objectToQueryParams, removeUndefined } from './helpers'
export * from './deprecated'

type DispatchState<TState> = Dispatch<SetStateAction<TState>>
type RouteObject = Record<string, string | string[]>
type ParamsRouteObject = Record<string, string>
type ParamsRouteObject = Record<string, string | undefined>

export const useQueryString = (defaultValues?: RouteObject): [RouteObject, DispatchState<RouteObject>] => {
const { pathname, search } = useDecodedLocation()
const history = useHistory()
const navigate = useNavigate()

const updateQuery: DispatchState<RouteObject> = useCallback((dispatch: SetStateAction<RouteObject>) => {
const updatedParams = typeof dispatch === 'function' ? dispatch(search) : dispatch
history.replace(pathname + objectToQueryParams(encodeValues(updatedParams)))
}, [search, pathname, history])
navigate(pathname + objectToQueryParams(encodeValues(updatedParams)), { replace: true })
}, [search, pathname, navigate])

const queryWithDefault = useMemo(() => Object.assign({}, defaultValues, removeUndefined(search)), [search, defaultValues])

Expand All @@ -34,12 +33,12 @@ export const useQueryStringKey = (key: string, defaultValue?: string | string[])

export const useRouteParams = (defaultValues?: ParamsRouteObject): [ParamsRouteObject, DispatchState<ParamsRouteObject>] => {
const { path, params } = useDecodedRouteMatch()
const history = useHistory()
const navigate = useNavigate()

const updateParams = useCallback((dispatch: SetStateAction<ParamsRouteObject>) => {
const updatedParams = typeof dispatch === 'function' ? dispatch(params) : dispatch
history.push(generatePath(path, encodeValues(updatedParams)))
}, [path, params, history])
navigate(generatePath(path, encodeValues(updatedParams)))
}, [path, params, navigate])

const paramsWithDefault = useMemo(() => Object.assign({}, defaultValues, removeUndefined(params)), [params, defaultValues])

Expand All @@ -51,16 +50,16 @@ export type UrlState = {
query: RouteObject
}
export const useUrlState = (defaultValues?: UrlState): [UrlState, DispatchState<UrlState>] => {
const history = useHistory()
const navigate = useNavigate()
const { path, params } = useDecodedRouteMatch()
const { search } = useDecodedLocation()

const updateUrl = useCallback((dispatch: SetStateAction<UrlState>) => {
const updatedState = typeof dispatch === 'function' ? dispatch({ params, query: search }) : dispatch
const updatedParams = encodeValues(updatedState.params)
const updatedQuery = objectToQueryParams(encodeValues(updatedState.query))
history.push(generatePath(path, updatedParams) + updatedQuery)
}, [history, params, path, search])
navigate(generatePath(path, updatedParams) + updatedQuery)
}, [navigate, params, path, search])

const stateWithdefaults = useMemo(() => {
return {
Expand Down
24 changes: 14 additions & 10 deletions src/test/RouterWrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import { createMemoryHistory } from "history"
import React from "react"
import { Route, Router } from "react-router-dom"
import { createMemoryHistory } from "history";
import React from "react";
// https://reactrouter.com/docs/en/v6/api#unstable_historyrouter
import { Route, Routes, unstable_HistoryRouter as HistoryRouter } from "react-router-dom";

export const getHistoryWrapper = (path?: string) => {
const history = createMemoryHistory()
const history = createMemoryHistory()

const wrapper: React.FC<{ path?: string }> = ({ children }) =>
<Router history={history}>
<Route path={path}>
{children}
</Route>
</Router>
const wrapper: React.FC = ({ children }) =>
<HistoryRouter history={history}>
<Routes>
<Route path={'*'} element={children} />
{/* {children}
</Route> */}
</Routes>
</HistoryRouter>

return {
history,
wrapper
Expand Down
Loading