Suvin Nimnaka Sukka
Suvin Nimnaka Sukka

Reputation: 492

VueJS - How to update component data from a function inside a method?

I'm trying to do a search using Firebase. I have this in my VueJS Code.

export default {
  data () {
    return {
      listings: [],
      searchData: {
        keyword: ""
      }
    }
  },
  name: 'SearchScreen',
  components: {
    ValidationProvider,
    ValidationObserver
  },
  firebase: {
    listings: listingsRef
  },
  methods: {
    search () {
      console.log(this.searchData.keyword)
      listingsRef.orderByChild('location').equalTo(this.searchData.keyword).on('value', function (snapshot){
        console.log(snapshot.val())
        return{
          listings: snapshot.val()
        }
      })
    }
  }
}

Now when I do the console.log It successfully filters out data and shows the response in the console. But I couldn't update the 'listings' in component data with the response I got from Firebase. Tried this.listing but didn't work. How can I do this?

Upvotes: 2

Views: 1587

Answers (3)

Eitan Yarimi
Eitan Yarimi

Reputation: 21

to the search function add a reference to the component

thisComponent = this

then inside the function (snapshot)

use thisComponent.searchData.keyword = (whatever)

Upvotes: -1

Laerte
Laerte

Reputation: 7073

One way to do that is to bind this to your function:

listingsRef.orderByChild('location').equalTo(this.searchData.keyword).on('value', function (snapshot){
    this.listings = snapshot.val()
}.bind(this))

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You should assign this (component instance) to a global variable vm and then in the callback assign that snapshot.val() to the listing data property as follows :

 search () {
      console.log(this.searchData.keyword)
       let vm =this;
      listingsRef.orderByChild('location').equalTo(this.searchData.keyword).on('value', function (snapshot){
        console.log(snapshot.val())

          vm.listings= snapshot.val()

      })
    }

or use the callback as an an arrow function (snapshot)=>{} :

 search () {
      console.log(this.searchData.keyword)
      listingsRef.orderByChild('location').equalTo(this.searchData.keyword).on('value',  (snapshot)=>{
        console.log(snapshot.val())

          this.listings= snapshot.val()

      })
    }

Upvotes: 3

Related Questions