0

In the js class, I call the apex getCityCurrentUser() method, which should return me a string, but I end up with an empty value. But the apex class works fine and gets my value from the database, which I try to return to js as a string (I make a log of this operation and see that my code exactly fills the string with the value I need). What's wrong?

@AuraEnabled(cacheable=true)
public static String getCityCurrentUser() {
    if (!Schema.sObjectType.User.fields.City.isUpdateable()) {
        return null;
    } else {
        List<User> currentUser = [SELECT City FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1];
        String cityUser;
        for (User u : currentUser) {
            cityUser = u.City;
        }
        System.debug('currentCity ' + cityUser);
        return cityUser;
    }
}

This is a log entry: USER_DEBUG [98]|DEBUG|currentCity Mogilev

connectedCallback() {
        let userCity = getCityCurrentUser();
        console.log('userCity: ' + getCityCurrentUser());
        performCallout({location: 'Minsk' }).then(data => {
            this.mapMarkers = [{
                location: {
                    Latitude: data['cityLat'],
                    Longitude: data['cityLon']
                },
                title: data['cityName'],
            }];
            this.result = data;
        }).catch(err => console.log(err));
    }

This is a log entry: userCity: [object Promise]

This is a log entry (JSON.stringify): userCity: {}

1
  • Can you please show how "getCityCurrentUser" is defined in your LWC and note that the connectedCallback may well be invoked before any wires. Why are you doing this in the connectedCallback? Please explain your LWC's lifecycle. Please edit the question to add these details.
    – Phil W
    Apr 19, 2021 at 13:37

1 Answer 1

2
    let userCity = getCityCurrentUser();

An imperative Apex call returns a Promise, because it has to go to the server and back. JavaScript won't wait by default, giving you just the Promise, so you have to wait until the Promise resolves.

You have two options here. You can either use Promise.then, or await.

// If you use await, the function must be async.
async connectedCallback() {
  try {
    // Waits here
    let userCity = await getCityCurrentUser();
    // rest of code here
  } catch(e) { 
    // Handles any "reject()" from the Promise
  }

Or...

connectedCallback() {
  getCityCurrentUser()
  .then((userCity) => performCallout({location: 'Minsk' }))
  .then(data => {
      // rest of code //
  })
  .catch(e => this.dealWithTheError(e));

Or...

connectedCallback() {
  getCityCurrentUser()
  .then((userCity) => {
    performCallout({location: 'Minsk' })
    .then(data => {
      // rest of code //
    })
  })
  .catch(e => this.dealWithTheError(e));

Any way you slice it, you need to wait for the asynchronous response in order to continue.

You must log in to answer this question.

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