React Native Push Notification stops working after navigating to a different Tab screen

Basically the issue is that – I have a NotificationHandler that registers and handles remote/push notifications. When I render the NotificationHandler outside the NavigationContainer of @react-navigation/native, the NotificationHandler stops working. It registers for Push Notification, but does not receive the notification or display it. However, when I render the NotificationHandler somewhere within the children of NavigationContainer it works! But! It only works unless you switch the tabs, once you switch the tab, the notifications stop showing up.

For the NotificationHandler, the code below uses [email protected], however, for the major part of the development I had been using [email protected] library.

import { useEffect } from 'react'
import {
  Notification,
  NotificationCompletion,
  Notifications,
  Registered,
  RegistrationError,
} from 'react-native-notifications'

function NotificationHandler() {
  useEffect(() => {
    Notifications.registerRemoteNotifications()
    console.log('NotificationHandler registered')

    Notifications.events().registerRemoteNotificationsRegistered(
      (event: Registered) => {
        // TODO: Send the token to my server so it could send back push notifications...
        console.log('Device Token Received', event.deviceToken)
      }
    )
    Notifications.events().registerRemoteNotificationsRegistrationFailed(
      (event: RegistrationError) => {
        console.error(event)
      }
    )

    Notifications.events().registerNotificationReceivedForeground(
      (
        notification: Notification,
        completion: (response: NotificationCompletion) => void
      ) => {
        console.log('Notification Received - Foreground', notification.payload)

        // Calling completion on iOS with `alert: true` will present the native iOS inApp notification.
        completion({ alert: true, sound: true, badge: false })
      }
    )

    Notifications.events().registerNotificationOpened(
      (notification: Notification, completion: () => void, action: any) => {
        console.log('Notification opened by device user', notification.payload)
        console.log(
          `Notification opened with an action identifier: ${action.identifier} and response text: ${action.text}`
        )
        completion()
      }
    )

    Notifications.events().registerNotificationReceivedBackground(
      (
        notification: Notification,
        completion: (response: NotificationCompletion) => void
      ) => {
        console.log('Notification Received - Background', notification.payload)

        // Calling completion on iOS with `alert: true` will present the native iOS inApp notification.
        completion({ alert: true, sound: true, badge: false })
      }
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return null
}

export default NotificationHandler

The above is basically straight from the docs, no changes whatsoever.

The NotificationHandler is rendered within the NavigationContainer which has a StackNavigator as the parent screen and a nested TabNavigator within one of the stack screens.

import {
  NavigationContainer,
  createNavigationContainerRef,
} from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import React, { useEffect, useState } from 'react'
import { Alert, LogBox, Platform, StatusBar } from 'react-native'

import InitialChecksHandler from 'screens/Login/components/InitialChecksHandler'
import Maintenance from 'screens/Maintenance/Maintenance'
import Splash from 'screens/Splash/Splash'

import type { InitialChecksResult, RootStackParamList } from 'utils/types'

import { AUTH_STATUS_MAP } from 'app/constant'

import { useAuthContext } from '../context/AuthContext'
import AuthStackNavigator from '../routes/Auth/Auth'
import MainTabNavigator from '../routes/Main/Main'
import NotificationHandler from './NotificationHandler'

const Stack = createNativeStackNavigator<RootStackParamList>()

LogBox.ignoreLogs([
  'Non-serializable values were found in the navigation state',
])

export const navigationRef = createNavigationContainerRef<RootStackParamList>()

// Need to disable type check here
// (Please check the declaration of navigationRef.navigate to understand why)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function navigate(name: any, params: any) {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params)
  }
}

function RootRoutes() {
  const { authStatus } = useAuthContext()

  return (
    <>
      <StatusBar backgroundColor="#0090DA" barStyle="light-content" />
      <Stack.Navigator
        initialRouteName="Auth"
        screenOptions={{ headerShown: false }}
      >
        {authStatus === AUTH_STATUS_MAP.LOGGED_IN ? (
          <Stack.Screen name="Main" component={MainTabNavigator} />
        ) : (
          <Stack.Screen name="Auth" component={AuthStackNavigator} />
        )}
        <Stack.Screen
          name="Maintenance"
          component={Maintenance}
          options={{ headerShown: false }}
        />
      </Stack.Navigator>
    </>
  )
}

function RootNavigator(): React.JSX.Element {
  const [initialCheckResults, setInitialCheckResults] =
    useState<InitialChecksResult | null>(null)

  if (!initialCheckResults) {
    return <Splash setResults={setInitialCheckResults} />
  }

  return (
    <NavigationContainer ref={navigationRef}>
      <InitialChecksHandler
        setInitialCheckResults={setInitialCheckResults}
        {...initialCheckResults}
      />
      <NotificationHandler />
      <RootRoutes />
    </NavigationContainer>
  )
}

export default RootNavigator

Please let me know if there is need for additional information. Thank you and any help is appreciated since I have been banging my head on this for over a week now.

Different PRF output when using platform or cross-platform authentication attachement

I am using the prf extension for passkeys that is available since ios 18 and macos15. I am using a fixed, hardcoded prf input when creating or geting the credentials. After creating a passkey, i try to get the credentials and retrieve the prf output, which works great, but i am getting different prf outputs for the same credential and same prf input used in the following scenarios:

Logging in directly (platform authenticator) on my macbook/iphone/ipad i get “prf output X” consistently for the 3 devices

When i use my iphone/ipad to scan the qr code on my macbook (cross-platform authenticator) i get “prf output Y” consistently with both my ipad and iphone.

Is this intended? Is there a way to get deterministic prf output for both platform and cross-platform auth attachements while using the same credential and prf input?

Why does event.stopPropagation() not prevent a parent directive’s @HostListener from receiving click events in Angular?

I’m building an Angular application and have a custom button component that uses a directive to throttle click events. Even when the button is disabled, clicking it still triggers the function associated with the click event in the parent directive.

Here’s a simplified version of my setup:

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-button',
  template: `
    <button [disabled]="isDisabled" (click)="onClick($event)">
      <ng-content></ng-content>
    </button>
  `,
})
export class ButtonComponent {
  @Input() isDisabled = false;
  @Output() click = new EventEmitter<Event>();

