Skip to content

Commit

Permalink
Refacto useSearchParams React Router v6
Browse files Browse the repository at this point in the history
  • Loading branch information
mquandalle committed Jun 16, 2022
1 parent 4b124d0 commit 2bbc1ca
Show file tree
Hide file tree
Showing 12 changed files with 46 additions and 124 deletions.
1 change: 1 addition & 0 deletions site/source/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { Helmet } from 'react-helmet-async'
import { useTranslation } from 'react-i18next'
import { useSelector } from 'react-redux'
import { Redirect, Route, Switch } from 'react-router-dom'
import { CompatRoute } from 'react-router-dom-v5-compat'
import styled, { css } from 'styled-components'
import Accessibilité from './pages/Accessibilité'
import Budget from './pages/Budget/Budget'
Expand Down
6 changes: 3 additions & 3 deletions site/source/actions/companyStatusActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useNextQuestionUrl } from '@/selectors/companyStatusSelectors'
import { LegalStatusRequirements } from '@/types/companyTypes'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router'
import { useNavigate } from 'react-router-dom-v5-compat'
import { Action } from './actions'

export type CompanyStatusAction = ReturnType<
Expand All @@ -17,12 +17,12 @@ export type CompanyStatusAction = ReturnType<
// This feels hacky, we should express this "dispatch and navigate" in another way
export const useDispatchAndGoToNextQuestion = () => {
const dispatch = useDispatch()
const history = useHistory()
const navigate = useNavigate()
const nextQuestion = useNextQuestionUrl()
const [dispatched, setDispatched] = useState(false)
useEffect(() => {
if (dispatched) {
history.push(nextQuestion)
navigate(nextQuestion)
}
}, [dispatched])

Expand Down
2 changes: 1 addition & 1 deletion site/source/components/MoreInfosOnUs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { SmallCard } from '@/design-system/card'
import { H2 } from '@/design-system/typography/heading'
import { useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocation } from 'react-router-dom'
import { useLocation } from 'react-router-dom-v5-compat'
import { icons } from './ui/SocialIcon'
import Emoji from './utils/Emoji'
import { SitePathsContext } from './utils/SitePathsContext'
Expand Down
5 changes: 1 addition & 4 deletions site/source/components/PageData.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import { useIsEmbedded } from '@/components/utils/embeddedContext'
import Meta from '@/components/utils/Meta'
import { SitePathsContext } from '@/components/utils/SitePathsContext'
import useSearchParamsSimulationSharing from '@/components/utils/useSearchParamsSimulationSharing'
import useSimulationConfig from '@/components/utils/useSimulationConfig'
import { Spacing } from '@/design-system/layout'
import { H1 } from '@/design-system/typography/heading'
import { Intro } from '@/design-system/typography/paragraphs'
import { situationSelector } from '@/selectors/simulationSelectors'
import { ComponentPropsWithoutRef, useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { ComponentPropsWithoutRef } from 'react'
import { useSelector } from 'react-redux'
import { useLocation } from 'react-router-dom'
import { TrackChapter } from '../ATInternetTracking'
import {
CurrentSimulatorDataProvider,
Expand Down
66 changes: 0 additions & 66 deletions site/source/components/utils/useSearchParams.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { useEffect, useMemo, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { RootState, SimulationConfig, Situation } from '@/reducers/rootReducer'
import { useHistory } from 'react-router'
import { useSearchParams } from '@/components/utils/useSearchParams'
import { useLocation, useSearchParams } from 'react-router-dom-v5-compat'
import { useEngine } from '@/components/utils/EngineContext'
import { configSelector } from '@/selectors/simulationSelectors'
import Engine, { ParsedRules, serializeEvaluation } from 'publicodes'
Expand All @@ -18,7 +17,7 @@ export default function useSearchParamsSimulationSharing() {
const [searchParams, setSearchParams] = useSearchParams()
const config = useSelector(configSelector)
const simulationUrl = useSelector((state: RootState) => state.simulation?.url)
const currentUrl = useHistory().location.pathname
const currentUrl = useLocation().pathname
const dispatch = useDispatch()
const engine = useEngine()

Expand Down
8 changes: 4 additions & 4 deletions site/source/pages/Landing/SearchOrCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { Grid } from '@mui/material'
import { useCallback, useContext, useEffect } from 'react'
import { Trans } from 'react-i18next'
import { useDispatch, useSelector } from 'react-redux'
import { generatePath, useHistory } from 'react-router-dom'
import { generatePath, useNavigate } from 'react-router-dom-v5-compat'

export default function SearchOrCreate() {
const sitePaths = useContext(SitePathsContext)
Expand Down Expand Up @@ -81,7 +81,7 @@ export default function SearchOrCreate() {
}

function useHandleCompanySubmit() {
const history = useHistory()
const navigate = useNavigate()
const sitePaths = useContext(SitePathsContext)
const setEntreprise = useSetEntreprise()

Expand All @@ -93,9 +93,9 @@ function useHandleCompanySubmit() {
setEntreprise(établissement)
const entreprise = établissement.siren
const path = generatePath(sitePaths.gérer.entreprise, { entreprise })
history.push(path)
navigate(path)
},
[history, setEntreprise, sitePaths.gérer.entreprise]
[navigate, setEntreprise, sitePaths.gérer.entreprise]
)

return handleCompanySubmit
Expand Down
11 changes: 5 additions & 6 deletions site/source/pages/Nouveautes/Nouveautes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { H1 } from '@/design-system/typography/heading'
import { GenericButtonOrLinkProps, Link } from '@/design-system/typography/link'
import { Body } from '@/design-system/typography/paragraphs'
import { useContext, useEffect, useMemo, useState } from 'react'
import { Redirect, useHistory, useRouteMatch } from 'react-router-dom'
import { Navigate, useMatch, useNavigate } from 'react-router-dom-v5-compat'
import styled from 'styled-components'
import { TrackPage } from '../../ATInternetTracking'

Expand All @@ -37,10 +37,9 @@ export default function Nouveautés() {
console.error(err)
)
}, [])
const history = useHistory()
const navigate = useNavigate()
const sitePaths = useContext(SitePathsContext)
const slug = useRouteMatch<{ slug: string }>(`${sitePaths.nouveautés}/:slug`)
?.params?.slug
const slug = useMatch(`${sitePaths.nouveautés}/:slug`)?.params?.slug
useEffect(hideNewsBanner, [])

const releasesWithId = useMemo(
Expand All @@ -58,7 +57,7 @@ export default function Nouveautés() {
`${sitePaths.nouveautés}/${slugify(data[index].name)}`

if (!slug || selectedRelease === -1) {
return <Redirect to={getPath(0)} />
return <Navigate to={getPath(0)} />
}

const releaseName = data[selectedRelease].name.toLowerCase()
Expand Down Expand Up @@ -96,7 +95,7 @@ export default function Nouveautés() {
value={selectedRelease}
items={releasesWithId}
onSelectionChange={(id) => {
history.push(getPath(Number(id)))
navigate(getPath(Number(id)))
}}
>
{(release) => (
Expand Down
10 changes: 5 additions & 5 deletions site/source/pages/Simulateurs/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { SitePathsContext } from '@/components/utils/SitePathsContext'
import { Link } from '@/design-system/typography/link'
import { useContext, useEffect, useMemo } from 'react'
import { Trans } from 'react-i18next'
import { Route, Switch, useLocation } from 'react-router-dom'
import { Route, Routes, useLocation } from 'react-router-dom-v5-compat'
import Home from './Home'
import useSimulatorsData from './metadata'
import SimulateurPage from '../../components/PageData'
Expand Down Expand Up @@ -33,7 +33,7 @@ export default function Simulateurs() {
<Route
key={s.path}
path={s.path}
render={() => <SimulateurPage {...s} />}
element={<SimulateurPage {...s} />}
/>
)),
[simulatorsData, sitePaths]
Expand All @@ -59,10 +59,10 @@ export default function Simulateurs() {
</Link>
)
) : null)}
<Switch>
<Route exact path={sitePaths.simulateurs.index} component={Home} />
<Routes>
<Route path={sitePaths.simulateurs.index} element={<Home />} />
{simulatorRoutes}
</Switch>
</Routes>
</>
)
}
27 changes: 10 additions & 17 deletions site/source/pages/Stats/Stats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { H2, H3 } from '@/design-system/typography/heading'
import { formatValue } from 'publicodes'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Trans } from 'react-i18next'
import { useHistory, useLocation } from 'react-router-dom'
import { toAtString } from '../../ATInternetTracking'
import statsJson from '@/data/stats.json'
import { debounce, groupBy } from '../../utils'
Expand All @@ -22,6 +21,7 @@ import GlobalStats, { BigIndicator } from './GlobalStats'
import SatisfactionChart from './SatisfactionChart'
import { Page, PageChapter2, PageSatisfaction, StatsStruct } from './types'
import { formatDay, formatMonth } from './utils'
import { useSearchParams } from 'react-router-dom-v5-compat'

const stats = statsJson as unknown as StatsStruct

Expand Down Expand Up @@ -117,30 +117,23 @@ interface BrushStartEndIndex {

const StatsDetail = () => {
const defaultPeriod = 'mois'
const history = useHistory()
const location = useLocation()
const [searchParams, setSearchParams] = useSearchParams()
useScrollToHash()
const urlParams = new URLSearchParams(location.search ?? '')

const [period, setPeriod] = useState<Period>(
(urlParams.get('periode') as Period) ?? defaultPeriod
(searchParams.get('periode') as Period) ?? defaultPeriod
)
const [chapter2, setChapter2] = useState<Chapter2 | ''>(
(urlParams.get('module') as Chapter2) ?? ''
(searchParams.get('module') as Chapter2) ?? ''
)

// The logic to persist some state in query parameters in the URL could be
// abstracted in a dedicated React hook.
useEffect(() => {
const queryParams = [
period !== defaultPeriod && `periode=${period}`,
chapter2 && `module=${chapter2}`,
].filter(Boolean)
history.replace({
search: `?${queryParams.join('&')}`,
hash: location.hash,
})
}, [period, chapter2])
const paramsEntries = [
['periode', period !== defaultPeriod ? period : ''],
['module', chapter2],
] as [string, string][]
setSearchParams(paramsEntries.filter(([, val]) => val !== ''))
}, [period, chapter2, setSearchParams])

const visites = useMemo(() => {
const rawData = period === 'jours' ? stats.visitesJours : stats.visitesMois
Expand Down
13 changes: 6 additions & 7 deletions site/source/pages/integration/Iframe.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { Grid } from '@mui/material'
import { lazy, Suspense, useContext, useEffect, useRef, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { Route } from 'react-router'
import { MemoryRouter, useHistory, useLocation } from 'react-router-dom'
import { MemoryRouter } from 'react-router-dom'
import styled from 'styled-components'
import { TrackingContext, TrackPage } from '../../ATInternetTracking'
import { hexToHSL } from '../../hexToHSL'
Expand All @@ -30,6 +30,7 @@ import apecLogo from './images/apec.png'
import cciLogo from './images/cci.png'
import minTraLogo from './images/min-tra.jpg'
import poleEmploiLogo from './images/pole-emploi.png'
import { useSearchParams } from 'react-router-dom-v5-compat'

const LazyColorPicker = lazy(() => import('../Dev/ColorPicker'))

Expand All @@ -47,13 +48,11 @@ const getFromSimu = <S extends SimulatorData, T extends string>(
: undefined

function IntegrationCustomizer() {
const { search } = useLocation()
const simulatorsData = useSimulatorsData()
const sitePaths = useContext(SitePathsContext)
const history = useHistory()
const [searchParams, setSearchParams] = useSearchParams()

const defaultModuleFromUrl =
new URLSearchParams(search ?? '').get('module') ?? ''
const defaultModuleFromUrl = searchParams.get('module') ?? ''

const [currentModule, setCurrentModule] = useState(
getFromSimu(simulatorsData, defaultModuleFromUrl)
Expand All @@ -62,8 +61,8 @@ function IntegrationCustomizer() {
)

useEffect(() => {
history.replace({ search: `?module=${currentModule}` })
}, [currentModule, history])
setSearchParams({ module: currentModule }, { replace: true })
}, [currentModule, setSearchParams])

const [color, setColor] = useState<string | undefined>()

Expand Down
16 changes: 8 additions & 8 deletions site/source/pages/integration/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Banner, InnerBanner } from '@/design-system/banner'
import { Link } from '@/design-system/typography/link'
import { useContext } from 'react'
import { Trans } from 'react-i18next'
import { Route, Switch, useLocation } from 'react-router-dom'
import { Routes, Route, useLocation } from 'react-router-dom-v5-compat'
import { TrackChapter } from '../../ATInternetTracking'
import API from './API'
import Iframe from './Iframe'
Expand Down Expand Up @@ -50,16 +50,16 @@ export default function Integration() {
</InnerBanner>
</Banner>
)}
<Switch>
<Route exact path={sitePaths.développeur.index} component={Options} />
<Route path={sitePaths.développeur.iframe} component={Iframe} />
<Route path={sitePaths.développeur.library} component={Library} />
<Route path={sitePaths.développeur.api} component={API} />
<Routes>
<Route path={sitePaths.développeur.index} element={<Options />} />
<Route path={sitePaths.développeur.iframe} element={<Iframe />} />
<Route path={sitePaths.développeur.library} element={<Library />} />
<Route path={sitePaths.développeur.api} element={<API />} />
<Route
path={sitePaths.développeur.spreadsheet}
component={Spreadsheet}
element={<Spreadsheet />}
/>
</Switch>
</Routes>
</TrackChapter>
)
}

0 comments on commit 2bbc1ca

Please sign in to comment.