ngOnInit called multiple times after database changes in Angular and Typescript

67 Views Asked by At

I have an app which is removing records from a Firestore database when the user clicks a button. On console I can see that ngOnInit is being called once with the old data and then twice with the new updated data. I am pushing these responses to an array so I end up with an array with 3 values instead of 1.

I have tried to pipe the subscribed data to take(1) but obviously it's returning the first one which is the old data before the change. I'm trying to implement onPush but I'm just getting a blank page.

swap-requests.html

<ion-content>
  <ion-grid class="ion-grid-width-md" *ngIf="user" >
    <tr *ngFor="let swaps of userSwapRequests;">
      <ion-row class="ion-padding" size="auto">
        <ion-col>
          <td *ngFor="let user of swaps.userCard">
            <ion-img [src]="user.images.small"
                     style="background: #F2F2F2;"></ion-img>
          </td>
        </ion-col>
        <ion-col>
          <td *ngFor="let friend of swaps.friendCard">
            <ion-img [src]="friend.images.small"
                     style="background: #F2F2F2;"></ion-img>
            </td>
        </ion-col>
      </ion-row>
<ion-row>
          <ion-button expand="block" color="danger" (click)="cancelSwap(swaps.swapData, swaps)">Cancel Swap</ion-button>
        </ion-col>
      </ion-row>
</ion-grid>
</ion-content>

swap-requests.page.ts


@Component({
  selector: 'app-swap-requests',
  templateUrl: './swap-requests.page.html',
  styleUrls: ['./swap-requests.page.scss'],
})


export class SwapRequestsPage implements OnInit {
  user: any[] = [];
  userSwapRequests: any[] = [];
  currentFriend: User[] = [];
  swapArray: any[] = [];

  constructor(
    private dataService: DataService,
    private pokeService: PokemoncardsService,
    private ToastCtrl: ToastController,
  ) {
    
  }

  ngOnInit() {
    this.dataService.loadUser(environment.currentUser).pipe(take(1)).subscribe((res: User[]) => {
      this.user.push(res);
      console.log('user', this.user);

      this.getUserPendingRequests();
    });
  }

  // get requests made by friends
  getUserPendingRequests() {
    this.userSwapRequests = [];

    let userSwapsList = this.user.map(data => data.swap_request);

    this.buildSwapArray(this.userSwapRequests, userSwapsList);
  }


  getFriend(value: any) {
    let friend: any[] = [];

    this.dataService.loadUser(value).subscribe((res: User[]) => {
      friend.push(res);
    });
    return friend;
  }

  getPokemonCard(number: any) {
    let result: any = [];
    this.pokeService.getPokeCard(number).subscribe(res => {
      result.push(res);
    });
    return result;
  }

  // create new array with API responses and friend's data
  async buildSwapArray(swaplist: any, userList: any) {

    userList.forEach((array: any) => {
      array.forEach((swap: any) => {
        let card: any;
        let usercard: any;
        let friend: any;

        Object.entries(swap).find(([key, value]) => {
          if (key === 'friend_card') {
            card = this.getPokemonCard(value);
            
          }
          if (key === 'user_card') {
            usercard = this.getPokemonCard(value);;
          }
          if (key === 'friend_id') {
            friend = this.getFriend(value);
          }
        })
        let newArray = {
          'friendCard': card,
          'userCard': usercard,
          'friend': friend,
          'swapData': swap,
        }
        swaplist.push(newArray);
        console.log('swapArray', this.userSwapRequests);
      })
    })
  }

  async cancelSwap(swapArray: any) {
    console.log('swapArray', swapArray);
    this.dataService.deleteSwapRequest(swapArray);

    let id = this.user.map(data => data.id);
    let friend: any;
    id.forEach((array) => {
      friend = array;
    })

    let friendArray: any = {
      'friend_card': swapArray.user_card,
      'friend_id': friend,
      'user_card': swapArray.friend_card,
    }
    let friendId = swapArray.friend_id;
    this.dataService.deleteFriendSwapRequest(friendArray, friendId);

    console.log('testsplice', this.userSwapRequests);
    const toast = await this.ToastCtrl.create({
      message: 'Swap confirmed',
      duration: 2000
    });
    toast.present();
  }

DataService:

export class User {
  id?: string;
  cards: [] = [];
  user_name: string | undefined;
  friends: [] = [];
  wishlist: [] = [];
  swaps: [] = [];
  pending_swap: [] = [];
  avatar: string | undefined;
  swap_request: [] = [];
  confirmed_swap: [] = [];
}

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private firestore: Firestore) { }

  loadUser(id: any): Observable<User[]> {
    const result = doc(this.firestore, `users/${id}`);
    return docData(result, { idField: 'id' }) as Observable<User[]>;
  }

  deleteSwapRequest(swapRequest: any) {
    const cardsIdRef = doc(this.firestore, `users/${environment.currentUser}`);
    return updateDoc(cardsIdRef, {
      swap_request: arrayRemove(swapRequest)
    });
  }

  deleteFriendSwapRequest(swapRequest: any, friend:any) {
    const cardsIdRef = doc(this.firestore, `users/${friend}`);
    return updateDoc(cardsIdRef, {
      pending_swap: arrayRemove(swapRequest)
    });
  }
0

There are 0 best solutions below