Encountering a JavaScript error when trying to manage autocomplete location information in the Google Maps API within VueJS 2

I recently implemented a search input form in my VueJS 2 application, allowing users to search for a location and view a list of nearby pharmacies on the page. However, I encountered an issue with the autocomplete feature not working properly. An error message stating "Can not read property 'find' of undefined" is being displayed. The relevant code snippet is provided below:

<input
   id="District"
   name="District"
   class="form-control"
   data-live-search="true"
   list="places-list"
   v-model="searchString"
   @input="handleAutocomplete($event.target.value)"
   />
<datalist id="places-list">
   <option
      v-for="place in placesList"
      :value="place['description']"
      label=""
      :key="place['place_id']"
      >
      <!-- {{ place.name }} -->
   </option>
</datalist>

<!-- The rest of the component's code goes here... -->

If anyone has encountered this error before and knows how to resolve it, your assistance would be greatly appreciated. Thank you!

Answer №1

The error is likely occurring because the handleAutocomplete method is assigning undefined to this.placeList. This could be due to the API not returning a valid JSON result. For example, when querying for "foo", an invalid JSON response is received:

foo{ "predictions" : [ ... ], "status" : "OK" } 

To resolve this issue, it is suggested to remove the "foo" from the response to make it valid JSON (and parseable by Axios). While fixing the API is the ideal solution, adding some defensive programming can also help:

try {
    const {
        data: {
            predictions
        }
    } = await this.$axios.get(
        `https://purnohealth.com/autocomplete.php?input=${query}`
    );
    if (!Array.isArray(predictions) {
        throw "Predictions is not an array.";
    }
    this.placesList = predictions;
    this.handleSearch(query);
} catch (error) {
    console.log(error);
}

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

What is the best way to divide an array while extracting data from a JSON object using

Currently, I am parsing the json data. My goal is to find a specific property within the json object that contains two nested arrays (list and array). However, when extracting the values, they are all being stored in a single array. Is there a way to separ ...

What occurs when a file being imported is also importing a file that the first file is already importing?

I have three JavaScript files with dependencies: - main.js <- dependencies: module.js, helper.js - module.js <- dependencies: helper.js - helper.js <- no dependencies main.js and module.js both import from helper.js, while main.js imports from ...

Learn the process of using Angular Js to compare checkbox values with stored comma-separated values in a database

When displaying amenity checkbox options using ng-repeat of a JSON array and saving them into the database as comma-separated IDs like "1,3,7" within a single string, the challenge arises when needing to edit the amenities. This is due to retrieving the ex ...

The `sameAs` validator in vuelidate does not function properly when using the `not` validator with a computed value

I am facing an issue with getting the not validator to work in conjunction with a computed sameAs value. While I am using the term "computed" here, I am not completely certain if it is the most accurate term. Hopefully, alongside the reproducible code pr ...

Are you experiencing a clash among various JS files in your WordPress installation?

I'm in a bit of a bind here. I've been tasked with working on a Wordpress website for a friend, using a free theme that he provided. Naturally, he wants some modifications made, so I've been editing the theme accordingly. The theme relies on ...

Step-by-step guide for launching a Next.js/Node application

Currently, I am developing a full-stack project utilizing a next.js application for the front-end and a node/express server for the API. The front-end and back-end are running on separate ports. Here is how my application is configured: https://i.stack.im ...

Modifying an array without altering the reference

Perhaps my approach is not quite right, so please provide feedback if necessary! Imagine having an Array that represents some valuable data. var initial = ['x', 'y']; var duplicate = initial; initial.push('z'); console.log(i ...

I'm trying to figure out how to make HTML tags display within a React/Next <head> element

I inherited a React/Next project filled with spaghetti code. The previous developer did not prioritize SEO, and I am still learning React. Now, my main focus is getting tags to render in the Component. <Head> <meta key="data-tes ...

Page is restricted to uploading only a single image at a time

I'm currently working on setting up a simple server that can handle both POST and GET requests. The goal is to allow users to upload images to a directory while saving relevant data like date, name, description, and id to a JSON file. In the case of a ...

Executing Bower installation within a corporate proxy network

Encountering Error : ECONNREFUSED Request to https://bower.herokuapp.com/packages/bootstrap-datepicker failed: connect ECONNREFUSED while attempting Bower Install from Package Manager Console. I came across suggestions in a different discussion on how to ...

The console log message persists even though the condition statement is present - Vue2

The main goal of my code is to trigger the fetchNumbers() function (which retrieves numbers from an API) when a user scrolls to the bottom of the page, creating an infinite scroll effect. However, I'm encountering an issue with the condition inside th ...

The hidden textbox loses its value when submitting

I have a form with fields and a RequiredFieldValidator. Additionally, I have another textbox that is hidden which gets populated by a JavaScript function: <script type="text/javascript"> $(document).ready(function (sender, args) { $("#myTextFiel ...

Having trouble with Mongoose's findOne method not functioning as expected

I am developing an application where users can input data such as the number of hours they slept and their eating habits. This information is then stored in a collection known as the Journal. When a user clicks on "stats", it activates a function called f ...

Make the most of your Bootstrap 3 layout by utilizing a full page container that fills both the width and height between a fixed header and

I am currently working on a basic bootstrap page with the Example template from Bootstrap's website. I want the content in the middle to take up the space between the header and footer, while ensuring that both the header and footer remain visible at ...

I need to extract information from the database and save all entries from the form in order to send them to myself. This includes calculating the real-time multiplication of weight and pieces

For a project, I need to gather contact data from the client, and then populate a MySQL database with the information to create new rows in a table. There's an additional requirement where I have to calculate the total weight of element pieces multip ...

The return value of fs.mkdirSync is undefined

I'm facing a challenge with creating a directory and utilizing that directory as a variable to extract files from zip/rar files. The section of code that is causing an error is shown below: var fileZip = fileName.replace(/^.*[\\\/]/, ...

The attempt at performing an inline edit in react.js was unsuccessful when trying to open a

After clicking on edit, I expected only 1 row to be affected. However, all rows were impacted. What mistake have I made? .. renderItem(){ return( this.state.items.map((item,i)=> <li key={i}> {this.state.isEdit ? this.renderEd ...

React's memo and/or useCallback functions are not functioning as anticipated

Within my Home Component, there is a state called records, which I utilize to execute a records.map() and display individual RecordItem components within a table. function Home() { const [records, setRecords] = useState<Array<RecordType>>(l ...

In Vue.js, dynamically rearrange the order of items in an Array and reflect that reordering in the Document Object Model

Within a Vue component, I have an Array named "block" that contains 4 values. These values are displayed in the DOM using a v-for directive: <div class="block" @click="shuffleArray()"> <div v-for="(number, index) in block"> <spa ...

Exploring the benefits of leveraging TypeScript with AWS NodeJS for improved stacktrace visibility over traditional JavaScript

I'm contemplating the idea of transitioning my existing JavaScript codebase to incorporate TypeScript in NodeJS. One aspect that I am concerned about is being able to view the stack trace in AWS CloudWatch (request log) in case an error occurs during ...