how to make query string url workable whenever someone visits on it directly using next.js?

Viewed 49

Here I have a search bar on my next.js website. Whenever I type a query(eg. delhi) in the search bar and hit submit button an api call runs and it is pushed to http://localhost:3000/jobs/job-search/related-jobs?title=%20delhi, where results based on this query show. But when I copy this link and paste it directly into the browser, the results are not showing. I don't know why and I don't have any idea to make this functionality work.Please help to solve this problem.Some code is given below.

Filter Search

import React,{useState,useEffect} from 'react';
import router from 'next/router';

const FilterSearch = ({fRoute}) => {
    
const [search,setSearch]=useState(" ");
const changeText=(e)=>{
    setSearch(e.target.value);
}

const submitHandle=async (e)=>{
    e.preventDefault();
    router.push(`/${fRoute}/job-search/related-jobs?title=${search}`);

}


return(
    <>
    <form className='flex' onSubmit={submitHandle}>
        <input type="search"  onChange={changeText} className='p-4 w-[70%] mx-3 ring-1 ring-teal-500 rounded-lg shadow-lg shadow-teal-400' placeholder='Search' />
        <button className='px-2 bg-red-500 rounded-md 'type='submit'>Search Job</button> 
    </form>
    </>

)

}
export default FilterSearch;

Results Page Component

import React,{useState,useEffect} from 'react';
import {useRouter} from 'next/router';
import {API} from '../../config';
import Card from '../jobs/Card'


const SearchedJobs = ({xRoute}) => {
    const [data,setData]=useState([]);
    const router=useRouter();
    const {title}=router.query;

    useEffect(async ()=>{
    
        const fetchData= async ()=> {
            const searchData=await fetch(`${API}/${xRoute}/filter/${title}`).then(res=>res.json());

            setData(searchData);
            
        }
        fetchData();
    
    },[]);

  return (
      <>
   <h1 className='pt-20 my-2 text-lg font-bold  lg:px-60'>Jobs Related to, {title}</h1>
    <div className='flex flex-col p-4 lg:grid lg:grid-cols-2 lg:px-60'>
        {data.map((j,i)=>{
            return(
                <article className="m-1 mb-5 rounded-md shadow-md shadow-green-400 hover:ring-slate-900 hover:ring-1" key={i}>
                <Card job={j} />
                </article>

            )

        })}
    </div>
      </>
 
  )
}

export default SearchedJobs

Card is nothing but a template to show results so don't worry about that

1 Answers

The query params are not available right when the component loads, because the router hook is still loading, but it re-renders the component when it becomes available.

One way to make it work is to edit the useEffect hook

useEffect(async ()=>{
  if (!title) return;

  const fetchData= async ()=> {
    const searchData=await 
      fetch(`${API}/${xRoute}/filter/${title}`).then(res=>res.json());

    setData(searchData);         
  }
  fetchData();
    
}, [title]);

Notice that I added title inside the useEffect dependency array, so that everytime title changes, it will refetch the data

Related