I'm trying to poll an endpoint with varying refreshIntervals. For instance, it starts with 5 seconds and then it changes to 10 seconds by pressing a button in the UI.
I'm using swrv but I'm not able to create a dependency that triggers the refreshInterval to change. How could I do this?
I assumed it should look something like this and I'd put a dependency somewhere:
const { data, error } = useSWRV("some key", fetcher, {
refreshInterval: <dynamic value>,
});
Related
For example, if I trigger onDidChangeTextDocument events consecutively, with an interval of at maximum 1 second, then I would like to avoid this event's associated logic.
However, if 1 second has passed since the lastest onDidChangeTextDocument has been triggered, I would like for it to proceed with its logic.
This approach is known as "coalescing events". A typical approach is to start a timer when an event appears with the required interval. Every new event restarts the timer, so it never triggers unless there are no new events within the timer value. The triggered timer then calls any further code, handling the coalesced events. This might cause some problems if you have to process all data sent by each event. In that case you have to collect that data on each invocation of your event handler.
Here's code to handle changes per file in a VS Code extension:
private changeTimers = new Map<string, ReturnType<typeof setTimeout>>(); // Keyed by file name.
workspace.onDidChangeTextDocument((event: TextDocumentChangeEvent) => {
if (event.contentChanges.length > 0) {
const fileName = event.document.fileName;
const timer = this.changeTimers.get(fileName);
if (timer) {
clearTimeout(timer);
}
this.changeTimers.set(fileName, setTimeout(() => {
this.changeTimers.delete(fileName);
... your processing here
}, 1000));
}
});
I downloaded the latest build of ngx-admin (https://github.com/akveo/ngx-admin), and served it up locally. In the ./#core/data/users.service.ts file I have added the following method
getHeroes (): Observable<any[]> {
return this.http.get<any[]>('http://localhost:63468/api/clubs/heroes');
}
That endpoint just returns some JSON like so:
[{"id":11,"name":"Mr. Nice"},{"id":12,"name":"Mr. Nice2"},{"id":13,"name":"Mr. Nice3"},{"id":14,"name":"Mr. Nice4"},{"id":15,"name":"Mr. Nice5"},{"id":16,"name":"Mr. Nice6"},{"id":17,"name":"Mr. Nice7"},{"id":18,"name":"Mr. Nice8"},{"id":19,"name":"Mr. Nice9"},{"id":20,"name":"Mr. Nice0"}]
In ./#theme/components/header/header.component.ts I have added a click handler method:
getHero() {
this.userService.getHeroes()
.subscribe(heroes => {
debugger;
this.hero = heroes[0]
});
}
In ./#theme/components/header/header.component.html I added a button and click event like:
<button (click)="getHero()">
add hero
</button>
{{hero?.name}}
I have done this to the same example project on Angular.io (https://angular.io/tutorial/toh-pt6).
The issue is:
In the ngx-admin application, once that debugger line is hit, the this.hero = heroes[0] is properly set with the data I expect. Once the execution leaves that line of code, the view is not updated. If I inject private ref: ChangeDetectorRef, and call this.ref.detectChanges(); immediately after this.hero = heroes[0], then the view is properly updated. However, in the angular.io example of heroes, the view is properly updated within the context of the subscribe call. In that application no this.ref.detectChanges(); is required.
Is there something in the ngx-admin project that is messing up the Angular change detection?
I'm trying to verify that an account was created successfully, but after clicking the submit button, I need to wait until the next page has loaded and verify that the user ended up at the correct URL.
I'm using pollUntil to check the URL client side, but that results in Detected a page unload event; script execution does not work across page loads. in Safari at least. I can add a sleep, but I was wondering if there is a better way.
Questions:
How can you poll on something like this.remote.getCurrentUrl()? Basically I want to do something like this.remote.waitForCurrentUrlToEqual(...), but I'm also curious how to poll on anything from Selenium commands vs using pollUntil which executes code in the remote browser.
I'm checking to see if the user ended up at a protected URL after logging in here. Is there a better way to check this besides polling?
Best practices: do I need to make an assertion with Chai or is it even possible when I'm polling and waiting for stuff as my test? For example, in this case, I'm just trying to poll to make sure we ended up at the right URL within 30 seconds and I don't have an explicit assertion. I'm just assuming the test will fail, but it won't say why. If the best practice is to make an assertion here, how would I do it here or any time I'm using wait?
Here's an example of my code:
'create new account': function() {
return this.remote
// Hidden: populate all account details
.findByClassName('nextButton')
.click()
.end()
.then(pollUntil('return location.pathname === "/protected-page" ? true : null', [], 30000));
}
The pollUntil helper works by running an asynchronous script in the browser to check a condition, so it's not going to work across page loads (because the script disappears when a page loads). One way to poll the current remote URL would be to write a poller that would run as part of your functional test, something like (untested):
function pollUrl(remote, targetUrl, timeout) {
return function () {
var dfd = new Deferred();
var endTime = Number(new Date()) + timeout;
(function poll() {
remote.getCurrentUrl().then(function (url) {
if (url === targetUrl) {
dfd.resolve();
}
else if (Number(new Date()) < endTime) {
setTimeout(poll, 500);
}
else {
var error = new Error('timed out; final url is ' + url);
dfd.reject(error);
}
});
})();
return dfd.promise;
}
}
You could call it as:
.then(pollUrl(this.remote, '/protected-page', 30000))
When you're using something like pollUntil, there's no need (or place) to make an assertion. However, with your own polling function you could have it reject its promise with an informative error.
I don't quite get the idea behind enquire.js' "setup" handler.
Case:
I want to load content through ajax once when you're not in a small viewport (lt 600px).
Naturally I would do enquire.register('(min-width: 600px)', { setup: myFunction });.
Problem:
Now I tested this multiple times but the setup handler also gets fired when you're in a small screen, which totally eliminates the benefit of the setup handler imo, because you would want to only load the ajax content once you enter a viewport bigger than 600px, wouldn't you?
See example jsfiddle.
Conclusion:
So actually I wouldn't even need the setup handler because I simply could load the content outside the enquire register and would have the same effect. (Which of course isn't what I want...)
Can someone tell me if I just misunderstood the purpose of setup or is there something I'm missing?
Combine with the deferSetup flag to defer the setup callback until the first match. This example illustrates the feature:
enquire.register(someMediaQuery, {
setup : function() {
console.log("setup");
},
deferSetup : true,
match : function() {
console.log("match");
},
unmatch : function() {
console.log("unmatch");
}
});
You can see a working example here: http://wicky.nillia.ms/enquire.js/examples/defer-setup/
I am working on an application and was doing something like this:
dojo.ready(
function(){ require['dojo/parser','dijit/registry','dojo/on'],function(.....){
//find a dijit and wrap it in event handling code.});
I was getting an error indicating that dojo was trying to register a widget with an id that was already in use. To solve the problem I entered this line of code:
//before finding the dijit destroy the existing registry.
However, logically this prevents the next line from working because now no widget exists to which I can connect an event. How can I recover the dijit ids?
The best solution is to find out why your code is trying to register a widget with an id that is already in use and change it to not to do so.
The #mschr's solution should work, but I would advise again using it, as it can break your code in many other places and you are likely to spend hours investigating strange behavior of your application.
Anyway, if you are willing to do it that way and automatically destroy widgets with the same ID, do not override registry.add() method. You could do it, but it does not mean, you should do it (especially in programming). Employ dojo/aspect instead to call a function that will destroy the widget with the same ID before registry.add() is called:
require([
"dojo/aspect",
"dijit/registry"
], function(
aspect,
registry
) {
aspect.before(registry, "add", function(widget) {
if(registry.byId(widget.id)) {
registry.byId(widget.id).destroy();
// this warning can save you hours of debugging:
console.warn("Widget with id==" + widget.id + " was destroyed to register a widget with the same id.");
}
return [widget];
});
});
I was myself curious how to accomplish #mschr solution without that override, so I created an jsFiddle to experiment: http://jsfiddle.net/phusick/feXVT/
What happens once you register a dijit is the following; it is referenced by the dijit.registry._hash:
function (widget) {
if (hash[widget.id]) {
throw new Error("Tried to register widget with id==" + widget.id + " but that id is already registered");
}
hash[widget.id] = widget;
this.length++;
}
Now, every now and then you would have a contentpane in which you would put a widget programatically (programatically, hence dojo.parser handles cpane.unload and derefences / destroys parser-instantiated widgets).
When this happens, you need to hook onto some form of 'unload', like, when your call cpane.set('content' foo) or cpane.set('href', bar). Hook is needed to destroy and unregister the instances you keep of widgets - otherwise you would have a memoryleak in your program.
Normally, once an object has no references anywhere - it will get cleaned out of memory however with complex objects such as a widget might be, 'class-variables' often have reference to something _outside _widget scope which flags the widget unsafe to delete to the garbage collector... Once you get this point, you will know to perform proper lifecycles, yet not before the concept is fully understood..
What you could do is to override the dijit.registry with your own handler and have any widgets that are doublets destroyed automatically like so:
// pull in registry in-sync and with global scoped
// accees (aka dijit.registry instead of dj_reg)
require({
async:false,
publishRequireResult:true
}, [
"dijit.registry"
], function(dj_reg) {
dijit.registry.add = function(widget) {
// lets change this bit
if (this._hash[widget.id]) {
this._hash[widget.id].destroy(); // optinally destroyRecursively
this.remove(widget.id)
}
this._hash[widget.id] = widget;
this.length++;
}
});