Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

Send Arrays from LWC to Apex Methods

Let's look at how to send arrays from LWC to Apex methods.

By Teja, ex-Salesforce engineer · Updated February 23, 2021 · 1 min read

Sending data to LWC components is not straightforward in Lightning. However, major heavy lifting is done by the framework for us.

When we send primitive data it's pretty much straightforward.

Then comes the million dollar question, how can we send an Array from LWC to an Apex Controller.

When we send an Array in LWC it will be received as a List in Apex.

Here is the sample code!

import { api, LightningElement, wire } from "lwc";

import foobar from "@salesforce/apex/ExploreAccountsController.fetchAccounts";

//Creating an Array
const accountsArray = ["united group", "sforce", "salesforce casts"];

export default class ExploreWiredApex extends LightningElement {

    //Sending the array to the Apex method
  @wire(foobar, {
    accArray: accountsArray
  })
  account({ error, data }) {
    if (data) {
      console.log(data);
    } else if (error) {
      console.log(error);
    }
  }
}

exploreAccountsController.js

Here is the Apex method, notice that the param is of type List.

We don't have to do anything, the framework is going to automatically map it for us.

Also, make sure the variable name is similar to that of the key of the object in @wire decorator of LWC component.

public with sharing class ExploreAccountsController {
  
  @AuraEnabled(cacheable=true)
  public static String fetchAccounts(
    String searchText,
    List<String> accArray
  ) {
    System.debug(' 🚀 ' + accArray);
    return 'Successfully Received!!!'
  }
}

exploreAccountsController.cls

Hope this is helpful!


Tip

Grab your FREE course

I have put together a FREE course on Javascript that helps you master Lightning Web Components.

It just takes 2 hours to finish the course and you will be able to feel the difference.

JavaScript for LWC →

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts