Improvement #12659
openOptimize setLoading function in API Calls
0%
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