I want to get the URL search params and their values using react-router 6, the approach provided in the documentation is as follows :
import * as React from "react";
import { useSearchParams } from "react-router-dom";
function App() {
let [searchParams, setSearchParams] = useSearchParams();
function handleSubmit(event) {
event.preventDefault();
// The serialize function here would be responsible for
// creating an object of { key: value } pairs from the
// fields in the form that make up the query.
let params = serializeFormQuery(event.target);
setSearchParams(params);
}
return (
<div>
<form onSubmit={handleSubmit}>{/* ... */}</form>
</div>
);
}
and this is the link https://reactrouter.com/en/main/hooks/use-search-params. I'm trying to do the same thing here but I don't understand where serializeFormQuery() is supposed to come from. I tried this code and it didn't work:
import {useSearchParams} from "react-router-dom";
myFunction() {
let [searchParams, setSearchParams] = useSearchParams();
const logSearchParams = () => {
let params = serializeFormQuery(searchParams);
console.log(params);
};
logSearchParams()
}
Is serializeFormQuery just a function example? meaning I should create it or am I missing something? because it's undefined.
Thanks for reading.
forms which forms objects of field values used inside the form as mentioned in the docs as well, if you are not using a form then it is not required tmk ..you might just want to read from returned values of the hook as
import {useSearchParams} from "react-router-dom";
function SampleApp = () => {
let [searchParams, setSearchParams] = useSearchParams();
const logSearchParams = () => {
console.log(searchParams.get("samplekey")); // url is assumed as https://.....com?samplekey="dummy"
};
logSearchParams();
.....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With