1

I want to refresh my Apex every X seconds from my LWC component.

I have a wired function in my component:

initialized;
wiredData;

@wire(getChartData)
chartData(result) {

    this.wiredData = result;

    if (result.data) {
        if (!this.initialized) {
            console.log('Initializing Chart!');
            this.initialized = true;
            
            // Do setup stuff here

            //Invoke a setInterval to rerun this wired method and goto next block
            setInterval(refreshApex(this.wiredData), 5 * 1000);
 
        }
        else {
            console.log('Updating Chart!')
            this.chart.update();
        }
    }
    else if (result.error) {
        console.log('Error in wire function getChartData!');
        console.log(result.error);
    }
}

How do I do this properly?

1 Answer 1

6

You're trying to call the return value of refreshApex, which is a Promise. This won't work the way you expect. You need to use a function, so one of any of the following should work.


Function.prototype.bind makes a function with bound parameters. Perfect for this scenario.

setInterval(refreshApex.bind(this, this.wiredData), 5e3);

An arrow function remembers what this is, and is definitely preferred over the normal function() whenever you can.

setInterval(()=>refreshApex(this.wiredData), 5e3)

You can also just set another function to do the work.

doRefresh() {
  refreshApex(this.wiredData);
}
// ... in your wire handler
setInterval(this.doRefresh, 5e3);

Notice how we do not use parentheses to specify parameters, because this would actually call the method, which isn't what we want.

setInterval's first parameter should be some kind of Function. If it is not, you're doing something wrong. If you're ever not sure, a handy trick is to check:

let x = someExpression;
console.log(x instanceof Function); // this will be true if it is.

If you get anything else, you know you've done something wrong. For example:

let x = refreshApex(this.wiredData);
console.log(x instanceof Function); // this is false, it is a Promise.

Finally, a word of caution. Always store the value from setInterval and call clearInterval before attempting to set a new one.

clearInterval(this.timerId);
this.timerId = setInterval(...);

Also clear the interval in the disconnectedCallback.

If you don't, your method will continue to run every five seconds each time the wire method is called, and you'll end up with a memory leak and degraded performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.