Skip to content

Instantly share code, notes, and snippets.

@thurt
Last active April 2, 2020 21:31
Show Gist options
  • Save thurt/645cf505fce2e7f211d55c7442bbe00b to your computer and use it in GitHub Desktop.
Save thurt/645cf505fce2e7f211d55c7442bbe00b to your computer and use it in GitHub Desktop.
Manually get or set more than one query parameter
import React, { useEffect, useState } from "react";
import { useLocation, useHistory } from "react-router";
const ExampleQueryParameters = () => {
const history = useHistory();
const [state, setState] = useState(
Object.fromEntries(new URLSearchParams(useLocation().search))
);
useEffect(() => {
history.replace(
"?" + new URLSearchParams(Object.entries(state)).toString()
);
}, [state, history]);
return (
<>
<h2>Example</h2>
<button onClick={event => setState({ ...state, q: Date.now() })}>
Set "q" param to Date.now()
</button>
<button
onClick={event => setState({ ...state, random: Math.random() })}
>
Set "random" param to a random number
</button>
</>
);
};
export default ExampleQueryParameters;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment