Search code examples
javascriptreactjsreact-hooksasync-awaitrequest

how to execute requests one by one in a useEffect


I have useEffect that executes the request when changing dependences (department and two dates field).

useEffect(() => {
    getFilteredRestReport({
      date_start: formatDatePatchPoint(date[0]),
      date_end: formatDatePatchPoint(date[1]),
      department,
    });
  }, [date, department])

When I make a request with an empty department, the request takes a long time to complete, and if during this request I make a request, for example, for some department, it will be executed first than without the department, but then when the request without departments is loaded, it will replace the data, although in the filter on the front, I have the last request department selected. And the question is how to stop an unnecessary request, or how to execute requests one by one?

I tried to do it with async/await

const request = async () => {
    await getFilteredRestReport({     
      date_start: formatDatePatchPoint(date[0]),
      date_end: formatDatePatchPoint(date[1]),
      department,
    });
  };

  useEffect(() => {
    request()
  }, [date, department]);

Solution

  • Knowing it is an asyncThunk function, from the following documentation. This should work:

    useEffect(() => {
      const reportPromise = getFilteredRestReport({
        date_start: formatDatePatchPoint(date[0]),
        date_end: formatDatePatchPoint(date[1]),
        department,
       });
      
      return () => {
        reportPromise.abort();
      }
    }, [date, department])