[SalesForce] LWC Pass variable to Apex SOQL

I'm trying to get the list of users in a Branch office. I have the following Apex performing two selections one based on a passed Id and the other based on a passed Office name.

    public with sharing class Top100 {
    @AuraEnabled(cacheable=true)
    public static List<User> getMktUsers(String usrId) {
        System.debug('theuserid:'+usrId);
        User ThisUser = [SELECT Id, Name, Office__c FROM User WHERE Id = :usrId LIMIT 1];
        System.debug('TheUserOfficeis: ' + ThisUser.Office__c);
        return [SELECT Id, Name FROM User WHERE Office__c = :ThisUser.Office__c and IsActive = True];
    }

    @AuraEnabled(cacheable=true)
    public static List<User> getUserList(String TheOffice) {
        System.debug('TheOfficeIs:' + TheOffice);
        return [SELECT Id, Name FROM User WHERE Office__c = :TheOffice and IsActive = True LIMIT 5];
    }
}

The JS looks like this:

import { LightningElement, api, track, wire } from "lwc";
import getMktUsers from "@salesforce/apex/Top100.getMktUsers";
import getUserList from "@salesforce/apex/Top100.getUserList";

import Id from "@salesforce/user/Id";

console.log(window.location.href);
let url_string = window.location.href;
let url = new URL(url_string);
let rid = url.searchParams.get("Id");
console.log(rid);

export default class Top100 extends LightningElement {
  @api recordId;
  @api objectApiName;

  @wire(getMktUsers, { usrId: { Id } }) MktUsers;
  @wire(getUserList, { TheOffice: "Orlando" }) accounts;

  userId = Id;
  recordId = rid;
  objectApiName = "lda_Opportunity__c";
}

Results from the second query (hard coded office) work fine, but the first query (passing the user id) do not work. Debug statement displaying the user id doesn't even fire. No errors. Can anyone help me figure out what is going on?

Best Answer

Try this:

import { LightningElement, api, track, wire } from "lwc";
import getMktUsers from "@salesforce/apex/Top100.getMktUsers";
import getUserList from "@salesforce/apex/Top100.getUserList";

import Id from "@salesforce/user/Id";

console.log(window.location.href);
let url_string = window.location.href;
let url = new URL(url_string);
let rid = url.searchParams.get("Id");
console.log(rid);

export default class Top100 extends LightningElement {
  @api recordId;
  @api objectApiName;
  userId = Id;

  @wire(getMktUsers, { usrId: '$userId' }) MktUsers;
  @wire(getUserList, { TheOffice: "Orlando" }) accounts;

  recordId = rid;
  objectApiName = "lda_Opportunity__c";
}

You have to pass the value dynamically using the $ symbol before the variable name.

https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.data_wire_example

Related Topic