Suhas Jain
Suhas Jain

Reputation: 43

variable values undefined in LWC - JavaScript

I have declared a const 'offset', and when I try to fetch this and update in a function , the value is undefined. Hence I wont be able to add value to const. Below is sample code

import { LightningElement, wire, track , api } from 'lwc';
import getContractWithDetails from '@salesforce/apex/AccountContactController.getContractWithDetails';

const offset = 0;

export default class WrapperClassExampleLWC extends LightningElement {

@track accountsWithContacts;
@track contractWithDetails;

handleScroll(event)
{
   console.log(' stats :' , this.offset);
}

}

handleScroll func is called when the user performs a scrolling action, and every time the scroll bar is reached to the bottom I want to update the offset value to higher value (say for example 30 every time) and fetch new records from apex and append to the table, but above console log gives me stats :undefined , why is this value undefined ? although I can check if the value is undefined and update with required value as below, I want to understand why is this value undefined even though I have set it to 0 , any links and pointers to SF LWC variable documentation would be helpful.

if(this.offset == undefined)
{
this.offset = 0;
}
this.offset = this.offset + 30;

Upvotes: 0

Views: 12262

Answers (2)

suban khoja
suban khoja

Reputation: 171

you have declared the varible outside the class.

So you don't have to use this to access the variable

So your function will look like below

handleScroll(event)
{
   console.log(' stats :' , offset);
}

Note : As you are declaring variable as const you can't change its value. if you want to change its value use let

Upvotes: 1

eyescream
eyescream

Reputation: 19637

const can't be updated after declaration, experiment with https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

And since you have it outside of the class, like some global variable - it doesn't need this. The script is telling you that this.offset doesn't exist (undefined). You can console.log(offset);

I think what you need is to make it a class member and drop the const

Upvotes: 1

Related Questions