Flatpickr will refresh the list of days once a day is selected, causing any modifications made using onDayCreate to be reverted

After creating a Vue.js component that displays a customized calendar with different background colors for days, I encountered a problem. Whenever I select a day, all my customizations are lost because Flatpickr redraws the DOM elements for the days. How can I ensure that my customizations are retained even after the days grid is updated?

<script>
import { UI_DATE_FORMAT } from "../data/System";
import flatPickr from "vue-flatpickr-component";
import RequestService from "../services/RequestService";

const request = new RequestService();

export default {
  props: [],

  data() {
    return {
      selectedDate: "",
      currentMonth: null,
      busyDaysData: {},
      updateDataProcess: false,

      dateConfig: {
        inline: true,
        dateFormat: UI_DATE_FORMAT,
        monthSelectorType: "static",
        wrap: false,

        onDayCreate: function (dObj, dStr, fp, dayElem) {
          this.calendarDayCreate(dayElem, fp);
        }.bind(this),
      },
    };
  },

  components: {
    flatPickr,
  },

  mounted() {},

  methods: {
    calendarDayCreate(dayElem, fp) {
      const month = fp.currentMonth + 1;
      const dayDay = dayElem.dateObj.getDate();
      const dayMonth = dayElem.dateObj.getMonth() + 1;

      if (dayMonth !== month) return;

      if (this.updateDataProcess) {
        const timer = setTimeout(() => {
          if (!this.updateDataProcess) {
            clearTimeout(timer);
            this.handleDay(dayDay, dayElem);
          }
        }, 250);
      } else {
        if (this.currentMonth !== month) {
          this.updateDataProcess = true;

          new Promise((onSuccess, onError) => {
            request.requestData(
              {
                data: "Calendar\\BusyDaysForMonth",
                arguments: {
                  appointment_id: 0,
                  month,
                  extended: true,
                },
              },
              (response) => {
                onSuccess(response);
              },
              (error) => {
                onError(error);
              }
            );
          }).then(
            (response) => {
              this.updateDataProcess = false;

              this.currentMonth = month;
              this.busyDaysData = response.data;
              this.handleDay(dayDay, dayElem);
            },
            (error) => {
              this.updateDataProcess = false;
              console.log(error);
            }
          );
        }
      }
    },

    handleDay(day, dayElem) {
      if (!this.busyDaysData[day]) return;
      console.log(dayElem);
      dayElem.classList.add(
        "app-" + this.busyDaysData[day].appointment_status ?? ""
      );
    },
  },
};
</script>

<template>
  <b-row id="appointments-calendar">
    <b-col cols="12">
      <flat-pickr
        :config="dateConfig"
        v-model="selectedDate"
        class="form-control flatpickr active"
        :placeholder="$t('appointments_input_date_ph')"
      >
      </flat-pickr>
    </b-col>
  </b-row>
</template>

<style scoped lang="scss"></style>

https://i.sstatic.net/UNahH.png

https://i.sstatic.net/Li55U.png

Despite trying various event hooks from the Flatpickr documentation (Events & Hooks), I have not been able to find a similar solution to the onDayCreate function for setting up days elements.

Answer №1

I have discovered the solution. I realized that I need to include a condition that checks if the month has changed or not.

if (this.currentMonth !== month) {
    this.updateDataProcess = true;

    new Promise((onSuccess, onError) => {
        request.requestData({
            data: 'Calendar\\BusyDaysForMonth',
            arguments: {
                appointment_id: 0,
                month,
                extended: true,
            },
        },
        (response) => { onSuccess(response) },
        (error) => { onError(error) });
    }).then(
        (response) => {
            this.updateDataProcess = false;

            this.currentMonth = month;
            this.busyDaysData = response.data;
            this.handleDay(dayDay, dayElem);
        },
        (error) => {
            this.updateDataProcess = false;
            console.log(error);
        }
    );
} else {
    this.handleDay(dayDay, dayElem);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I establish a scope variable through client-side JavaScript in XPages?

My goal is to update an XPages scope variable using Client-side JavaScript. I have a complex XPage with multiple sections that are toggled on and off using Dojo. Within this XPage, there is a button that triggers some Server-side JavaScript. However, after ...

Utilize the ng.IFilterService interface within a TypeScript project

I am facing an issue with a .ts file that contains the following code: module App.Filters { export class SplitRangeFilter implements ng.IFilterService { static $inject = ['$filter']; public static factory(): Function { ...

Determine the quantity of items currently in an active state

I created a function that toggles the active state of list items when clicked: React toggleActive: function(item){ item.active = !item.active; }, JSX <li key={property.id} onClick={() => this.toggleActive(property)}> Is there a way to count ...

Using Object.create to establish multiple prototypes in JavaScript

I am trying to have my child object inherit the prototypes of multiple parents, but the following methods do not seem to work: child.prototype = Object.create(parent1.prototype, parent2.prototype); and also this: child.prototype = Object.create(parent1 ...

Working with both vue 2 and vue 3 simultaneously on a single machine

Starting my first vue 3 project and running into issues with installing vue-cli. The documentation mentions that for Vue 3, I should be using Vue CLI v4.5 which can be found on npm as @vue/cli. To upgrade, it is necessary to reinstall the latest version of ...

What steps are required to insert additional tags into select2?

I've successfully retrieved the tags from my API, but I'm facing an issue with adding new tags. Here's the code snippet I've been using: $(function(){ var user_email = localStorage.getItem('email'); var api = ...

Navigate a JSON object using JavaScript

As I continue to juggle learning code with my job, I am diving into the world of creating charts using AMcharts. My goal is to generate multiple data sets based on orientation and potentially expand further in the future. In the JSON snippet below, you can ...

Encountering parameter issues while working with Google Maps React in TypeScript

Currently, I'm utilizing TypeScript in this particular file. import React, {Component} from 'react' import {Map, InfoWindow, Marker, GoogleApiWrapper, mapEventHandler, markerEventHandler} from 'google-maps-react'; import { coordina ...

Which NPM packages are necessary for implementing modular Vue components?

While I have experience with traditional multi-page applications created using HTML + JS libraries and server-side rendering (SSR), I am relatively new to modern web development. Currently, I am learning Vue JS (the latest version) through online tutorials ...

Encountered an ERESOLVE error when attempting to install a package, unable to resolve the dependency tree

After attempting to install the necessary dependencies for my project with npm install, an error message came up that I am unable to decipher: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: &l ...

Guide to executing an efficient Graphql request in Vue using Apollo

Seeking assistance with configuring my initial queries on scaphold.io. Here is the query I am running through the internal GraphiQL: query AllPrograms { viewer { allPrograms{ edges { node { id name } ...

fetching indexeddb information using the equivalent of a "WHERE IN (a,b)" query

I've been working on transitioning from websql to indexeddb, but I'm struggling to recreate the SELECT query: "SELECT * FROM tableA WHERE cid ='"+cid+"' AND hid IN("+hid+",1) ORDER BY hid DESC LIMIT 1"; function getMyData(e) { var ...

Effortlessly download multiple mp4 files simultaneously using jQuery through the console

When I open HTML pages in a new window, a media file ".mp4" is among the elements. To save only the media content within each page, I have this code: Is there a way to identify and download all external media files loaded on these pages? var anchor = docu ...

Guide on successfully importing a pretrained model in Angular using TensorFlow.js

I need help with uploading a pretrained Keras model to my existing tensorflow.js model and then making simple predictions by passing tensors in the correct format. The model is stored locally within the project, in the assets folder. export class MotionAn ...

VueSocket - Broadcasting messages to all active application instances

I'm currently working on sending a message to two browsers that are running the same Vue-socket enabled app. During the app creation process, I set up a listener for new messages like this: mounted: function(){ this.$socket.on('newMessage &apos ...

Using a JavaScript callback function as a parameter for the addJavascriptInterface method in Java

Can Java interact with arbitrary functional objects in JavaScript by calling them as callbacks? For example, if we have a function called 'access' that is registered to invoke a Java function: access(function(blabla){ ... }); Are there eff ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...

Stopping the animation of scrollLeft upon user interaction can be achieved by utilizing JavaScript

Here is my current code snippet: <script> $(document).ready(function() { $('.scrolls').stop().animate({ scrollLeft : 4000 },100000, 'linear') }) </script> I am looking for a way to halt the animation once ...

Display Partial View in MVC 4 using ajax success callback

Issue: Unable to load view on ajax success. Situation: I have two cascaded dropdowns where the second dropdown's options are based on the selection of the first dropdown. Upon selecting an option in the second dropdown, I want to display a list of re ...

Utilizing ng-class to manipulate arrays in AngularJS

Within my controller's $scope, there is an array called myElements... $scope.myElements = [false, false, true, false, true, false]; ...and I want to assign the class firstClass to a div element if any of the elements in the array are true, otherwise ...