I want to create a URL, something like this:
http://localhost:3000/boarding-school/delhi-ncr
but router.push() keeps on pushing dynamic URL and it’s generating something like this:
http://localhost:3000/boarding-school/boarding-school/boarding-school/delhi-ncr and I don’t want this, if somebody can help me please do it.
I want a URL like this at the end: http://localhost:3000/boarding-school/delhi-ncr?gender=male&somekey=value like this
I tried but did not figure out how to achieve that please help me
my code:
import Layout from "../../../component/Layout/layout";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import Image from "next/image";
import { useEffect, useState } from "react";
const Listing = ({ params }) => {
const router = useRouter();
const pathname = usePathname();
console.log("The Parmas", params);
console.log("the router", router);
// console.log("pathanme", pathname);
// const searchParams = useSearchParams();
// console.log(searchParams);
/******** API data **********/
const [instituteData, setInstituteData] = useState([]);
const [genderData, setGenderData] = useState([]);
const [boardData, setBoardData] = useState([]);
const [schoolData, setSchoolData] = useState([]);
const [budgetData, setBudgetData] = useState([]);
/******************/
/* ************ Filter Data ***********/
const [selectedGender, setSelectedGender] = useState("");
const [selectedBudget, setSelectedBudget] = useState("");
const [selectedBoard, setSelectedBoard] = useState("");
const [selectedSchools, setSelectedSchools] = useState("");
useEffect(() => {
let urlSegment = `/${selectedSchools}${pathname}`;
if (selectedSchools) {
router.push(urlSegment);
}
if (selectedGender) {
// const genderUrl = (urlSegment += `?gender=${selectedGender}`);
// router.push(genderUrl);
}
}, [selectedSchools, selectedGender, router]);
const appendSchoolNameToCurrentRoute = (event) => {
const { name, value, checked } = event.target;
setSelectedSchools(name);
};
2
Answers
Here is my solution after so many tries, By the way I am using Nextjs-13 stable version there is still some issues with query parameters it get cleared out upon selecting school type twice
I was trying to create custom URL, I am leaving this solution for the reference if some body need, any way, thanks whosoever answered my question.
When the selectedSchools or selectedGender state changes, the useEffect hook will be triggered, and it will construct the URL path based on the selected school and add the gender query parameter if selectedGender is not empty. You can add additional query parameters in a similar way.