Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router 6 useSearchParams not working

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.

like image 406
Navid Nami Avatar asked Oct 31 '25 06:10

Navid Nami


1 Answers

  • It would be used with 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();
 
  .....
}
like image 100
Codenewbie Avatar answered Nov 03 '25 12:11

Codenewbie