• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: useEffect calling api’s couple of times reactjs

Resolved: useEffect calling api’s couple of times reactjs

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have this useEffect function in react component. I am calling api videoGridState here. Now what is happening here it is calling my api 2 times one at intitial page reaload and second one when count is changing. I want it to be called single time when page reloads. But also when streamSearchText changes
How can I do that?

Answer:

The main issue is that you have two useEffect calls, and so they’re each handled, and the second triggers the first (after a delay), resulting in the duplication.
As I understand it, your goal is:
  1. Run videoGridState immediately on mount, and
  2. Run it again after a delay of 1000ms whenever streamSearchText changes

That turns out to be surprisingly awkward to do. I’d probably end up using a ref for it:
Live Example:


You could also do the query immediately when streamSearchText is "", but that would happen every time streamSearchText was "", not just on mount. That may be good enough, depending on how rigorous you need to be.
Additionally, though, if you’re still seeing something happen “on mount” twice, you may be running a development copy of the libraries with React.StrictMode around your app (the default in many scaffolding systems). See this question’s answers for details on how React.StrictMode may mount your component more than once and throw in other seeming surprises.

If you have better answer, please add a comment about this, thank you!

javascript reactjs
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Why when i change manualy the url on my react page it ignores the .css file?

24/03/2023

Resolved: navigate and redirect not redirecting to path in react router

24/03/2023

Resolved: Time Complexity: Find the number of people who know a secret leetcode 2327

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.