Error message displayed: "An error occurred while processing the VueJS InertiaJS Uncaught (in promise) TypeError. It seems that the property 'search'

Currently, I am working on a Vue JS project with Inertia. One of the features I am implementing is a list that allows users to filter by name.

data() {
        return {
            selectedUser: this.value,
            selected: null,
            search: '',
        }
    },

computed: {
        userlist: function(){
            return this.users.filter(function(user){
                return user.name.toLowerCase().match(this.search.toLowerCase())
            });
        }
    },

In my component, I have the following input field and display logic:

<input class="form-input" placeholder="Search.." v-model="search">
<a href="#" class="block px-4 py-2 text-sm leading-5 text-gray-700 hover:text-gray-900 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-900 flex items-center" v-for="user in userlist" :key="user.id" @click.prevent="select(user)">

However, upon opening the modal where the component is located, an error occurs:

Uncaught (in promise) TypeError: Cannot read property 'search' of undefined

To isolate the issue, I hardcoded a value for the search parameter like so:

computed: {
        userlist: function(){
            return this.users.filter(function(user){
                return user.name.toLowerCase().match('John')
            });
        }
    },

After implementing this temporary fix, the component renders without any errors. I am currently stuck trying to debug this issue, so any guidance or assistance would be greatly appreciated.

Answer №1

The issue likely arises from utilizing the this keyword with the expectation that it refers to your component instance, but in reality, it is being used within a function declaration. This creates a new context, causing this to be undefined.

computed: {
    userlist: function(){
        // In this instance, 'this' refers to the component
        return this.users.filter(function(user){
            // --> function(user) { creates a new context
            // At this point, 'this' becomes undefined leading to an error with this.search
            return user.name.toLowerCase().match(this.search.toLowerCase())
        });
    }
}

To address this issue, you can utilize an arrow function, which will maintain the current context. As a result, the this keyword will continue to reference your component instance.

computed: {
    userlist: function(){
        // Here ‘this’ points to the component instance
        return this.users.filter((user) => { // --> function replaced with arrow function
            // In this case, 'this' still points to the component instance
            return user.name.toLowerCase().match(this.search.toLowerCase())
        });
    }
}

Answer №2

Here's one way you could approach it:

computed: {
    filteredUsers: function(){
        const component = this;
        return this.allUsers.filter(function(user){
            return user.firstName.toLowerCase().includes(component.searchTerm.toLowerCase())
        });
    }
},

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

Is there a way to modify the parent component's state and pass it down to the child component as a prop efficiently?

I am facing an issue with a parent component that sets the score counter and passes it to the child component. There is a function in the parent component called resetBoard() which should reset the score counter back to 0 when triggered by a button click ...

A guide to dynamically rendering pages in Next.js

Currently, I am working on rendering a webpage on the frontend by fetching data from the database. The route for a specific webpage is hard coded at the moment, but I am looking to make it dynamic as there are multiple webpages in the database. I also want ...

The documentation for Gridsome/Netlify CMS has a flaw that results in Graphql not functioning

My attempts to integrate Gridsome with NetlifyCMS using Gridsome's documentation have been unsuccessful. Below is a snippet of the Netlify config.yml setup: collections: - name: "posts" label: "Posts" folder: "posts" create: true s ...

Bug in Async.js causes unexpected results in loop involving numbers

When attempting to reference a variable in a for loop using the Async Library for Node.js, it seems to not work as expected. Here is an example: var functionArray = [] , x; for(x = 0; x < 5; x++) { functionArray.push(function (callback) { conso ...

Ending a connection to MS SQL server in node.js with mssql library

In my journey to write a node.js script for querying an MSSQL database, I find myself navigating the realm of JavaScript, node.js, and VSCode with limited SQL knowledge. While I have managed to piece together working code, the issue lies in the connection ...

specialized html elements within data-ng-options

I have a code snippet where I am populating select options from a controller using data-ng-options. However, I would also like to include an icon with each option. For example, I want to append <span class="fa fa-plus"></span> at the end of e ...

Asynchronous execution of Vue lifecycle methods

In my Vue.js application, I am facing a specific scenario: data() { return { data: [] } }, async created() { console.log('before async call') try { // async call ... console.log('after async call') t ...

Placing a Fresh Item into a Designated Slot within an Array

Imagine having a MongoDB collection that consists of an array of objects being retrieved from an Angular Resource. [{_id: "565ee3582b8981f015494cef", button: "", reference: "", text: "", title: "", …}, {_id: "565ee3582b8981f015494cf0", button: "", ref ...

"Return to previous view with the zoom back feature in CanvasJS

How can I implement a zoom back button in CanvasJS using jQuery or normal JavaScript? I've been attempting to place it near the ones in the top right corner, but something seems to be amiss. Alternatively, is it feasible to enable zooming in and out ...

Passing arguments to the callback function in React: a comprehensive guide

Within my react component, I have a collection of elements that I want to make clickable. When clicked, I trigger an external function and pass the item ID as an argument: render () { return ( <ul> {this.props.items.map(item => ( ...

Error in NextJS: Attempting to access a length property of null

Does anyone have insights into the root cause of this error? warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'lengt ...

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

Utilize React and Jest to handle errors by either mocking window values or resolving them

When my app attempts to inject environmental variables at runtime for docker using the window object, I encounter errors in my tests. The code snippet below shows the configuration: url config: declare const window: Window & typeof globalThis & ...

Problem with Material UI Checkbox failing to switch states

I'm a bit confused about the functionality of my checkbox in Material UI. The documentation makes it seem simple, but I'm struggling to get my checkbox to toggle on or off after creating the component. const createCheckBox = (row, checkBoxStatus, ...

Ways to verify whether an array contains any of the specified objects and then store all those objects in Supabase

Perhaps the title of my question is not very clear, but I find it difficult to summarize in just one line. To provide context, it would be best to see the JavaScript query I'm making for Supabase and its response. The data: [ { title: 'Th ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

How can we transfer a jQuery value from an input field without using a single

This task may seem challenging. How can single quotes be eliminated from a variable when passed directly to another variable? I am using jQuery variable $("#test").val() to extract the value from an input below <input type="text" ...

Handling and iterating through unfamiliar objects in AngularJS

I've been exploring the concept of generics in ASP.NET MVC for a while now, and it got me thinking about how generics are used in other languages like AngularJS. Let's say I have 2 endpoints to work with: www.listofstudents.com/all and www.list ...

Divide the data received from an AJAX request

After making my ajax request, I am facing an issue where two values are being returned as one when I retrieve them using "data". Javascript $(document).ready(function() { $.ajax({ type: 'POST', url: 'checkinfo.php', data: ...

Tips for Retrieving a JavaScript Variable's Value in JSP

In my JSP file, I have implemented dynamic rows of textboxes using JavaScript. Now that I have input values into these fields, how can I retrieve those values in my result JSP page? ...