Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
How to do cleanup in useEffect React?

Usually I do useEffect cleanups like this:

useEffect(() => {
    if (!openModal) {
      let controller = new AbortController();
      const getEvents = async () => {
        try {
          const response = await fetch(`/api/groups/`, {
            signal: controller.signal,
          });
          const jsonData = await response.json();
          setGroupEvents(jsonData);
          controller = null;
        } catch (err) {
          console.error(err.message);
        }
      };
      getEvents();
      return () => controller?.abort();
    }
  }, [openModal]);

But I don't know how to do in this situation:

I have useEffect in Events.js file that get events from function and function in helpers.js file that create events on given dates except holidays (holiday dates fetch from database).

Events.js

useEffect(() => {
    if (groupEvents.length > 0) {
      const getGroupEvents = async () => {
        const passed = await passEvents(groupEvents); // function in helpers.js (return array of events)
        if (passed) { 
          setEvents(passed.concat(userEvents));
        } else {
          setEvents(userEvents);
        }
      };
      getGroupEvents();
    }
  }, [groupEvents, userEvents]);

helpers.js

const passEvents = async (e) => {
  try {
    const response = await fetch(`/api/misc/holidays`, {
      credentials: 'same-origin',
    });
    const jsonData = await response.json();
    const holidays = jsonData.map((x) => x.date.split('T')[0]); // holiday dates
    return getEvents(e, holidays); // create events
  } catch (err) {
    console.error(err.message);
  }
};
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Remove ?:

return () => controller.abort();

Like to this: https://www.youtube.com/watch?v=aKOQtGLT-Yk&list=PL4cUxeGkcC9gZD-Tvwfod2gaISzfRiP9d&index=25

Is it what you want?

about 4 years ago · Juan Pablo Isaza Report

0

You can either not clean up, which really is also fine in many situations, but if you definitely want to be able to abort the in-flight request, you will need to create the signal from the top-level where you want to be able to abort, and pass it down to every function.

This means adding a signal parameter to passEvents.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!