useEffect run initially and then only if state changes
Unanswered
Ojos Azules posted this in #help-forum
Ojos AzulesOP
Here i want to get disabledDays to add to my calendar but i dont want to wait if state changes, i want initallly to get disabledDays and then if barberId or date change then re run the fetch. Any thoughts?
My code:
My code:
const [disabledDays, setDisabledDays] = useState<Date[]>([]);
useEffect(() => {
if (barberId && date) {
fetchWorkingHours(barberId)
.then((barber) => {
const unavailableDays = daysOfWeek.filter(
(day) => !barber?.dayOfWeek.includes(day.name)
);
const unavailableDaysNumbers = unavailableDays.map(
(day) => day.number
);
const disabledDays = generateDisabledDaysForAllMonths(
unavailableDaysNumbers
);
setDisabledDays(disabledDays);
getTimes(
barber?.morningStartTime!,
barber?.morningEndTime!,
barber?.afternoonStartTime!,
barber?.afternoonEndTime!,
30,
date,
barberId
)
.then((slots) => {
setTimeSlots(slots);
})
.catch((error) => {
console.error("Error fetching time slots:", error);
// Handle error here
});
})
.catch((error) => {
console.error("Error fetching working hours:", error);
// Handle error here
});
}
}, [barberId, date]); // Only re-run the effect if barberId or date changes4 Replies
American Crow
2nd useEffect with an empty dep. Array?
Ojos AzulesOP
A solution maybe:
const [hasFetchedDataOnce, setHasFetchedDataOnce] = useState(false);
useEffect(() => {
if ((barberId && date) || !hasFetchedDataOnce) {
fetchWorkingHours(barberId)
.then((barber) => {
const unavailableDays = daysOfWeek.filter(
(day) => !barber?.dayOfWeek.includes(day.name)
);
const unavailableDaysNumbers = unavailableDays.map(
(day) => day.number
);
const disabledDays = generateDisabledDaysForAllMonths(
unavailableDaysNumbers
);
setDisabledDays(disabledDays);
getTimes(
barber?.morningStartTime!,
barber?.morningEndTime!,
barber?.afternoonStartTime!,
barber?.afternoonEndTime!,
30,
date!,
barberId
)
.then((slots) => {
setTimeSlots(slots);
setHasFetchedDataOnce(true); // Update state to indicate that data has been fetched at least once
})
.catch((error) => {
console.error("Error fetching time slots:", error);
// Handle error here
});
})
.catch((error) => {
console.error("Error fetching working hours:", error);
// Handle error here
});
}
}, [barberId, date, hasFetchedDataOnce]); // Only re-run the effect if barberId or date changesjust have another useEffect?
with an emtpy deps array