UNPKG

@resourge/react-fetch

Version:

[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

44 lines (41 loc) 1.08 kB
/** * react-fetch v1.41.3 * * Copyright (c) resourge. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */ import { useRef } from 'react'; import { throttleMethod } from '../utils/throttleMethod'; import { useOnFocus } from './useOnFocus/useOnFocus'; const threshold = 10 * 60 * 1000; const useOnFocusFetch = (fetch, onWindowFocus) => { const fetchRef = useRef(fetch); fetchRef.current = fetch; useOnFocus(() => { let dateNow = Date.now(); const fetchOnWindowFocus = throttleMethod(() => { fetchRef.current().finally(() => { dateNow = Date.now(); }); }, 1000); return { focus: () => { const now = Date.now(); if (now - dateNow <= threshold) { return; } fetchOnWindowFocus(); }, blur: () => { dateNow = Date.now(); }, clear: fetchOnWindowFocus.clear }; }, onWindowFocus); }; export { useOnFocusFetch }; //# sourceMappingURL=useOnFocusFetch.js.map