  onClick(event: Event) {
    if (this.isDisabled) {
      event.stopPropagation();
    } else {
      this.click.emit(event);
    }
  }
}
import { Directive, Output, EventEmitter, HostListener } from '@angular/core';

@Directive({
  selector: '[throttledClick]',
})
export class ThrottledClickDirective {
  @Output() throttledClick = new EventEmitter<Event>();
  private isThrottled = false;

  @HostListener('click', ['$event'])
  handleClick(event: Event) {
    if (!this.isThrottled) {
      this.isThrottled = true;
      this.throttledClick.emit(event);
      setTimeout(() => this.isThrottled = false, 200);
    }
  }
}
<app-button
  throttledClick
  [isDisabled]="isButtonDisabled"
  (throttledClick)="onThrottledClick()">
  Click Me
</app-button>

When isButtonDisabled is true, the button is disabled, but clicking it still triggers the onThrottledClick() method. I expected that event.stopPropagation() in the button component would prevent the click event from reaching the directive, but it doesn’t.

Getting undefined (reading ‘toString’) in ng-apexcharts

i was using ng-apexcharts(^1.9.0) & apexcharts(^3.45.1). and it was working fine & deployed in production. After few months i create a branch from master(deployed in prod) but i am getting below console error hovering on legend. Same code same version no changes, still getting issue. can someone please help me with this ??
(https://i.sstatic.net/xVF5Slji.png)](https://i.sstatic.net/xVF5Slji.png)

I have tried with different version of ng-apexcharts and apexcharts, but getting same error.

Enhancing JavaScript Enum Implementation with Autocomplete Support

Problem:

I am unable to achieve full autocomplete support for custom enum implementation in vanilla JavaScript

/**
 * This doesn't work
 * @template T
 * @param {T} arr
 * @returns {Enum<T>}
 */
export function _enum(...arr) {/* ... */}

const a = _enum({ foo: 0, bar: 1, baz: 2 }); 
a. // Autocomplete works
const b = _enum("foo", "bar", "baz"); 
b. // Autocomplete shows nothing

I believe the issue lies in the fact that ...arr is not an array defined with as const, and I’m unsure of how to resolve this.

Progress:

I have developed a vanilla JavaScript enum implementation that supports both an object and multiple strings as parameters:

export function _enum(...arr) {
    return Object.freeze(
        Object.fromEntries(
            arr.length === 1 && typeof arr[0] === "object"
                ? Object.entries(arr[0]).flatMap(([a, b]) => [
                        [a, b],
                        [b, a],
                  ])
                : arr
                        .map(a => [a, enumItem()])
                        .flatMap(([a, b]) => [
                            [a, b],
                            [b, a],
                        ])
        )
    )
}

In addition, I have created a custom enum type in helpers.d.ts:

type Enum<T> = T extends readonly string[]
  ? { [key in T[number]]: number }
  : T[number];

I have tested the Enum type as follows:

let a = ["foo", "bar", "baz"] as const; // JavaScript doesn't have 'as const'
type A = Enum<typeof a>;

let b = [{ foo: 0, bar: 1, baz: 2 }]; // representation of ...arr parameter
type B = Enum<typeof b>;

// Both A and B have the type
// {
//     foo: number;
//     bar: number;
//     baz: number;
// }
// and autocomplete works in both cases

exact source: github

Is there a way to train ai on my template

I am sick of going through multiple (html, js, css) about 140 files in a template that I have downloaded. Can I found a way to train Ai and ask it what ever I need and it just provide me with the exact code.

I asked ChatGPT, before I subscribe, and it replies with it can’t hold multiple files.

Why Vue3 ref.value can’t access private properties declared with #, but private can?

I have two classes declared.Goods and User

class Goods {
    #price: number
    #quantity: number

    constructor(price: number, quantity: number) {
       this.#price = price;
       this.#quantity = quantity;
    }

    get totalPrice() {
       return this.#price * this.#quantity;
    }

    totalPriceFunc() {
       return this.#price * this.#quantity;
    }
}

class User {
    private id: number
    private name: string;

    constructor(id: number, name: string) {
       this.id = id;
       this.name = name;
    }

    get info() {
       return `id: ${this.id}, name: ${this.name}`;
    }

    infoFunc() {
       return `id: ${this.id}, name: ${this.name}`;
    }
}

init Goods and User and use vue3 ref;

const g = new Goods(10, 100);
console.log('>>>>>>>g ref before: ', g.totalPrice, g.totalPriceGetFunc());
// >>>>>>>g ref before:  1000 1000

const gRef = ref<Goods>(g);
console.log('>>>>>>>g ref after: ', g.totalPrice, g.totalPriceGetFunc());
// >>>>>>>g ref after:  1000 1000

try {
    console.log('gRef totalPrice: ', gRef.value.totalPrice);
    console.log('gRef totalPriceGetFunc: ', gRef.value.totalPriceGetFunc());
} catch (e) {
    console.error(e);
        // TypeError: Cannot read private member #price from an object whose class did not declare it
        // at get totalPrice (HelloWorld.vue:19:15)
        // at Reflect.get (<anonymous>)
        // at MutableReactiveHandler.get (reactivity.esm-bundler.js:928:25)
        // at setup (HelloWorld.vue:50:46)
        // at callWithErrorHandling (runtime-core.esm-bundler.js:199:19)
        // at setupStatefulComponent (runtime-core.esm-bundler.js:7847:25)
        // at setupComponent (runtime-core.esm-bundler.js:7808:36)
        // at mountComponent (runtime-core.esm-bundler.js:5161:7)
        // at processComponent (runtime-core.esm-bundler.js:5127:9)
       //  at patch (runtime-core.esm-bundler.js:4645:11)
}
-------------------------------------------------------------------

const u = ref<User>(new User(1, 'Daniel'));

console.log('u info: ', u.value.info);
// u info:  id: 1, name: Daniel

console.log('u infoFunc: ', u.value.infoFunc());
// u infoFunc:  id: 1, name: Daniel

Why is it that the #price property of Goods cannot be used when using ref to declare responsive state, but private id private name can be used normally?

Button to download file and redirect to new page

How do I enable my button to download and redirect to a new page? I have tried many code combination but it just downloads and does not redirect

<div class="banner">
    <h3>Download your file:<br> {{ filename }}</h3>
    <div>
        {% csrf_token %}
        <form action="{% url 'download_pdf' %}" enctype="multipart/form-data" method="post">
            {% csrf_token %}
            <button onclick="openTab()" class="btn btn-primary w-20" id="myBtn" tabindex="4">Download PDF
            </button>
        </form>
    </div>
</div>
<script>
function openTab() {
window.open('home');
}
</script>

How to delete duplicate object from array Angular 8

i have below array of object from API response.i want to push only those object whose id is not repeating and totalTime is 0

for ex – in below JSON, object with id = 4 is repeating twice so i dont want to include
this object into new array, here id = 1 and id = 3 have totaltime is 0, than i want to push this one .

Below is my JSON

const response = [
  {  
      "id": "1",
      "oeeCalculations": {
          "others": {
              "totalTime": 0
          }
      }
  },
  {
      "id": "2",
      "oeeCalculations": {
          "others": {
              "totalTime": 744
          }
      }
  },
  {
      "id": "3",
      "oeeCalculations": {
          "others": {
              "totalTime": 0
          }
      }
  },
  {
      "id": "4",
      "oeeCalculations": {
          "others": {
              "totalTime": 0
          }
      }
  },
  {
      "id": "4",
      "oeeCalculations": {
          "others": {
              "totalTime": 744
          }
      }
  }
];

Expected output –

const newResponse = [
    {  
        "id": "1",
        "oeeCalculations": {
            "others": {
                "totalTime": 0
            }
        }
    },
    {
        "id": "3",
        "oeeCalculations": {
            "others": {
                "totalTime": 0
            }
        }
    }
];

I tried below code, but its returning unique lines only..

 const values = Object.values(
      response.reduce((a, b) => {
        if (!a[b.id]) a[b.id] = b 
          return a
       }, {})
    )

Darkening an image when clicked is requiring an initial click on that image, and I don’t know why

I’m trying to make an item tracker for a game as a webapp. I wanted to have the icon of each item displayed in a grid, and when you click on the image it darkens to indicate that you’ve gotten it. So far I’ve only figured out how to affect the opacity of the images, but works well enough for now. Though when the opacity starts at 1.0, it requires a second click to activate, but only for the first time. After that it works as intended, toggling on click. If I set the initial opacity to 0.5, it works on the first click.

I made a table to place the images in a grid (added 8 for the time being) and gave each one a unique id, and the class “Loot” like so:

function lootDarken(x) {
  image = document.getElementById(x);
  if (image.style.opacity === "1") {
    image.style.opacity = "0.5";
  } else {
    image.style.opacity = "1";
  }
}
<table>
  <tr>
    <td><img onClick="lootDarken('Loot1')" id="Loot1" class="Loot" src="https://picsum.photos/200/300"></td>
    <td><img onClick="lootDarken('Loot2')" id="Loot2" class="Loot" src="https://picsum.photos/200/300"></td>
    <td><img onClick="lootDarken('Loot3')" id="Loot3" class="Loot" src="https://picsum.photos/200/300"></td>
    <td><img onClick="lootDarken('Loot4')" id="Loot4" class="Loot" src="https://picsum.photos/200/300"></td>
    <td><img onClick="lootDarken('Loot5')" id="Loot5" class="Loot" src="https://picsum.photos/200/300"></td>
    <td><img onClick="lootDarken('Loot6')" id="Loot6" class="Loot" src="https://picsum.photos/200/300"></td>
    <td><img onClick="lootDarken('Loot7')" id="Loot7" class="Loot" src="https://picsum.photos/200/300"></td>
    <td><img onClick="lootDarken('Loot8')" id="Loot8" class="Loot" src="https://picsum.photos/200/300"></td>
  </tr>
</table>

Also, if there’s a cleaner/easier way to place these images in a grid, please share. I have to go through hundreds of these.

I thought maybe it was because the opacity wasn’t officially set, and that clicking it the first only set the opacity to 1 since technically, the opacity wasn’t 1. So I added the class “Loot” in order to set the opacity on startup. That didn’t work, so I tried setting the initial opacity to 0.5 just to see what would happen and that worked wonderfully.

I also tried reversing the function, making it check if the opacity is not 1:

function lootDarken(x) {
    
    image = document.getElementById(x);
    if (image.style.opacity != "1") {
        image.style.opacity = "1";
    } else {
        image.style.opacity = "0.5";
    }
    
}

But that led to the same result. I don’t even know what is happening that’s causing this weird interaction, so I came here hoping for an explanation… and maybe tips on how to make it less repetitive.

Embedded Iframe content is not loading in IOS devices – safari

I have iframe content loading external source. my code is like this

<iframe title="xyz" allowtransparency = "true" marginheight="0"
  marginwidth ="0" class="investisIframe"
  src="https://irs.tools.investis.com/Clients/uk/bt/SharePriceLookup/Default.html?culture=en-GB"
  frameborder="0" id="001" width="100%" height="500">
</iframe>

Above code works fine in android and windows devices. But not working in ios devices. Please help me to resolve this issue

  1. I have tried clearing the cache still the same issue.
  2. By adding timestamp at the end of url then also same issue.

Change Backend URL based on Deployment Space in React UI – MTA

We are using React for our UI project and backend is in Spring Boot.

We are trying to deploy our application in canary landscape in 4 different cf spaces, say, dev, test, e2e, and demo.

We are using MTA based deployment to deploy both our UI and backend app.

We want to generate a common Build for UI but want to change the url based on deployment space, for example:

dev space: dev-backend-app.domain.com

test space: test-backend-app.domain.com

e2e space: e2e-backend-app.domain.com

Deployment will be per space but we want to promote same build everywhere.

To achieve this, we used following commands using dotenv dependency :

 "start:dev":"env-cmd -f .env.dev react-scripts start",
    "start:test":"env-cmd -f .env.test react-scripts start",

in .env.dev or .env.test, we set backend url which we can read from process.env

REACT_APP_BACKEND_URL=dev-backend-app.domain.com

Now, im able to run my application locally by ; npm run start:dev and it is successful loading env and working.
However, I want to achieve this via mta yaml file. To achieve this i modified mta.yaml file module to :

- name: ui-app
  type: nodejs
  path: client/customer_app/build/
  build-parameters:
    builder: custom
    commands:
      - npm install
  parameters:
    memory: 2048M
    disk-quota: 2048M
    instances: 1
    buildpack: https://github.com/cloudfoundry/staticfile-buildpack.git
    routes:
      - route: ${target}-ui-app.${domain}
    command: npm run start:dev

However, on deployment fails with :

[2024-09-26T04:00:30.909161] bash: line 1: npm: command not found (STDERR, APP/PROC/WEB)#

Hence, looking for solution to detect/change backend url at runtime and not at compile time ( so we create one binary).

How to generate dynamic test cases using jest

Fetch live schools from db then generate and execute test cases for each school.
I have tried with beforeAll hook data fetched perfectly but was not able to generate dynamic test cases.

let token = ''
let liveSchools: any[] = []
const seconds = 1000



describe('GB Live Establishment API Tests', () => {
  beforeAll(async () => {

    const response = await server.post('/v1/login').send(credentials)
    token = response.body.data.access_token

    // Fetch live schools
    liveSchools = await fetchLiveSchools()
  })

  // Step 2: Test to ensure live schools are fetched successfully
  it('should fetch live schools', () => {
    expect(liveSchools.length).toBeGreaterThan(0)
  })

  
  liveSchools.forEach((school, index) => {
    it(
      `should return basic details of establishment ${school.slug} (row ${index + 1})`,
      async () => {
        const result = await server
          .get(`/v1/establishment/${school.slug}`)
          .auth(token, { type: 'bearer' })

        // Assertions for the dynamic test
        expect(result.body.data.slug).toBe(school.slug)
        expect(result.statusCode).toBe(200)
      }
    )
  })
})