diff --git a/src/api/hooks.js b/src/api/hooks.js index da236d0..f3f5746 100644 --- a/src/api/hooks.js +++ b/src/api/hooks.js @@ -5,7 +5,9 @@ * See /LICENSE for more information. */ -import { useCallback, useReducer } from "react"; +import { + useCallback, useEffect, useReducer, useState, +} from "react"; import { ForisURLs } from "forisUrls"; import { @@ -90,3 +92,23 @@ const useAPIDelete = createAPIHook("DELETE"); export { useAPIGet, useAPIPost, useAPIPatch, useAPIPut, useAPIDelete, }; + +export function useAPIPolling(endpoint, delay) { + const [state, setState] = useState({ state: API_STATE.INIT }); + const [getState, get] = useAPIGet(endpoint); + + useEffect(() => { + if (getState.state === API_STATE.SUCCESS) { + setState(getState); + } + }, [getState]); + + useEffect(() => { + if (delay !== null) { + const interval = setInterval(get, delay); + return () => clearInterval(interval); + } + }, [delay, get]); + + return [state]; +} diff --git a/src/index.js b/src/index.js index 5f755d9..9a51089 100644 --- a/src/index.js +++ b/src/index.js @@ -7,7 +7,12 @@ // API export { - useAPIGet, useAPIPost, useAPIPatch, useAPIPut, useAPIDelete, + useAPIGet, + useAPIPost, + useAPIPatch, + useAPIPut, + useAPIDelete, + useAPIPolling, } from "api/hooks"; export { API_STATE } from "api/utils";