英文:
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("productId");
const fetchData= async() =>{
await axios.get("http://localhost:3500/api/anime",{params:productId}).then((res)=>{
setAllAnime(res.data);
})
}
useEffect(()=>{
if(productId)
{
fetchData()
}
},[productId])
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论