How to get Proxy object content?
Asked Answered
B

3

16

I am working with lightning web component and apex class. This is new for me.

I am trying to get the content of a Proxy object generated by an Apex class.

But when I console log it I have a result like this :

Proxy { <target>: {}, <handler>: {…} }

This is my LWC component :

import { LightningElement, track, wire } from "lwc";
import getAllActiveAccounts from "@salesforce/apex/AccountsController.getAllActiveAccounts";

export default class HelloWorld extends LightningElement {
  @wire(getAllActiveAccounts) accounts;

  @track foo;
  click() {
    console.log("Show Proxy object accounts ", this.accounts); // Show Proxy object
    console.log("Foo", this.accounts.name); // Show `undefined`
  }
}

Apex class :

public with sharing class AccountsController {
  @AuraEnabled(cacheable = true)
  public static List < Account > getAllActiveAccounts() {
    return [SELECT Id, Name FROM Account LIMIT 10];
  }
}

The Html template is a button that show the console.log on click.

I want to know if it's possible to show the names provided by the apex class ? Or a way to show the Proxy object content or the availabel keys.

Banting answered 19/8, 2019 at 14:18 Comment(1)
I was very confused when I encountered this too.Cauldron
D
6

To get the available keys, you can use Object.key & .data on the Proxy object.

In your case, you can get the keys with this way :

console.log(Object.keys(this.accounts.data[0]));
Drive answered 19/8, 2019 at 15:17 Comment(0)
H
25

To print the Proxy Object use:

JSON.stringify(this.accounts)

To actually use it on some functions use this:

let accounts = JSON.parse(JSON.stringify(this.accounts))
console.log(accounts.name) 
Hainaut answered 4/2, 2020 at 14:33 Comment(0)
D
6

To get the available keys, you can use Object.key & .data on the Proxy object.

In your case, you can get the keys with this way :

console.log(Object.keys(this.accounts.data[0]));
Drive answered 19/8, 2019 at 15:17 Comment(0)
B
5

So what you can do is instead of logging the Proxy object, perform a JSON.stringify():

console.log("Show Proxy object accounts ", JSON.stringify(this.accounts)); 

Another great trick is to use the custom dev formatter: https://dev.to/daveturissini/debug-lightning-web-components-lwc-track-and-api-properties-using-chrome-dev-tools-formatter-49c5

Also this blog provides lots of good advice: https://developer.salesforce.com/blogs/2019/02/debug-your-lightning-web-components.html

Bug answered 19/8, 2019 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.