skip to Main Content

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

2

Answers


  1. I am not fully sure if i understand the question.

    If you wish to make the request only when the department has a value and are trying to avoid a call with default value of department (although you haven’t mentioned if you are setting a default value) then you could just add a check inside you useEffect and call request() only when the condition is met.
    this will stop the request when department is not defined.

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

    Let me know if this helps you. If not, please try to explain what i missed.

    Login or Signup to reply.
  2. 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])
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search