-2

My goal is to get the metadata for all my Opportunities in Salesforce (the address, city, and state). I was told to look into query data directly from Apex, then I can return those values to my LWC. I'm not sure If I'm doing it right, but I created an apex file called QueryData.cls, with the code below; (following a YouTube video).

Apex "QueryData.cls" Code:

public with sharing class QueryData {

    @AuraEnabled(cacheable=true)
    public static List<Opportunity> getListofOpportunity()  {

        List<Opportunity> OppList = new List<Opportunity>();
        OppList = [SELECT Id, Service_Adress__c FROM Opportunity LIMIT 5];

        return OppList;

    }

}

Refined Question:

Am I missing anything with my Apex code?

How would I be able to return my values to my LWC?

Anything else that I'm missing?

1

1 Answer 1

1

There's two ways to call Apex, by wire and imperatively.


To call by wire, just import the method and use it with wire.

import getListofOpportunity from '@salesforce/apex/QueryData.getListofOpportunity';
import { LightningElement, wire } from 'lwc';

export default class OpportunityMap extends LightningElement {
  @wire(getListofOpportunity) opportunities;
}

opportunities will have two main properties, data and error. Just wait for data to be populated, and you can show the records.

For example:

<template>
  <template lwc:if={opportunities.data} for:each={opportunities.data} for:item="opportunity">
    <div key={opportunity.Id}>{opportunity.Service_Address__c}</div>
  </template>
</template>

To call imperatively, you just call the method directly from JavaScript:

import getListofOpportunity from '@salesforce/apex/QueryData.getListofOpportunity';
import { LightningElement, wire } from 'lwc';

export default class OpportunityMap extends LightningElement {
  async connectedCallback() {
    let opportunities = await getListofOpportunities(); // Note: cAsE sEnSiTiVe
    // do something with opportunities, which is an Array
  }
}
2
  • Thank you got it to work! My last question: Would there be away to insert each data point of "opportunity.Service_Address__c" to an array? So that It can be run through a for-loop. Or is it not necessary?
    – Pinto
    Apr 13 at 23:17
  • 1
    @Pinto If you only care about the addresses, you can do that: let addresses = opportunities.map((opportunity)=>opportunity.Service_Address__c); The map function takes a transform function that is used to change data from one form to another, and produces a new Array as the result (the original is left alone). If you want unique addresses, you can also use Set: let uniqueAddrs = [...new Set(addresses)]; which would deduplicate the addresses and leave you with another Array of just the unique addresses.
    – sfdcfox
    Apr 14 at 2:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .