Search code examples
reactjsreact-hooksweb-frontend

I want to grab the query params from the url bar and make an API requrest depending on the query params


I am trying to copy the search functionality of anilist.co . When I try to grab the query params using useSearchparams() the useEffect runs infinitely, Even adding the qp variable in the dependency array is not fixing it.

Here is the code snippet of what I am doing. enter image description here

// this should make sure useEffect runs only when query params are changed

The qp variable should have stopped the useEffect from working infinitely, but it doesnt seem to work. Also maybe I could have a better approach to emulate the anilist.co search functionality


Solution

  • useEffect is running infinitely because the dependency parameter and state that you are updated (pq) in useEffect are the same(It keeps updating that's why useEffect is running again and again). Try using the code snippet, mentioned below.

    Hope this helps you.

    function useQuery() {
      return new URLSearchParams(useLocation().search);
    }
    
    const query = useQuery();
     const productId = query.get("productId");
      
      
      const fetchData= async() =>{
        await axios.get("http://localhost:3500/api/anime",{params:productId}).then((res)=>{
          setAllAnime(res.data);
        })
        
        }
      useEffect(()=>{
        if(productId)
        {
          fetchData()
        }
        },[productId])