从URL栏中获取查询参数并根据查询参数发出API请求。

huangapple go评论59阅读模式
英文:

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.

// 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

英文:

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

答案1

得分: 1

useEffect无限运行,因为您在useEffect中更新的依赖参数和状态(pq)相同(它不断更新,这就是为什么useEffect一遍又一遍地运行的原因)。尝试使用下面提到的代码片段。

希望这对您有所帮助。

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]);

【注意】:上述代码是已经翻译好的部分,不包括代码本身。

英文:

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.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function useQuery() {
  return new URLSearchParams(useLocation().search);
}

const query = useQuery();
 const productId = query.get(&quot;productId&quot;);
  
  
  const fetchData= async() =&gt;{
    await axios.get(&quot;http://localhost:3500/api/anime&quot;,{params:productId}).then((res)=&gt;{
      setAllAnime(res.data);
    })
    
    }
  useEffect(()=&gt;{
    if(productId)
    {
      fetchData()
    }
    },[productId])

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 03:26:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定