Skip to content
Snippets Groups Projects

Catch error state in API polling.

Merged Bogdan Bodnar requested to merge api-polling-catch-error into dev
All threads resolved!
+ 10
8
@@ -5,14 +5,10 @@
* See /LICENSE for more information.
*/
import {
useCallback, useEffect, useReducer, useState,
} from "react";
import { useCallback, useEffect, useReducer, useState, } from "react";
import { ForisURLs } from "forisUrls";
import {
API_ACTIONS, API_METHODS, API_STATE, getErrorPayload, HEADERS, TIMEOUT,
} from "./utils";
import { API_ACTIONS, API_METHODS, API_STATE, getErrorPayload, HEADERS, TIMEOUT, } from "./utils";
const DATA_METHODS = ["POST", "PATCH", "PUT"];
@@ -98,8 +94,14 @@ export function useAPIPolling(endpoint, delay = 1000, until) { // delay ms
const [getState, get] = useAPIGet(endpoint);
useEffect(() => {
if ([API_STATE.SUCCESS, API_STATE.ERROR].includes(getState.state)) {
setState(getState);
if (getState.state !== API_STATE.INIT) {
setState((currentState) => {
// Keep API_STATE.SENDING state only for a first request.
if (getState.state === API_STATE.SENDING && currentState.state !== API_STATE.INIT) {
return currentState;
}
return getState;
});
}
}, [getState]);