Project

General

Profile

Actions

Improvement #12659

open

Optimize setLoading function in API Calls

Added by Oshani Silva about 2 months ago. Updated about 2 months ago.

Status:
New
Priority:
Low
Assignee:
-
Start date:
24/02/2025
Due date:
% Done:

0%

Estimated time:
Device Type:
Component:
Type:
UI

Description

Currently we use setLoading(true) to show a loading spinner before initiating an API call to indicate that the data is being fetched and setLoading(false) to hide the loader once the operation completes in both success and failure responses.

In our current frontend development, setLoading(false) is placed separately inside .then() and .catch() promise functions [1]. Instead of manually calling setLoading(false) separately in success or failure, using the finally promise function [2] for setLoading(false) would be an effective approach.

Code comparison

Separate usage of setLoading(false)

setLoading(true);
axios
.get(
'/api/data')
.then((response) => {
setData(response.data);
setLoading(false);
})
.catch((error) => {
handleApiError(
error);
setLoading(false);
});

Usage of setLoading(false) inside the finally block(Optimized approach)

axios
.get(
'/api/data')
.then((response) => {
setData(response.data);
})
.catch((error) => {
handleApiError(
error);
});
.finally(() => {
setLoading(false);
});

[1] - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

[2] - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

Actions #1

Updated by Oshani Silva about 2 months ago

  • Priority changed from None to Low
Actions

Also available in: Atom PDF