Using Axios, I'm to render backend data from a utility file in my component.
In my useEffect hook, I have a conditional statement to check a selected date. If the date matches, I return a time slot that is available to book an appointment.
const [availableDates, setAvailableDates] = useState();
const [currentTimeSlot, setCurrentTimeSlot] = useState();
const [timeSlots, setTimeSlots] = useState();
useEffect(() => {
async function getData(data) {
let tempObjStoreData = service.getTempObjStoreData();
let dates = await service.stepDate.getAvailableData();
console.log('dates', dates);
setAvailableDates(dates);
setFlagRender(true);
// this effect will run every time currentDate is changed
if (availableDates) {
console.log('show dates', dates);
// get time slots of currentDate
let slots;
dates.forEach((d) => {
debugger;
if (isEqual(availableDates, new Date(d.date))) {
slots = d.timeSlots;
}
});
setTimeSlots(slots);
}
}
return getData();
}, [availableDates]);
When I test the component, I can select a date. However, the time slots are only briefly shown before disappearing. Looking at availableDates in my console log, I see that it is continuously being called.
Looking at other S/O questions like this one: React Hook useEffect : fetch data using axios with async await .api calling continuous the same api, the solution was empty brackets at the end of the useEffect hook:
example from solution
useEffect(() => {
fetchData();
}, []); //This will run only once
end of my useEffect hook
}, [availableDates]);
However, if I remove this, I get the following error:
React Hook useEffect has a missing dependency: 'availableDates'.
Either include it or remove the dependency array.
How can I stop useEffect from constantly rendering this data?
selected datebut I don't see it in the code...[availableDates]to[]and write another one[availableDates]only others action not use inside thissetAvailableDatesinside thisuseEffect