fefe
fefe

Reputation: 9055

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?

Upvotes: 1

Views: 5159

Answers (3)

Shashank Bhatt
Shashank Bhatt

Reputation: 857

From alpine js doc,

If you want to access magic methods or properties from a component object, you can do so using the this context:

Alpine.data('dropdown', () => ({
    open: false,
 
    init() {
        this.$watch('open', () => {...})
    }
}))

Upvotes: 1

Xinjie ZHANG
Xinjie ZHANG

Reputation: 23

You should not use arrow function and add this

retrieveList(){
    const membersUrl = `${experts.apiUrl}members?include=user,association,affiliate`;
    this.$watch('specialistType', (value) => console.log(value) );

    experts.apiCalls(membersUrl)
  },

Upvotes: 0

demhadesigns
demhadesigns

Reputation: 196

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

Upvotes: 4

Related Questions