URL de referencia: https://fullcalendar.io/docs/events-function
La siguiente es una forma de proporcionar eventos como una función para FullCalendar. ¿Cómo escribiría esto en un componente funcional de reacción? Obtengo los datos usando graphql, que es un poco diferente.
function(info, successCallback, failureCallback) { req.get('myxmlfeed.php') .type('xml') .query({ start: info.start.valueOf(), end: info.end.valueOf() }) .end(function(err, res) { if (err) { failureCallback(err); } else { successCallback( Array.prototype.slice.call( // convert to array res.getElementsByTagName('event') ).map(function(eventEl) { return { title: eventEl.getAttribute('title'), start: eventEl.getAttribute('start') } }) ) } })y aquí está mi función actual, devuelve una matriz simple ... ¿cómo implementaría la devolución de llamada y la devolución de llamada fallan como se menciona en los documentos?
const fetchData = async () => { const { searchEvents: myEvents } = await searchEvents() try { const data = myEvents.content.forEach((x) => { x.start = new Date(x.start) x.end = new Date(x.end) }) setIsPageLoaded(true) calendarRef.current.getApi().addEventSource(data) return clonedata } catch (err) { console.log(err) } return true }Recomendaría escribir una función fetchFeed simple que solo se encargue de obtener los datos. Usando promesas, puede evitar los muchos inconvenientes de los diseños orientados a la devolución de llamada:
function fetchFeed (start, end) { return new Promise((success, failure) => { req .get("myxmlfeed.php") .type("xml") .query({ start, end }) .end((err, res) => { if (err) failure(err) else success(res) }) }) } Ahora podemos llamar a fetchFeed con alguna fecha de startDate y alguna endDate . El resultado positivo se puede procesar en .then(...) y cualquier error se puede abordar en .catch(...) -
fetchFeed(startDate, endDate) .then(res => { // ... }) .catch(err => { console.log(err) }) Promises recibió soporte adicional con la sintaxis async y await que hace que escribir este tipo de programa sea aún más natural.
async function updateFeed (...) { const res = await fetchFeed(startDate, endDate) for (const e of res.getElementsByTagName("event")) { // ... } } updateFeed(...).then(console.log).catch(console.error)