From d06ef502d2bdd2e9d57acd4684ef55c606e98989 Mon Sep 17 00:00:00 2001 From: zenby Date: Mon, 12 Oct 2020 15:59:14 +0300 Subject: [PATCH] fix infinite requests --- src/components/header.js | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/components/header.js b/src/components/header.js index 906a8d4..394a308 100644 --- a/src/components/header.js +++ b/src/components/header.js @@ -8,19 +8,28 @@ import { Link } from "gatsby" import { act } from "react-dom/test-utils" const Header = props => { + const shouldRequestStats = () => { + const isFirstRequest = stats.starsCount === 0 + const isVisible = window.document.visibilityState === 'visible' + const hasFocus = window.document.hasFocus() + return isFirstRequest || isVisible && hasFocus + } + const fetchData = async () => { - var response = await axios.get( - "https://api.github.com/repos/rahuldkjain/github-profile-readme-generator" - ) + if (shouldRequestStats()) { + var response = await axios.get( + "https://api.github.com/repos/rahuldkjain/github-profile-readme-generator" + ) - const { stargazers_count, forks_count } = response.data + const { stargazers_count, forks_count } = response.data - act(() => - setstats({ - starsCount: stargazers_count, - forksCount: forks_count, - }) - ) + act(() => + setstats({ + starsCount: stargazers_count, + forksCount: forks_count, + }) + ) + } } const [stats, setstats] = useState({