Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API.

Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search certain APIs' data as well.

The main problem arises when the data fails to display even without any filtering. The error message displayed in the console reads

this.items.filter is not a function

Thank you very much!

<input type="text" v-model="search">
<div v-for="content in filteredItems" :key="content.name">
  <span> {{ content }}</span>
</div>

export default {
  name: "hello",
  data: () => ({
    search: '',
    items: []
  }),

mounted() {
  var self = this;
  axios
    .get("https://jsonplaceholder.typicode.com/posts/1")
    .then(function(response) {
      console.log(response);
      self.items = response.data;
    })
    .catch(function(error) {
      console.log(error);
    });
},
computed: {
  filteredItems: function() {
    let searchTerm = (this.search || "").toLowerCase();
    return this.items.filter(function(item) {
      let title = (item.title || "").toLowerCase();
      return title.indexOf(searchTerm) > -1;
    });
  }
}

If I switch the API to this one, for example, the search feature functions correctly.

Answer №1

Accessing

https://jsonplaceholder.typicode.com/posts/1
will retrieve a solitary item.

This item is not found within an array; rather, it is presented as an object without any need for a filter.

On the other hand, querying

https://restcountries.eu/rest/v2/all
results in an array being returned, and this time a filter can be applied as needed.

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

Setting new query parameters while maintaining existing ones without deleting them in Next.js v13

"use client"; import { useCallback, useEffect, useState } from "react"; import Accordion from "../accordion/accordion"; import { useRouter, usePathname, useSearchParams, useParams, } from "next/navigation"; i ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

Problems persist with storing Node.js values in database

I need help inserting values from a socket emit into my database. Here is the code I am using: socket.on("chat message", (data) => { var sql = "INSERT INTO tbl_user_chats (sender,receiver,message,created_at,ad_id,category_id) VALU ...

I'm encountering an issue in my server.js file where I am unable to read the property 'collection' as it is undefined

I have encountered an error in my code: /home/ubuntu/workspace/server.js:43 db.collection('quotes').find().toArray(function(err, results) { ^ TypeError: Cannot read property 'collection' of undefined at Object.<anonymous> ( ...

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

Smart method for organizing browsing history

I'm currently working on enhancing the navigation in an AJAX application. Here is my current approach: Whenever a user clicks on an AJAX link, the corresponding call is made and the hash is updated. Upon loading a new page, I verify if the hash exis ...

What is the best method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

Specify the versions of packages in your package.json file

My package.json file contains many dependencies with "*" as the version, which I have learned is not recommended. I want to update them all to their latest versions. Despite using npm-check-updates tool, it indicates that all packages are up-to-date. Can ...

When integrating the React custom hook setValue into another component, it appears to be returning an undefined

I have created a custom useLocalStorage hook. When I directly use it in my component and try to update the value, I encounter an error stating that setValue is not a function and is actually undefined. Here's the code snippet: // Link to the original ...

E6 arrow functions simplify the process of condensing an array of objects into a single object

Here is an array that I have: a=[{'test':1,'test2':'2'},{'test':3,'test2':'4'}] My goal is to reduce this array into a single object This is the expected output {1:2,3:4} I attempted the foll ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

What is the best method for directing to various pages on a GitHub Pages website?

My GitHub Pages site is live at this link. While the splash page loads perfectly, clicking on the circle to transition to the next page, 'landing.html', leads to a 404 error. I have exhausted all possible solutions to address this issue, includin ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

An issue with escaped double quotes in Swift causing JSONDecoder decode to fail

If you set up a playground and insert this code, you will observe that the decoded object is nil. The JSON object [{"transcript":"A person might say, \"Hello\"."}] passes any linter successfully, but it appears that ...

Having difficulty converting an object into an iterable using an arrow function

Currently immersed in learning JavaScript, I successfully created a class and now find myself faced with the task of making it iterable. The Group class represents a collection of values, akin to a Set, equipped with methods for adding, removing, and che ...

Node.js program experiences issues with incorporating netCDF files

I am attempting to encode a NetCDF file within my Node.js program using the netcdf library, which can be found at https://www.npmjs.com/package/netcdf. After running the program, I encountered the following error: C:\app [master +2 ~1 -0 !]> npm ...

Nextjs server encountered an issue where it was unable to connect to the localhost

npm run dev > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563239352239247b372626393f38223b3338227b3439393d3f38317b2133347b372626166678677866">[email protected]</a> dev > next dev ▲ Next.js 14.2. ...

Difference between ng-controller variable and ng-init variable

When working with the code snippet below in angularJS, <script type="text/javascript"> angular.module('app').controller('add', ['$scope',function($scope) { $scope.name = "Bonita Ln"; }]); </script& ...

Tips for creating a Next.js "Link" component with an optional "href" property

I've created a custom React function using typescript for the Next.js Link component. The "href" property is necessary for the "Link" to be used anywhere, so it couldn't be utilized as a button that functions as a submit button in forms. import N ...