Last active
February 20, 2021 04:54
-
-
Save an-ivannikov/6bb81ab7a94f2b26b03d2099c7988db6 to your computer and use it in GitHub Desktop.
Synchronizing Request and Filter Parameters in React
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
import * as React from 'react'; | |
import { useLocation, useHistory } from 'react-router-dom'; | |
import queryString from 'query-string'; | |
export default function Component(props) { | |
const history = useHistory(); | |
const location = useLocation(); | |
const initSearch = location.search; | |
const initialFilter = { param: 'all' }; | |
const filter = Object.assign({}, initialFilter, queryString.parse(initSearch)); | |
const filterCopy = JSON.parse(JSON.stringify(filter)); | |
if (filterCopy.param === 'all' || filterCopy.param === '') | |
delete filterCopy.param; | |
const newSearch = '?' + queryString.stringify(copyFilter); | |
if (initSearch !== newSearch) { | |
location.search = newSearch; | |
history.replace(location); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment