Search code examples
eventswatchalpine.js

AlpineJS can not use magic method $watch


Having the following AlpineJS code and trying to use the magic method $watch, the code will fail with ReferenceError: $watch is not defined

window.experts = {
  apiUrl: 'http://test.local:8991/api/',
  data: [],
  list: [],
  expertsForm: null,
  expertType: 'all',
  queryUrl: '',
  currentPage: 1,
  sortByName: 'asc',
  sortByZip: 'asc',
  q: '',
  fetchStatus: 'loading...',
  retrieveList: () => {
    const membersUrl = `${experts.apiUrl}members?include=user,association,affiliate`;
    $watch('specialistType', (value) => console.log(value) );

    experts.apiCalls(membersUrl)
  },
  setExpertType: (type) => {
    console.log(type)
  },
  apiCalls: (url) => {
    const response = fetch(url).then(res => {
      if (!res.ok) {
        experts.fetchStatus = 'error'
      }

      return res.json()
    }).then(result => {
      experts.list = result.data;
      experts.data = result;
      experts.fetchStatus = 'idle'
    });
  }
}

what goes wrong in this case?


Solution

  • Try accessing it via this. So it should be this.$watch(value, callback).