I'm using Apex to query data directly from Apex. I have the Wire Service working correctly for HTML, but I want to be able to record my data to an array in my LWC JavaScript file.
Am I missing something or doing it wrong? Should I create a method instead?
LWC JS Code:
import { LightningElement, wire } from 'lwc';
// Importing from the "MapMarkers.js" file.
import { MapMarkers } from './MapMarkers';
// Importing from the "mappingBox" LWC.
import { SearchString, SearchState } from 'c/mappingBox';
// Importing from the "messageChannels" folder.
import { subscribe, MessageContext } from 'lightning/messageService';
import COUNTER_FILE from '@salesforce/messageChannel/updatecounter__c';
// Importing Apex "QueryData" code, to get Opportunity object and fields data.
import getOpportunityList from '@salesforce/apex/QueryData.getOpportunityList';
// -----------------------------------------------------------------------------
// Global Variables.
let SearchStreet = '20 abc St';
let SearchCity = 'boston';
var myArray = [];
export default class Mapping extends LightningElement {
// ** Still in work **
@wire(getOpportunityList)
opportunities;
myArray = this.opportunities;
Apex Code:
public with sharing class QueryData {
@AuraEnabled(cacheable=true)
public static List<Opportunity> getOpportunityList() {
List<Opportunity> OppList = new List<Opportunity>();
OppList = [SELECT Id, Service_Address__c, Development_Rep__c, Name, Project_Type__c, CloseDate FROM Opportunity LIMIT 5];
return OppList;
}
}
Refined Question:
The reasons why I didn't create a method was that I need to be able to past this array to the "MapMarkers.js" file, and I don't think a LWC method can be import correctly to a JavaScript file.
Best Answer
Wire methods are asynchronous. That means you can't get the data during the construction of your component;
myArray = this.opportunities;
executes beforegetOpportunityList
does. If you want to do anything with the data in Javascript, you need to wait for the data to load. Alternatively, using a wire handler allows you to correctly set the data when it is available.Or the construction you'll find in the documentation:
Note that the data property will be read-only, so you will need to copy the data before you can use.