0

After an input change in my input element, I run an empty string check(if (debouncedSearchInput === "")) to determine whether I fetch one api or the other.

The main problem is the correct promise returned faster than the other one, resulting incorrect data on render.

    //In my react useEffect hook
        useEffect(() => {
           //when input empty case
           if (debouncedSearchInput === "") autoFetch();
           //search
           else searchvalueFetch();
        }, [debouncedSearchInput]);

searchvalueFetch() returned slower than autoFetch() when I emptied the input. I get the delayed searchvalueFetch() data instead of the correct autoFetch() data.

What are the ways to tackle this? How do I queue returns from a promises?

I read Reactjs and redux - How to prevent excessive api calls from a live-search component? but

1) The promise parts are confusing for me

2) I think I don't have to use a class

3) I would like to learn more async/await

Edit: added searchvalueFetch, autoFetch, fetcharticles code

  const autoFetch = () => {
    const url = A_URL
    fetchArticles(url);
  };
  const searchNYT = () => {
    const url = A_DIFFERENT_URL_ACCORDING_TO_INPUT
    fetchArticles(url);
  };
  const fetchArticles = async url => {
    try{
      const response = await fetch(url);
      const data = await response.json();
      //set my state
    }catch(e){...}
  }

2 Answers2

0

This is an idea how it could looks like. You can use promises to reach this. First autoFetch will be called and then searchvalueFetch:

   useEffect(() => {
     const fetchData = async () => {
       await autoFetch();
       await searchvalueFetch();
     };

     fetchData();

   }, []);
demkovych
  • 7,827
  • 3
  • 19
  • 25
0

You can also use a function in any lifecycle depends on your project.

lifecycle(){
     const fetchData = async () => {
try{
       await autoFetch();
       await searchvalueFetch();
} catch(e){
console.log(e)
}
     };

     fetchData();

   }
}
Ankit Kumar Rajpoot
  • 5,188
  • 2
  • 38
  • 32