'Cannot read properties of undefined (reading 'search'). Don't know how to fetch queries in react-router version 6 , react 18
Where am I wrong?
useEffect(() => {
if (user) {
navigate(
{
pathname: `/dashboard`,
}
);
}
}, []);
const navigate = useNavigate();
const queries = new URLSearchParams(navigate.location.search);
After fetching query I perform queries.get which is again undefined, why?
Solution 1:[1]
Assuming you have an url like this : localhost:3000?param1=value1
,
You are supposed to do something like that to get the value from the url parameter:
const location = useLocation()
const [search, setSearch] = useSearchParams()
setSearch(location.search)
useEffect(() => {
const value1 = search.get("param1")
console.log(value1)
},[search])
However, I would rather recommand to use the hook useParams
, so you can get directly the param like this:
const { param1} = useParams();
//param1 contains the value1
Assuming that the route to this component would be:
<Route path="/:param1" element={<App />} />
Solution 2:[2]
Cannot read properties of undefined (reading 'search'). Don't know how to fetch queries in react-router version 6 , react 18
The issue here is that it seems like you are assuming the react-router-dom@6
navigate
function is the same thing as the react-router-dom@5
history
object.
const queries = new URLSearchParams(navigate.location.search);
navigate.location
is undefined, so an error is thrown when attempting to access a search
property.
You don't need to read the search
string from a location
object though because react-router-dom@6
ships a useSearchParams
hook to return the current URL's queryString URLSearchParams
object and a special navigation function.
The useSearchParams
hook is used to read and modify the query string in the URL for the current location. Like React's own useState hook, useSearchParams
returns an array of two values: the current location's search params and a function that may be used to update them.
Your code converted to get "queries" from `useSearchParams:
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams(); // searchParams -> queries
useEffect(() => {
if (user) {
navigate("/dashboard");
}
}, []);
Get queryString parameters as per usual:
const param = searchParams.get("param");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TheTisiboth |
Solution 2 | Drew Reese |