Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

reactjs - How to rerun useEffect when page is visible?

A react app using hooks. In useEffect there is an api-call to populate content on page. Each element fetched is clickable. And a click will open details for the clicked element in a new browser window/tab.

When working in the new window, the user can make changes on that object. The user will then close that tab or at least just go back to the main window/tab.

Question is how I can detect that the user is coming back to the main window. This is because I want to re-fetch data from API. Thus, I want to rerun useEffect. While googling I found this:

https://www.npmjs.com/package/react-page-visibility

Is that really what I'm looking for? Reading the docs I'm not really sure if that can be the solution to my issue. Is there another way to solve this?

question from:https://stackoverflow.com/questions/65647295/how-to-rerun-useeffect-when-page-is-visible

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the visibilitychange event to achieve that:

const onVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    console.log("Tab reopened, refetch the data!");
  }
};

useLayoutEffect(() => {
  document.addEventListener("visibilitychange", onVisibilityChange);

  return () => document.removeEventListener("visibilitychange", onVisibilityChange);
}, []);

Codesandbox


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...