Send Arrays from LWC to Apex Methods

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!


💡
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.