'Mutation observer not observing element when placed inside a function

I'm trying to set the liveChatAvailable value to true and isLoading value to false once the cripClient element loads to the page.

When the observer object is within a function the if (crispClient) code never runs.

After some research, it seems that it might have something to do with the code needing to be asynchronous but I don't really know how to go about it so a push in the right direction would be great.

Update: I made the mixin run the code on mounted() instead of doing it inside of the component to see if that would make a difference but it didn't.

LiveChatAvailability.js

  export const LiveChatAvailability = {
    data() {
      return {
        isLoading: true,
        liveChatAvailable: false
      }
    },
  
    methods: {
      setLiveChatAvailability() {      
        
        const crispClient = document.querySelector('.crisp-client');
        const observer = new MutationObserver((mutations, obs) => {
          if (crispClient) {
  
            this.loading = false;
            this.liveChatAvailable = true;

            obs.disconnect();
            return;
          }
  
          observer.observe(document, {
            childList: true,
            subtree: true
          });
        });
      }
    }
  } 

LiveChatButton.vue

<template>
  <button v-if="liveChatAvailable" @click.prevent="liveChatTrigger">Start a live chat now</button>
</template>

<script>
import {LiveChatAvailability} from '../../../../../public_html/assets/src/js/Vue/Mixins/LiveChatAvailability';
export default {
  mixins: [
    LiveChatAvailability
  ],
  created() {
    this.setLiveChatAvailability();
  },
  methods: {
    liveChatTrigger() {
      if (window.$crisp) {
        window.$crisp.push(['do', 'chat:open']);
      }
    }
  },
}
</script>


Solution 1:[1]

Placing the crispClient const within the MutationObserver code allowed it to work.

  export const LiveChatAvailability = {
    data() {
      return {
        isLoading: true,
        liveChatAvailable: false
      }
    },
  
    methods: {
      setLiveChatAvailability() {      
        
        
        const observer = new MutationObserver((mutations, obs) => {
          if (crispClient) {

            const crispClient = document.querySelector('.crisp-client');
  
            this.loading = false;
            this.liveChatAvailable = true;

            obs.disconnect();
            return;
          }
  
        });

          observer.observe(document, {
            childList: true,
            subtree: true
          });
      }
    }
  } 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kaleshe Alleyne-Vassel