0

I have a @wire function which calls an apex method which should return some list of contacts. However I get the following error on page load:

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

Here is my JS controller:

import { LightningElement, wire, api } from 'lwc';
import findContacts from '@salesforce/apex/ContactComponentController.findContacts';

export default class ContactList extends LightningElement {
    contacts;
    error;
    keyword;

    @wire(findContacts, { accountId: '$recordId', keyword: this.keyword }) 
    wiredContacts({ error, data }) {
        if (data) {
            this.contacts = data; 
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.contacts = undefined;
        } 
    }
}

Here is my Apex method:

@AuraEnabled(cacheable=true)
public static List<Contact> findContactsFull(String accountId, String keyword) {
    String queryString = '';
    String key = '%' + keyword + '%';

    queryString += 'SELECT Id, Name, Email, Birthdate, Title, AccountId FROM Contact WHERE AccountId=:accountId ';

    if(keyword != null) {
        queryString += 'AND Name Like :' + keyword;
    }

    return database.query(queryString);
}

As far as I can tell keyword is defined at the top of the JS so I don't understand why I would get an undefined error. Even if I give a string value to keyword I get the same error.

  • 1
    replace this.keyword to '$keyword' – rahul gawale May 25 at 16:16
3

You can not use this while passing arguments to the wired methods.

Use '$propertyName' instead, just like you have done for accountId.

This should work.

@wire(findContacts, { accountId: '$recordId', keyword: '$keyword' }) 
wiredContacts({ error, data }) {
    if (data) {
        this.contacts = data; 
        this.error = undefined;
    } else if (error) {
        this.error = error;
        this.contacts = undefined;
    } 
}
| improve this answer | |
  • 1
    Knew it had to be something simple! Thanks – Luke Bray May 25 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.