Using VueJS: Updating component data with a function within a method

I'm attempting to perform a search using Firebase within 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()
        }
      })
    }
  }
}

Upon calling console.log, the data is being successfully filtered and displayed in the console. However, I am facing difficulty updating the 'listings' in the component data with the response received from Firebase. Attempted using this.listing, but it was not effective. How can I overcome this issue?

Answer №1

To ensure proper scope, it's recommended to assign the component instance (this) to a global variable named vm. Then, within the callback function, you can assign the value of snapshot.val() to the listing data property in the following manner:

 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()

      })
    }

Alternatively, you can use an arrow function as the callback like so:

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

          this.listings = snapshot.val()

      })
    }

Answer №3

Integrate the component into the search feature by referencing it.

thisElement = this

Next, within the function (snapshot), assign a value to thisComponent.searchData.keyword.

let searchTerm = "example"
thisElement.searchData.keyword = searchTerm

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

Variability in the values returned by the useState hook

Currently, I am working on developing my initial user signup form, and I have encountered a challenge that seems relatively simple to resolve but goes beyond my current expertise. The issue pertains to the helperText for an MUI select component which is no ...

The jQuery click event appears to be malfunctioning

Attempting to create a basic calculator using jQuery, the code seems straightforward but nothing is happening when executed. It's as if the JavaScript file isn't linked properly. Below is the jQuery code snippet: function addNumber(num){ ...

"Eliminating Redundant JS and CSS Files in Magento to Improve

While analyzing the performance of a website, I noticed that GTmetrix found some CSS & JS files being loaded from different locations but containing the same file. An example: <action method="addItem" module="ves_blockbuilder" ifconfig="ves_blockbuilde ...

Creating an array of arrays in Javascript: A comprehensive guide

Can someone assist me in creating an array of arrays? I have a matrix calculator and I need to create the array of arrays ('smaller'). How can this be achieved? The functions create2Darray and calculateDet are working fine, so there is no issue w ...

error TS2559: The type 'BookInterface[]' does not share any properties with the type 'BookInterface'

Hello, I am currently working on a project using Angular 7 and encountering the error TS2559: Type 'BookInterface[]' has no properties in common with type 'BookInterface'. Despite making changes to the code, the issue persists. Below is ...

Using jQuery to manipulate the radio button input's alternate content in HTML attributes

How can I use Jquery Attr.Radio Button click to write to the div with id #RadioDesc? <input type="radio" desc="sample description" class="AddText"> <script type="text/javascript"> $( document ).ready( function() { $("radio").click ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Creating a Yeoman application with a personalized Node.js server

As I embark on the journey of developing a node.js and angular application using the powerful Yeoman tool, I can't help but wonder about one thing. Upon generating my application, I noticed that there are predefined tasks for grunt, such as a server ...

leveraging svg within react components

I've been attempting to integrate SVG with react, but I haven't been successful. Despite trying various solutions, I'm still unable to figure out why I keep encountering this error: InvalidCharacterError Failed to execute 'createElemen ...

How to exclude the port number from the href in a Node.js EJS template?

I have the following code snippet. I am trying to list out the file names in a specific directory and add an href tag to them. The code seems to be working fine, however, it still includes the port number where my node.js app is running. How can I remove ...

Efficiently loading images into a navigation flyout: the ultimate guide

I have a large navigation flyout menu that includes images to display the items. Although it is functioning properly, I have noticed that the page load time is a bit slow due to the higher number of images being loaded. Here is an example of my code: &l ...

How can I show a different output in Vue.js than what is stored in the model?

Consider the following scenario: https://plnkr.co/edit/1mMThIpE1poiGMh98npf?p=preview There is a straightforward example where the input always shows firstName. If I want the input to display firstName all the time, except when the name is John, and the ...

Is there a powerful alternative to ThreeJS that can be integrated into Android apps?

I am in the process of creating a website that allows users to personalize their jewelry online. To achieve this, I am utilizing ThreeJS. My next step is to develop an Android app, which requires me to create an API-only app for both the website and the An ...

Error: Attempted to access undefined property 'renderMenu' in a promise without handling it

I am looking to generate a dynamic menu based on the JSON data provided below: [ { "teamId": "10000", "teamName": "Laughing Heroes", "superTeamId": "", "createTime": "2017-06-25T06:07:45.000Z", "createUserId": null }, { "team ...

What could be the reason for the undefined value of my variable

I am facing an issue with a function that I have written function collectData() { var data = []; data[0] = {name: "Sophia", age: 25, gender: "female"}; data[1] = {name: "John", age:30, gender ...

Tips on placing a button at the bottom of the AppBar and keeping it fully responsive

I am attempting to place my login and log out buttons at the end of the AppBar. When I try forcing it with marginLeft: '70%',, it works but only on large resolutions. On smaller resolutions, the buttons go out of place. Here is an example of forc ...

Is it possible to add a click handler function to a dynamically generated link in Vue?

When working with Vue components, I receive dynamic messages from the server: module.exports = { data() { return: { windowText: '' } }, methods: { showCancelEntrieWindow(){ this.$http.post('/page', {'number& ...

Struggling to process the JSON response generated by PHP

Currently, I am utilizing the pmxdr library to execute a cross-domain call from jQuery to PHP and receive a JSON response. Despite this, I am struggling to properly handle the response. When I attempt to display it in HTML, it appears as: {"title":"Mr","f ...

Utilize JavaScript to compute and implement a deeper shade of background color

To dynamically apply darker shades of background using JavaScript, I have devised the following code. .event-list .bg{ background:#eee; padding:5px; } .grid .event-list:first-child .bg{ background: #2aac97 } .grid .event-list:nth-child(2) .bg{ backgrou ...

What is the name of this JavaScript function declaration syntax? (var) => {}

While perusing the most recent NodeJS documentation, I stumbled upon a novel approach to defining a function: fs.unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); Source: ht ...