PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] Why react hooks cleanup function is executed when reopening a closed tab?

 November 15, 2022     error-handling, javascript, react-hooks, reactjs, safari     No comments   

Issue

I have a problem when I close a tab and then I undo that action. It basically executes all the cleanup functions in the component, aborting the new fetches that are needed to load the component (old cleanup functions are aborting new fetches). For Chrome and Firefox, it works fine. For what I have tested, it happens only on Safari.

React.useEffect(() => {
    const abortController = new AbortController();

    fetch(`${URL}${API.mediaDetails}`
    + `?id=${encodeURIComponent(props.match.params.id)}`
    + `&type=${encodeURIComponent(props.match.params.type)}`
    + `&lang=${encodeURIComponent(props.match.params.locale?.slice(0, 2))}`, {
        signal: abortController.signal,
        timeout: DOWNLOAD_HUB_REQ_TIMEOUT
    }).then((res) => res.json()).then((res) => {
        res.type = props.match.params.type;
        return setDetails(res);
    }).catch((err) => {
        setDetails(null);
        setError(err);
    });

    return () => abortController.abort();
}, [props.match.params]);

Solution

The cleanup function (to abort the request) will be run whenever the component is removed from the DOM. When you close the tab, that component (and in fact, all of the components on the page) will be removed, which means all their cleanup functions will be run.

This is normally what you want. If you go to /foo/1, and you start fetching data for foo #1 ... but then you change pages to /foo/2 ... you want to abort the fetch for foo #1! You don't need it anymore, so why have it slow down the request for foo #2?

However, if you for some reason don't want this behavior, you could always set some sort of flag (eg. dontCleanup) before the user leaves, and then check for that flag in your cleanup function.

NOTE: Individual browsers (eg. Safari) may have bugs that violate this behavior. Upgrading to the latest browser version should resolve it.



Answered By - machineghost
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,214,578

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing