1
0
mirror of https://gitlab.nic.cz/turris/reforis/foris-js.git synced 2024-11-14 17:35:35 +01:00

Add hook for API polling.

This commit is contained in:
Bogdan Bodnar 2019-11-15 12:54:12 +01:00
parent d935f78d6e
commit 2e68e56e44
No known key found for this signature in database
GPG Key ID: 49E4169AD3CA42B0
2 changed files with 29 additions and 2 deletions

View File

@ -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];
}

View File

@ -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";