How to improve rendering performance with *ngFor in Angular - javascript

I am creating a chat app, and performance is slow when a lot of messages are sent at once. The messages show up but the UI becomes unresponsive for a while. Here is a simplified version of the code and how can I fix this?
HTML:
<div class="message-notification" *ngFor="let newMessage of chatMessages"; trackBy: trackByMsgs>
<custom-notification [incomingChat]="newMessage" (dismissedEvent)="onDismiss($event)" (closedEvent)="onNotifcationClose($event)"></custom-notification>
</div>
TS:
newChatMessages: any[];
constructor(private chatService: ChatService) {}
ngOnInit() {
this.chatService.chatMsg.subscribe((msg:any) => {
if (msg) {
this.activatePopup(msg);
}
}
activatePopup(message) {
if (message.msgId !== null && message.title !== null) {
this.setTitle(message);
//If popup is already open then do not display a duplicate popup for the same message
let index = this.isPopupOpen(message);
if (index === -1) {
newChatMessages.push(message);
}else {
newChatMessages[index] = message;
}
}
}
trackByMsgs(index:number, msg:any) {
return msg.msgId && msg.title;
}
isPopUpOpen(message){
let index = -1;
if (this.newChatMessages){
index = this.newChatMessages.findIndex(
msg => msg.id === message.id && msg.title === message.title);
}
return index;
}

The best in your case is to control the angular change detection manually by using OnPush Change Detection Strategy. You should carefully use it, cause when it's on, angular will detect changes only if onChanges lifecycle is been triggered or async pipe has received a new value. It also applies to all the component children.
Then you would need to detect the changes manually by injecting the ChangeDetectorRef in your component and call the method detectChanges on it each time you want to apply your data changes to your dom.
Read this article for better understanding
Another interesting article for improving the performance of your angular app https://medium.com/swlh/angular-performance-optimization-techniques-5b7ca0808f8b
Using trackBy helps angular to memorize the loaded elements in the ngFor and update only the changed once on change detection. But your trackByMsgs returns a boolean which is not what it should return. If you adjust your trackBy to return a unique key like msg.msgId or the index of the item, you might see a difference.

Related

BehaviorSubject observable triggers many times

I subsribed to observable of behaviorSubject and it's triggers too many times. It happens only when i am navigating on the same component route, as an example...folder-folder-folder and now ...delete file triggers x3 times.
Subscribe code:
this.headerService.selectedItems.subscribe( {
next:(value) =>
if (this.selectedRowsIds.size >= 1 && value === true) {
this.deleteDocs();
}... and here value comes x3 times
BehaviorSubject:
deleteButton = new BehaviorSubject<any>({});
selectedItems = this.deleteButton.asObservable();
deleteTrigger(trigger: boolean) : void {
this.deleteButton.next(trigger);
}
I tried to unsubcribe, to send false trigger everytime when i navigate, but nothing changes.
I mention that component DOES NOT DESTROY in this case, cause we open folder-folder-folder on the same component, with changing route params.
The Problem can due to many other factors
Due to any change in route in the process.
Due to Not emitting value at right time.
Behavior Subject fires the value as soon as its initialized new BehaviorSubject<any>({}) with an {} (and empty object it emits and this value it holds )
Insufficient working and dependable code to see the flow , if possible please provide insight.
My Solution:
deleteButton :BehaviorSubject<boolean>= new BehaviorSubject<boolean>(false);
deleteTrigger(trigger: boolean) : void {
this.deleteButton.next(trigger);
}
trigger: boolean (here we are only emitting boolean values because input is always boolean)
this.headerService.deleteButton.subscribe(response => {
if(response) {
this.selectedRowsIds.size >= 1 && value === true ?
this.deleteDocs() : '';
}
});
this would subscribe to the action when a value is emitted from deleteButton and the value is true then it would excute desired logic though tenary opeartor
You can use rxjs takeLast with behavior subject to fix the issue or Promise Resolve. takeLast, you could also use take, takeOnce all found in rxjs. Also you do not need to strong type your interfaces on behavior subjects. It's recommended for security concerns. because any is applied.
Also you should make your subscription async and await the answer from the subscription.
RXJS LINK
rxjs
import { BehaviorSubject, takeLast, tap } from 'rxjs';
private yourSubject = new BehaviorSubject<any>({});
//or your choice
private yourSubject = new BehaviorSubject({});
//or your choice
private yourSubject = new BehaviorSubject({} as any);
public yourSubject$ = this.yourSubject.asObservable();
this.yourSubject$.pipe(takeLast(1),tap((item)=>{return item})).subscribe()
Promise resolve
this.yourSubject$.subscribe((element)=>{
const item = Promise.resolve(element)
return item;
});
//or your choice
this.yourSubject$.subscribe(async (element)=> {
const item = await element;
return item;
})

How to fire NGRX Selector foreach children component independently

I have a component which have a role as a widget in a dashboard. So, I'll use an *ngFor to render as many widgets as the dashboard have. The WidgetComponent is only one and receive a part of its data by #Input() from the parent.
parent
<app-widget *ngFor="let widget of widgets"
[widget]="widget">
</app-widget>
In the child, I listen an event using NGRX Selectors:
this.store.pipe(
select(fromStore.selectPage, {widgetId: this.widgetId, page: this.paginator.currentPage}),
distinctUntilChanged() // can be used, but is unnecessary
).subscribe(rows => {
console.log(rows);
});
When I want to change the page, I dispatch a new event in my store:
ngAfterViewInit(): void {
const pages = currentPage < 3
? [1, 2, 3]
: [currentPage - 1, currentPage, currentPage + 1];
const request: PaginatedData = {
widgetId: this.widget.id,
itemsPerPage: paginator.itemsPerPage,
pages
};
this.store.dispatch(updatePagesAction({request}));
}
selector:
export const selectPage = createSelector(selectState, (state, props) => {
const table = state.widgetTables.find(x => x.widgetId === props.widgetId);
if (typeof table === 'undefined') {
return [];
}
const existingPageKey = Object.keys(table.pages).find(key => key === props.page.toString());
return existingPageKey ? table.pages[existingPageKey] : [];
});
Problem: When I dispatch an action for a widget, there will be fired the selector for all widgets which listen in same time at the store.
I need to fire the selector only for in cause widget. The problem can be that I use the same selector for all widgets?
I can not use a filter() in my widget component pipe() because even if I use something like filter(x => x.widgetId === this.widget.Id), the event will be fired and all widgets will receive again the data, even if is equals with the last value.
Ah, I know: this can be due of at every pange changed, my store return a new state (for all widgets) and so the selectors are fired for all.
Also, I have this feature stored in a service which works very well, but because the app use already ngrx in another modules, I'm thought that is better to align all data which must be saved in memory and used later, to be saved inside a ngrx store (and not using custom services).
thanks
How I would approach the problem
I think you can use a function that returns a selector instead, Try to implement like below
export const selectPageWith = ({widgetId, page}: widgetId: number, page: any) =>
createSelector(selectState, state => {
const table = state.widgetTables.find(x => x.widgetId === widgetId);
if (typeof table === 'undefined') {
return [];
}
const existingPageKey = Object.keys(table.pages).find(key => key === page.toString());
return existingPageKey ? table.pages[existingPageKey] : [];
})
Now you can use this in your component like
this.store.pipe(
select(fromStore.selectPageWith({widgetId: this.widgetId, page: this.paginator.currentPage}),
distinctUntilChanged() // can be used, but is unnecessary
).subscribe(rows => {
console.log(rows);
});
Explanation
Simply we are trying to create unique selectors for each of the widget. By creating a function that returns a selector, different parameters produces different selectors for each widget

RxJS: forkJoin seems not working

I'm currently using combineLatest() method to get all my friends and make it as a list. However, it produces an ordering issue when I try to remove an item from the beginning. (View does not render correctly) Therefore, I'd like to switch from combineLatest() to forkJoin() to get all the friends at once.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
friends$: Observable<User[]>;
getMyFriendList() {
this.friends$ = this.userService.getMyFriendsId().switchMap(friendKeys => {
return Observable.forkJoin(friendKeys.map(user => this.userService.getFriends(user.key)));
});
}
But nothing happens when I call forkJoin(). What am I doing wrong here?
getMyFriendsId() {
let friendRef = this.getFriendRef(this.currentUserId);
this.friends$ = friendRef.snapshotChanges().map(actions => {
return actions.map(a => ({ key: a.payload.doc.id, ...a.payload.doc.data()}));
});
return this.friends$;
}
getFriends(uid: string) {
return this.getUsersRef(uid).valueChanges();
}
EDIT
getMyFriendsId() updates a new data when a logged in user remove another user in the friend list.
<ion-list>
<ion-list-header>Friends <span class="total-friends"></span></ion-list-header>
<ion-item-sliding *ngFor="let user of friends$ | async">
<ion-item *ngIf="user" (click)="viewUserProfile(user)">
<ion-avatar (click)="showOriginalAvatarImage()" item-start>
<img-loader [src]="user.thumbnailURL" [spinner]="true"></img-loader>
</ion-avatar>
<h2>{{user.displayName}}</h2>
<p>{{user.statusMessage}}</p>
</ion-item>
...
<ion-list>
Lifecycle event
ionViewWillEnter() {
// Runs when the page is about to enter and become the active page.;
this.getMyFriendList();
}
.forkJoin() combines all the observables, and will only emit the values if all observables are COMPLETED. The reason your code doesn't work is because a you are using valueChanges(), and it is a type of event that will never complete -- they are forever listening to the changes of the value!
If you really want to use .forkJoin (or to prove the point), add a take(1) into your valueChanges:
getFriends(uid: string) {
return this.getUsersRef(uid).valueChanges().take(1);
}
The above code will work because it forcefully completes the observable with take(), but obviously will defeat the purpose because your code will only work once. Conclusion is if you want to keep on observing for a change of a particular value, and combine it with another observable, yes, use combineLatest()

RxJS and React multiple clicked elements to form single data array

So I just started trying to learn rxjs and decided that I would implement it on a UI that I'm currently working on with React (I have time to do so, so I went for it). However, I'm still having a hard time wrapping my head around how it actually works... Not only "basic" stuff like when to actually use a Subject and when to use an Observable, or when to just use React's local state instead, but also how to chain methods and so on. That's all too broad though, so here's the specific problem I have.
Say I have a UI where there's a list of filters (buttons) that are all clickeable. Any time I click on one of them I want to, first of all, make sure that the actions that follow will debounce (as to avoid making network requests too soon and too often), then I want to make sure that if it's clicked (active), it will get pushed into an array and if it gets clicked again, it will leave the array. Now, this array should ultimately include all of the buttons (filters) that are currently clicked or selected.
Then, when the debounce time is done, I want to be able to use that array and send it via Ajax to my server and do some stuff with it.
import React, { Component } from 'react';
import * as Rx from 'rx';
export default class CategoryFilter extends Component {
constructor(props) {
super(props);
this.state = {
arr: []
}
this.click = new Rx.Subject();
this.click
.debounce(1000)
// .do(x => this.setState({
// arr: this.state.arr.push(x)
// }))
.subscribe(
click => this.search(click),
e => console.log(`error ---> ${e}`),
() => console.log('completed')
);
}
search(id) {
console.log('search --> ', id);
// this.props.onSearch({ search });
}
clickHandler(e) {
this.click.onNext(e.target.dataset.id);
}
render() {
return (
<section>
<ul>
{this.props.categoriesChildren.map(category => {
return (
<li
key={category._id}
data-id={category._id}
onClick={this.clickHandler.bind(this)}
>
{category.nombre}
</li>
);
})}
</ul>
</section>
);
}
}
I could easily go about this without RxJS and just check the array myself and use a small debounce and what not, but I chose to go this way because I actually want to try to understand it and then be able to use it on bigger scenarios. However, I must admit I'm way lost about the best approach. There are so many methods and different things involved with this (both the pattern and the library) and I'm just kind of stuck here.
Anyways, any and all help (as well as general comments about how to improve this code) are welcome. Thanks in advance!
---------------------------------UPDATE---------------------------------
I have implemented a part of Mark's suggestion into my code, but this still presents two problems:
1- I'm still not sure as to how to filter the results so that the array will only hold IDs for the buttons that are clicked (and active). So, in other words, these would be the actions:
Click a button once -> have its ID go into array
Click same button again (it could be immediately after the first
click or at any other time) -> remove its ID from array.
This has to work in order to actually send the array with the correct filters via ajax. Now, I'm not even sure that this is a possible operation with RxJS, but one can dream... (Also, I'm willing to bet that it is).
2- Perhaps this is an even bigger issue: how can I actually maintain this array while I'm on this view. I'm guessing I could use React's local state for this, just don't know how to do it with RxJS. Because as it currently is, the buffer returns only the button/s that has/have been clicked before the debounce time is over, which means that it "creates" a new array each time. This is clearly not the right behavior. It should always point to an existing array and filter and work with it.
Here's the current code:
import React, { Component } from 'react';
import * as Rx from 'rx';
export default class CategoryFilter extends Component {
constructor(props) {
super(props);
this.state = {
arr: []
}
this.click = new Rx.Subject();
this.click
.buffer(this.click.debounce(2000))
.subscribe(
click => console.log('click', click),
e => console.log(`error ---> ${e}`),
() => console.log('completed')
);
}
search(id) {
console.log('search --> ', id);
// this.props.onSearch({ search });
}
clickHandler(e) {
this.click.onNext(e.target.dataset.id);
}
render() {
return (
<section>
<ul>
{this.props.categoriesChildren.map(category => {
return (
<li
key={category._id}
data-id={category._id}
onClick={this.clickHandler.bind(this)}
>
{category.nombre}
</li>
);
})}
</ul>
</section>
);
}
}
Thanks, all, again!
Make your filter items an Observable streams of click events using Rx.Observable.fromevent (see https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/events.md#converting-a-dom-event-to-a-rxjs-observable-sequence) - it understands a multi-element selector for the click handling.
You want to keep receiving click events until a debounce has been hit (user has enabled/disabled all filters she wants to use). You can use the Buffer operator for this with a closingSelector which needs to emit a value when to close the buffer and emit the buffered values.
But leaves the issue how to know the current actual state.
UPDATE
It seems to be far easier to use the .scan operator to create your filterState array and debounce these.
const sources = document.querySelectorAll('input[type=checkbox]');
const clicksStream = Rx.Observable.fromEvent(sources, 'click')
.map(evt => ({
name: evt.target.name,
enabled: evt.target.checked
}));
const filterStatesStream = clicksStream.scan((acc, curr) => {
acc[curr.name] = curr.enabled;
return acc
}, {})
.debounce(5 * 1000)
filterStatesStream.subscribe(currentFilterState => console.log('time to do something with the current filter state: ', currentFilterState);
(https://jsfiddle.net/crunchie84/n1x06016/6/)
Actually, your problem is about RxJS, not React itself. So it is easy. Suppose you have two function:
const removeTag = tagName =>
tags => {
const index = tags.indexOf(index)
if (index !== -1)
return tags
else
return tags.splice(index, 1, 0)
}
const addTag = tagName =>
tags => {
const index = tags.indexOf(index)
if (index !== -1)
return tags.push(tagName)
else
return tags
}
Then you can either using scan:
const modifyTags$ = new Subject()
modifyTags$.pipe(
scan((tags, action) => action(tags), [])
).subscribe(tags => sendRequest(tags))
modifyTags$.next(addTag('a'))
modifyTags$.next(addTag('b'))
modifyTags$.next(removeTag('a'))
Or having a separate object for tags:
const tags$ = new BehaviorSubject([])
const modifyTags$ = new Subject()
tags$.pipe(
switchMap(
tags => modifyTags$.pipe(
map(action => action(tags))
)
)
).subscribe(tags$)
tags$.subscribe(tags => sendRequest(tags))

When I run setState with a large object my component gets removed from the DOM

I'm building an app that lets you organize emojis via drag and drop. I have a method that runs on drop that sorts a large array of emoji objects. When I run setState and commit the object back into a parent component's state, React removes the parent component from the DOM. It just disappears... There are no errors in the console and using react dev tools i can see that the components state has in fact been updated with the new object. Any help would be much appreciated.
This sorting mechanism sends the updated object to it's parent components via props:
endDrag(props, monitor, dragComponent) {
if (monitor.didDrop()) {
let sourceEmoji = dragComponent.props.emoji
let targetEmoji = monitor.getDropResult().props.emoji
const updatedCategorizedEmojis = props.categorizedEmojis.map((category)=> {
return category.emojis.map((emoji, idx)=> {
if (emoji.id == sourceEmoji.id) {
emoji['newPosition'] = (targetEmoji['newPosition'] - 0.5)
return emoji
} else {
return emoji
}
}).sort((a,b)=> {
if (a['newPosition'] > b['newPosition']) {
return 1
}
if (a['newPosition'] < b['newPosition']) {
return -1
}
}).map((emoji, idx)=> {
emoji['newPosition'] = idx
return emoji
})
})
props.updateSortedEmojis(updatedCategorizedEmojis)
}
}
The array of objects looks like this:
That whole thing gets added to the parent's state and when it does the component gets removed without errors.
Any info would be greatly appreciated, thanks!

Categories

Resources