Undefined user object when trying to define JWT token with NextAuth

I have the following code that connects to my database to authenticate the connection using NextAuth, in which case it returns an object (usr) that contains the id of the user logging in.

import NextAuth from 'next-auth'
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from 'bcryptjs'

export default NextAuth({
    session: {
        jwt: true
    },
    providers: [
        CredentialsProvider({
            name: 'data',
            
            credentials: {
                username: { label: "Username", type: "text" },
                password: { label: "Senha", type: "password" }
            },
            
            async authorize(credentials) {
                const usr = await db('...')
                    .select('...', '...', '...')
                    .where({ usr_login : credentials.username })
                    .first();

                if (!usr) { // Database connection failed or user doesn't exist
                    return null
                } else {
                    // Verifying the password
                    if (bcrypt.compareSync(credentials.password, usr.password)) {
                        const ret = {
                            id: usr.usr_login,
                        }
                        console.debug('Authorize : ', ret);
                        return ret;
                    } else {
                        return null;
                    }
                }
            }
        })
    ],
    callbacks: {
        jwt: async (token, user, account, profile, isNewUser) => {
            console.debug('JWT : ', token, user, account, profile, isNewUser);
            if(user) {
                token.user = user;
            }
            console.debug('JWT : ', token, user, account, profile, isNewUser);
            return Promise.resolve(token);
        },
        session: async (session, user) => {
            if (session && user.user) {
              session.userId = user.user.id;
              return Promise.resolve(session);
            } else {
              // Handle the case where session or user is undefined
              console.error('Session or user is undefined', { session, user });
              return Promise.resolve(session);
            }
          },
    },
    pages: {
        signIn: '/login'
    }
})

The output from console.debug('Authorize : ', ret) shows that the object is indeed created and contains an ID, which means the database connection isn’t the issue. When it enters the JWT callback function, the first console.debug('JWT : ', token, user, account, profile, isNewUser); shows that it received the correct information, but when it tries to assign it on token.user = user, it seems to be undefined and the output I get from the logs is:

JWT :  {
  token: {
    name: undefined,
    email: undefined,
    picture: undefined,
    sub: 'john'
  },
  user: { id: 'john' },
  account: {
    providerAccountId: 'john',
    type: 'credentials',
    provider: 'credentials'
  },
  isNewUser: false,
  trigger: 'signIn'
} undefined undefined undefined undefined
JWT :  {
  token: {
    name: undefined,
    email: undefined,
    picture: undefined,
    sub: 'john'
  },
  user: undefined,
  account: {
    providerAccountId: 'john',
    type: 'credentials',
    provider: 'credentials'
  },
  isNewUser: false,
  trigger: 'signIn'
} undefined undefined undefined undefined

Also, when I try to debug the user alone, it also returns undefined. I thought it might be an issue with the scope of the variable, but I couldn’t see where it might be from since it’s the only user variable defined. Another possibility would be a race condition, but I don’t see how that would crash it, since it was actually defined and should be entering the if(user) {} clause, but apparently it doesn’t. I don’t know why just before using the variable it is defined, but when I try to assign it it vanishes.

I appreciate any help you can provide. Thanks 🙂

CSS transition applied through JavaScript problem

My button transition to the second one is good and working but I want the background to be included in the transition, for example, In the first page I have blue background, A description box, and a “Get Started” button. I want the background color to change into red with the same transition with my button and description box then vice versa when I get to the second page. Also, my “home” button in the second page is not working, I mean the transition isn’t applied when I click it.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Home</title>
  <link rel="stylesheet" href="home.css">
</head>
<body>
  <div class="description">Yusisista Minimap is a web-based application that provides students and visitors with 
    easy access to navigate the UCC Congress campus, 
    allowing them to locate desired facilities, offices,
    and rooms with ease and efficiency.</div>

  <button id="getStartedButton" class="slide">Get started</button>

  <div class="about">HIIIIIIIIIIIIIIIII</div>
  <button id="homeButton" class="homebut">Home</button>

  <script src="home.js"></script> <!-- Include JavaScript file -->
</body>
</html>
body {
    background-color: blue;
  }
  
  .description {
    position: relative;
    margin: 100px auto 50px;
    /* shorthand for margin */
    width: 500px;
    height: 225px;
    border-radius: 30px;
    padding: 75px 25px;
    /* shorthand for padding */
    background: linear-gradient(
      90deg,
      rgba(10, 135, 0, 1) 0%,
      rgba(217, 98, 0, 1) 45%,
      rgba(25, 179, 0, 1) 92%
    );
    color: aliceblue;
    font-size: 20px;
    font-family: Arial, Helvetica, sans-serif;
    text-align: justify;
    line-height: 25px;
    /* Transition for description opacity */
  }
  
  .hide-description {
    animation: myAnim 2s ease-in-out 1s 1 normal forwards;
  }
  
  @keyframes myAnim {
    0% {
      transform: translateY(0%);
      opacity: 1;
    }
    95% {
      transform: translateY(-190vh);
      opacity: 1;
    }
    100% {
      transform: translateY(-200vh);
      opacity: 0;
    }
  }
  
  .slide {
    position: relative;
    margin-left: 100vh;
    /* shorthand for margin */
    width: 150px;
    height: 100px;
    border-radius: 30px;
    background: linear-gradient(
      90deg,
      rgba(10, 135, 0, 1) 0%,
      rgba(217, 98, 0, 1) 45%,
      rgba(25, 179, 0, 1) 92%
    );
    color: aliceblue;
    font-size: 20px;
    font-family: Arial, Helvetica, sans-serif;
    text-align: center;
    line-height: 25px;
    /* Add your button styling here */
  }
  
  .hide-button {
    animation: myAnim 2s ease-in-out 1s 1 normal forwards;
  }
  
  .about {
    opacity: 0;
    position: fixed;
    top: 45%;
    left: 33.3%;
    transform: translate(50%, 200vh);
    margin: 0 auto;
    width: 500px;
    height: 225px;
    border-radius: 30px;
    padding: 75px 25px;
    /* shorthand for padding */
    background: linear-gradient(
      90deg,
      rgba(10, 135, 0, 1) 0%,
      rgba(217, 98, 0, 1) 45%,
      rgba(25, 179, 0, 1) 92%
    );
    color: aliceblue;
    font-size: 20px;
    font-family: Arial, Helvetica, sans-serif;
    text-align: justify;
    line-height: 25px;
    transition: all 2s ease-in-out;
  }
  
  
  .show-about {
    animation: myAnim1 2s ease-in-out 0s 1 normal both;  }

    @keyframes myAnim1 {
        0% {
            opacity: 0;
            transform: translateY(50%);
        }
    
        100% {
            opacity: 1;
            transform: translateY(-50%);
        }
    }
    

    .homebut {
      opacity: 0;
      position: fixed;
      margin-top: 85vh;
      margin-left: 46%;
      /* shorthand for margin */
      width: 150px;
      height: 100px;
      border-radius: 30px;
      background: linear-gradient(
        90deg,
        rgba(10, 135, 0, 1) 0%,
        rgba(217, 98, 0, 1) 45%,
        rgba(25, 179, 0, 1) 92%
      );
      color: aliceblue;
      font-size: 20px;
      font-family: Arial, Helvetica, sans-serif;
      text-align: center;
      line-height: 25px;
      /* Add your button styling here */
    }

    .show-homebut {
      animation: myAnim2 2s ease-in-out 0s 1 normal both;  }
  
      @keyframes myAnim2 {
          0% {
              opacity: 0;
              transform: translateY(50%);
          }

          50% {
            opacity: 0;
            transform: translateY(0%);
        }
      
          100% {
              opacity: 1;
              transform: translateY(-50%);
          }
      }

      .show-slide {
        animation: myAnim3 2s ease-in-out 0s 1 normal both;  }
    
        @keyframes myAnim3 {
            0% {
                opacity: 0;
                transform: translateY(-50%);
            }
  
            50% {
              opacity: 0;
              transform: translateY(0%);
          }
        
            100% {
                opacity: 1;
                transform: translateY(50%);
            }
        }
     

        .show-description {
          animation: myAnim4 2s ease-in-out 0s 1 normal both;  }
      
          @keyframes myAnim4 {
              0% {
                  opacity: 0;
                  transform: translateY(-50%);
              }
          
              100% {
                  opacity: 1;
                  transform: translateY(50%);
              }
          }
const getStartedButton = document.getElementById("getStartedButton");
const homeButton = document.getElementById("homeButton");
const desc = document.querySelector(".description");
const slideButton = document.querySelector(".slide");

// Event listener for the get started button
getStartedButton.addEventListener("click", function() {
  desc.classList.add("hide-description"); // Add class to hide description
  slideButton.classList.add("hide-button"); // Add class to hide button
  setTimeout(function() {
    document.querySelector(".about").classList.add("show-about"); // Add class to show 'about' section after transition ends
    document.querySelector(".homebut").classList.add("show-homebut");
    desc.style.display = "none";
    slideButton.style.display = "none";
  }, 2000); // Adjust this time to match the duration of the transition in CSS
});

// Event listener for the home button
homeButton.addEventListener("click", function() {
  document.querySelector(".about").classList.remove("show-about"); // Remove class to hide 'about' section
  document.querySelector(".homebut").classList.remove("show-homebut");
  setTimeout(function() {
    desc.classList.remove("hide-description"); // Remove class to show description
    slideButton.classList.remove("hide-button"); // Remove class to show button
    desc.style.display = "block";
    slideButton.style.display = "block";
  }, 2000); // Adjust this time to match the duration of the transition in CSS
});

I want everything to slide up and down and please help me fix my code. Thanks in advance

React CDN Pivottable Uncaught ReferenceError

I am trying to use CDN to do a simple pivot table using the react-pivottable library.

Here is the HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React PivotTable Example</title>

    <!-- React and ReactDOM CDN links -->
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

    <!-- Babel CDN -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <!--react-pivottable-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/PlotlyRenderers.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/pivottable.min.css" rel="stylesheet">

</head>
<body>
<div id="root"></div>

<!-- Your React app script -->
<script src="JS/report/ReactPivotTest.js" type="text/babel"></script>
</body>
</html>

and here is the react code:

const e = React.createElement;

const data = [['attribute', 'attribute2'], ['value1', 'value2']];

class ReactPivotTest extends React.Component {
    constructor(props) {
        super(props);
        this.state = props;
    }
    
    render() {
        return (
            <PivotTableUI
            data={data}
            onChange={s => this.setState(s)}
            {...this.state}
            />
            );
        }
    }
    
    const domContainer = document.querySelector('#root');
    const root = ReactDOM.createRoot(domContainer);
    root.render(e(ReactPivotTest));

When the page loads up I get:

Uncaught ReferenceError: PivotTableUI is not defined

The example is from the CDN site:

text

Android app crashing with error: [PropertyFetcher]: TimeoutException getting properties for device

I am trying to run a react native based application in debugging mode. But it is throwing TimeoutException.

Development Environment:
using Android OS XOS v12.0.0 (OS12.0-S-P156-221214)

java --version 
openjdk 11.0.22 2024-01-16
OpenJDK Runtime Environment (build 11.0.22+7-post-Ubuntu-0ubuntu222.04.1)
OpenJDK 64-Bit Server VM (build 11.0.22+7-post-Ubuntu-0ubuntu222.04.1, mixed mode, sharing)

adb --version
Android Debug Bridge version 1.0.41
Version 34.0.1-9680074

react-native: 0.72.4

Execution log:

> Task :app:installDebug
[PropertyFetcher]: TimeoutException getting properties for device 0965731355092050
java.lang.Throwable: TimeoutException getting properties for device 0965731355092050
 at com.android.ddmlib.PropertyFetcher.handleException(PropertyFetcher.java:248)
 at com.android.ddmlib.PropertyFetcher$1.run(PropertyFetcher.java:211)
Caused by: com.android.ddmlib.TimeoutException
 at com.android.ddmlib.AdbHelper.read(AdbHelper.java:1201)
 at com.android.ddmlib.AdbHelper.readAdbResponse(AdbHelper.java:353)
 at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:650)
 at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:511)
 at com.android.ddmlib.internal.DeviceImpl.executeShellCommand(DeviceImpl.java:719)
 at com.android.ddmlib.PropertyFetcher$1.run(PropertyFetcher.java:207)

[PropertyFetcher]: TimeoutException getting properties for device 0965731355092050
java.lang.Throwable: TimeoutException getting properties for device 0965731355092050
 at com.android.ddmlib.PropertyFetcher.handleException(PropertyFetcher.java:248)
 at com.android.ddmlib.PropertyFetcher$1.run(PropertyFetcher.java:211)
Caused by: com.android.ddmlib.TimeoutException
 at com.android.ddmlib.AdbHelper.read(AdbHelper.java:1201)
 at com.android.ddmlib.AdbHelper.readAdbResponse(AdbHelper.java:353)
 at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:650)
 at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:511)
 at com.android.ddmlib.internal.DeviceImpl.executeShellCommand(DeviceImpl.java:719)
 at com.android.ddmlib.PropertyFetcher$1.run(PropertyFetcher.java:207)

Installing APK 'app-debug.apk' on 'Pixel_XL_API_31(AVD) - 12' for :app:debug
[PropertyFetcher]: TimeoutException getting properties for device 0965731355092050
java.lang.Throwable: TimeoutException getting properties for device 0965731355092050
 at com.android.ddmlib.PropertyFetcher.handleException(PropertyFetcher.java:248)
 at com.android.ddmlib.PropertyFetcher$1.run(PropertyFetcher.java:211)
Caused by: com.android.ddmlib.TimeoutException
 at com.android.ddmlib.AdbHelper.read(AdbHelper.java:1201)
 at com.android.ddmlib.AdbHelper.readAdbResponse(AdbHelper.java:353)
 at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:650)
 at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:511)
 at com.android.ddmlib.internal.DeviceImpl.executeShellCommand(DeviceImpl.java:719)
 at com.android.ddmlib.PropertyFetcher$1.run(PropertyFetcher.java:207)

Skipping device '0965731355092050' for ':app:debug': Unknown API Level

In Emulator every thing is working fine. With some other devices it is also working fine. Not able to even install the app.

I tried:

  1. Disabling adb authorization timeout
  2. Tried revoking USB debugging authorization and then running it.

How to use datatable, in table that append by jquery?

Im still new in jquery, i created a table in jquery and after the table was appended I used datatable, but the datatable had an error I don’t know what caused the error.

Here is my code:

HTML:

    <div class="card-body pt-5">
            <form action="" method="POST" id="approval_form" enctype="multipart/form-data">
                @method('POST')
                <div class="table-responsive">
                <table id="approval_eseverance" class="table table-hover table-row-bordered table-striped border gy-7 gs-7">
                    <thead>
                        <tr class="fw-semibold fs-6 text-gray-800 border-bottom-2 border-gray-200">
                             <th class="min-w-100px" >a</th>
                                <th class="min-w-150px">b</th>
                                <th class="min-w-200px">c</th>
                                <th class="min-w-150px ">d</th>
                                <th class=" min-w-150px">e</th>
                                <th>f</th>
                        </tr>
                    </thead>
                    <tbody>(the tr td in tbody)
</tbody>
                    </table>
                </div>
                </form>

JS:

       $(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
     new DataTable('#approval_eseverance', {
        "dom": '<"top"lf>rt<"bottom"ip>',
        fixedColumns: {
            left: 3,
        },
        scrollX: true,
        layout: {
            bottomEnd: {
                paging: {
                    boundaryNumbers: false
                }
            }
        }
    });
 $(document).on('click', '.approval_detail', function (e) {
        e.preventDefault();
        // alert("test");
        var request_id = $(this).data('request-id');
$.ajax({
            url: "{{ route('detail') }}",
            type: 'POST',
            data: {
                request_id: request_id,
            },
            success: function (res) {
                $('#approval_form').empty();
 var table = $('#approval_form');
var table_detail = "";
table_detail +=
                        '<div id="create-form-pkwt" class="create-form table-responsive" autocomplete="off">';
                    table_detail +=
                        '<table class="table tb_create table-bordered" id="create-pkwt">';
                    table_detail += '<thead>';
                    table_detail +=
                        '<tr class="fw-bold fs-6 text-gray-800"><th style="white-space:nowrap" class="text-center" rowspan="3">No</th></tr>';
table_detail +=
                        '<th style="white-space:nowrap" class="text-center" rowspan="3">Number</th>';
                    table_detail +=
                        '<th style="white-space:nowrap" class="text-center" rowspan="3">Name</th>';
 table_detail += '</thead>';
  table_detail += ' <tbody>';
for (var i = 0; i < res.length; i++) {
                        table_detail +=
                            '<tr><td class="text-center" style="white-space:nowrap">'+res[i].sub+'</td>';
                        table_detail +=
                            '<td class="text-center" style="white-space:nowrap"><input type="hidden" id="pernr_create-pkwt' +
                            res[i].sub + '" name="pernr[]" value="' + res[i].number+
                            '">' + res[i].number+ '</td>';
                        table_detail +=
                            '<td class="text-center headcol3" style="white-space:nowrap"><input type="hidden" id="ename_create-pkwt' +
                            res[i].sub + '" name="ename[' + res[i].number+
                            ']" value="' + res[i].name+ '">' + res[i].ename + '</td></tr>';
 table_detail += '</tbody>';
                    table_detail += '</table></div>';
 table_detail += '</div>';
                    table.append(table_detail);
                        $("#create-pkwt").DataTable({
                            scrollY:        "300px",
                            scrollX:        true,
                            scrollCollapse: true,
                            fixedColumns:   {
                                left: 2
                            }
                        });

In js i empty the table in html and append the new table, the table append and show well good but the datatable is error.
i got this error

Error

Can anyone help me

How to use runtime.sendMessage from background to a content script?

I’m trying to use browser.runtime.sendMessage from background.js to a content script, but I keep having the error:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist. <anonymous> moz-extension://e188c1d0-70e8-4b82-8e62-287a34ac151c/background.js:1

Here’s background.js:

browser.runtime.sendMessage({hi:'hi'})

Here is content_scripts/sometest.js:

browser.runtime.onMessage(message => {
  console.log(message)
});

I even have a button in the pop up that should be sending a message whenever I click it. But it stills produces the same error, even if I click outside about:debugging or a mozilla page (which theoretically you can’t inject content scripts). Here is choose_beast.js:

const storeone = document.querySelector("#storeone");

console.log(storeone) //this gets logged

storeone.addEventListener("click", () => {
  console.log("clicked"); // also this gets logged in the console!
  browser.runtime.sendMessage({action:"send_oi"}) //this produces the same error
});

And finally, here is my manifest.json

{

  "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
  "manifest_version": 2,
  "name": "Beastify",
  "version": "1.0",
  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
  "icons": {
    "48": "icons/beasts-48.png"
  },

  "permissions": [
    "activeTab",
    "webRequest",
    "webRequestBlocking"
  ],

  "content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": ["content_scripts/sometest.js"]
    }
  ],

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },

  "browser_action": {
    "default_icon": "icons/beasts-32.png",
    "theme_icons": [{
        "light": "icons/beasts-32-light.png",
        "dark": "icons/beasts-32.png",
        "size": 32
    }],
    "default_title": "Beastify",
    "default_popup": "popup/choose_beast.html"
  },

  "web_accessible_resources": [
    "beasts/*.jpg",
    "redirect.html"
  ]

}

How to use conditional app.use() in nestJS backend?

This is how I’m trying to add helmet to my nestJS application. Additionally I need to add graphqlUploadExpress
How do I correctly use the usesUpload condition to use helm or helm + upload?

import { NestFactory } from '@nestjs/core'
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import helmet from 'helmet'

const upload = graphqlUploadExpress()

export const main = async (
  AppModule: unknown,
  usesUpload = false
) => {
  const app = await NestFactory.create(AppModule, options)
  app.use(usesUpload ? helm : helm, upload) // <-- I think, this is not correct
  await app.listen(3000)
}

Turn not awaited unhandled erroneous promise into warning @ processTicksAndRejections (created by throw error in “then”)

there is no await on top-level allowed and my expectation was that the error thrown below would be logged as warning only but it turns out to be a blocker for completion, i.e. upon statement await fsProm.stat the processing basically stops. I would not understand why?

const fsProm = require('fs').promises;

async function codeWithUnhandledPromise(){
    const notAwaited = Promise.resolve().then(function(){
        throw new Error('Irrelevant');
    });
    await fsProm.stat( __filename );
    console.log( 'Not reached' );
}
async function main(){
    try {
      await codeWithUnhandledPromise();
    } catch (error) {
      console.log( 'Not reached' );
    } finally {
      console.log( 'Not Reached' );
    }
}

main().then(undefined,function(){ 
    console.log( 'Not Reached' );
    return;
});
console.log( 'done' );

Bookmarklet is replacing the entire body with the text from new style definition

So I’m trying to make a couple quick bookmarklets to help me with using Jira:

  1. Remove the sidebar
  2. Enlarge the text editor area

The following bits of code work fine in the dev console:

document.getElementsByClassName('jira-editor-container')[0].style.height='1000px';
document.getElementById('viewissuesidebar').style.display='none';

But when I alter them to,

javascript:document.getElementsByClassName('jira-editor-container')[0].style.height='1000px';
javascript:document.getElementById('viewissuesidebar').style.display='none';

And use them as bookmarklets, the entire page body is replaced with the style values (eg. 1000px or none).

Any help would be greatly appreciated. I don’t understand the disconnect between the dev console working and the bookmarklet not working.

How to create for selecting years and months, fetching payroll data based on the selections, and dynamically generating pay slips for the chosen month

import AppSelect from '@/components/form-fields/AppSelect';
import {
  Box,
  Button,
  CircularProgress,
  Divider,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Stack,
  Typography,
  useTheme,
} from '@mui/material';
import React, { useEffect } from 'react';
import { BlobProvider, PDFDownloadLink } from '@react-pdf/renderer';
import Iconify from '@/components/iconify';
import PaySlipPDF from './paySlipPDF';
import useGet from '@/hooks/useGet';
import { useForm } from 'react-hook-form';
import { useParams } from 'react-router-dom';
import { PAYSTRUCTURE_PAYROLL_LIST_ENDPOINT } from '@/constants/my-company/employee-directory';
import useUserStore from '@/store/user.store';

type PayRoll = {
  year: string;
  month: string;
  monthText: string;
  payrollId: string;
};

const Payslips = () => {
  const theme = useTheme();
  const [selectedIndex, setSelectedIndex] = React.useState(1);
  const [payrollId, setPayrollId] = React.useState('');
  const [list, setlist] = React.useState<PayRoll[] | undefined>([]);
  const { control, watch } = useForm();
  const user = useUserStore((state) => state.user);
  // const {id} = useParams();
  const { data } = useGet<any>(
    PAYSTRUCTURE_PAYROLL_LIST_ENDPOINT (user?.Employee?.id), ['getPayrunListForEmp']
  );

  
  // const options = [...new Set(data?.map((each: { year: any; }) => each.year))].map((each) => ({
  //   label: each,
  //   value: each,
  // }));


  // const year = watch('year');
  // useEffect(() => {
  //   if (data) {
  //     setlist(data?.filter((each: { year: any; }) => each.year === year));
  //   }
  // }, [year, data]);
  
  const options = [...new Set(data?.map((each:any) => each.year))].map((each) => ({
    label: each,
    value: each,
  }));

  const year = watch('year');
  useEffect(() => {
    setlist(data?.filter((each:any) => each.year == year));
  }, [year, data, payrollId]);
  const handleListItemClick = (index: number, id: string) => {
    setSelectedIndex(index);
    if (payrollId !== id) {
      setPayrollId(id);
    } else {
      // Reset payrollId if the same month is selected again
      setPayrollId('');
    }
  };
  
  // Add your custom styles for the header box
  const headerStyles = {
    display: 'flex',
    flexDirection: 'row',
    width: '70%',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: theme.spacing(2),
    backgroundColor: '#4A5363',
    color: theme.palette.primary.contrastText,
  };
  // console.log('Data:', data);
  // console.log('Options:', options);
  // console.log('List:', list);
  // console.log('Mapped Years:', data?.map((each: { year: any; }) => each.year));
  return (
    <Stack
      sx={{
        display: 'flex',
        flexDirection: 'row',
        margin: 2,
        gap: 2,
        flexWrap: 'wrap',
        height: '100%',

        [theme.breakpoints.down('sm')]: {
          flexDirection: 'column',
        },
      }}
    >
      <Stack
        direction='column'
        sx={{
          width: '250px',
          [theme.breakpoints.down('sm')]: {
            width: '100%',
          },
        }}
        gap={2}
      >
        <AppSelect control={control} name='year' options={options} />
        <Box component='span' sx={{ bgcolor: 'background.paper', flex: 1 }}>
          <List component='nav' aria-label='main mailbox folders'>
            {list?.map((each, idx) => (
              <ListItemButton
                selected={selectedIndex === idx}
                onClick={(event) => handleListItemClick(idx, each.payrollId)}
              >
                <ListItemText primary={each.monthText} />
              </ListItemButton>
            ))}
          </List>
        </Box>
      </Stack>
      <Box sx={{ flex: 1 }}>
        {payrollId ? (
          <PaySlipPDF id={payrollId} />
        ) : (
          <Typography variant='body2'>Select Year and Month </Typography>
        )}
      </Box>
    </Stack>
  );
};

export default Payslips;

in this provided code if i select month which is in listitembutton it fetch data and gives payslipdf, but after selecting next month for three time then only it shows next payslip pdf for that month for example if i select jan it shows payslip pdf and same time if i press feb for three times then only it shows the payslip pdf

` useEffect(() => {
    setlist(data?.filter((each:any) => each.year == year));
  }, [year, data, payrollId]);
  const handleListItemClick = (index: number, id: string) => {
    setSelectedIndex(index);
    if (payrollId !== id) {
      setPayrollId(id);
    } else {
      // Reset payrollId if the same month is selected again
      setPayrollId('');
    }
  };`

i modify the logic but it won’t works please give some solution it in react tyepscript

How to subscribe on signal change event in Spark AR?

I have a simple TargetTracker in a scene

(async function() {
    const [
        tracker
    ] = await Promise.all([
        Scene.root.findFirst('targetTracker0')
    ]);

    ...

and i am trying to perform an action when target trcker detects its object. Now, i have read in the community gitbook that it has a property called isTracking, which outputs a BoolSignal.

Now, i’m trying to subscribe to an event of this signal changing and i don’t seem to be able to work. So far from googling around i have this

    tracker.isTracking.monitor().subscribe(function (val) {
        if(val){
            fireAnimations();
        }else{
            haltAnimations();
        }
    });

However, this doesn’t seem to work, and i cannot really debug it, as i don’t know how to Diagnostics.log event from a real camera (or how to simulate TargetTracker detection change in the studio)

Changing attributes on a cloned object changes all objects

I have loaded an OBJ file and from that original I .clone() it into an array. Later I wish to change the vertexColor of some of them to a different color, but changing one changes them all.

var oload = new OBJLoader();
oload.load("objects/tunnel1.obj", function(data)
{
    tunnels[0] = data;
    tunnels[0].traverse(function(titem)
    {
        if(titem.isMesh)
        {
            if(titem.name.toUpperCase().indexOf("INNER")>-1)
            {
                titem.material = new THREE.MeshBasicMaterial(map: wnewtex, vertexColors: true);
            }
        }
    });
});

for(var x = 0; x < width; x++)
{
    for(var y = 0; y < height; y++)
    {
        if(leveldata[x][y] == 15)
        {
            tunnels.push(tunnels[0].clone());
            tunnels[tunnels.length-1].position.set(-x*2,newh,(height-y-1)*2);
            scene.add(tunnels[tunnels.length-1]);
        }
        else if(leveldata[x][y] == 16)
        {
            tunnels.push(tunnels[0].clone());
            tunnels[tunnels.length-1].position.set(-x*2,newh,(height-y-1)*2);
            tunnels[tunnels.length-1].rotation.set(0,Math.PI/2,0);
            scene.add(tunnels[tunnels.length-1]);
        }
        else if(leveldata[x][y] == 23)
        {
            tunnels.push(tunnels[0].clone());
            tunnels[tunnels.length-1].position.set(-x*2,newh,(height-y-1)*2);
            tunnels[tunnels.length-1].rotation.set(0,Math.PI/2,0);
            tunnels[tunnels.length-1].traverse(function(titem)
            {
                if(titem.isMesh)
                {
                    if(titem.name.toUpperCase().indexOf("INNER")>-1)
                    {
                        titem.geometry.setAttribute("color",new THREE.BufferAttribute(new Float32Array(item.geometry.attributes.position.count*3), 3 ));
                        var colort = titem.geometry.attributes.color.array;
                        for(var v2 = 0; v2 < titem.geometry.attributes.position.count*3; v2+=3)
                        {   // Make Red
                            colort[v2+0] = 1;
                            colort[v2+1] = 0;
                            colort[v2+2] = 0;
                        }
                        titem.geometry.attributes.color.needsUpdate = true;
                    }
                }
            });
            scene.add(tunnels[tunnels.length-1]);
        }
        else if(leveldata[x][y] == 26)
        {
            tunnels.push(tunnels[0].clone());
            tunnels[tunnels.length-1].position.set(-x*2,newh,(height-y-1)*2);
            tunnels[tunnels.length-1].rotation.set(0,Math.PI/2,0);
            tunnels[tunnels.length-1].traverse(function(titem)
            {
                if(titem.isMesh)
                {
                    if(titem.name.toUpperCase().indexOf("INNER")>-1)
                    {
                        titem.geometry.setAttribute("color",new THREE.BufferAttribute(new Float32Array(item.geometry.attributes.position.count*3), 3 ));
                        var colort = titem.geometry.attributes.color.array;
                        for(var v2 = 0; v2 < titem.geometry.attributes.position.count*3; v2+=3)
                        {   // Make Green
                            colort[v2+0] = 0;
                            colort[v2+1] = 1;
                            colort[v2+2] = 0;
                        }
                        titem.geometry.attributes.color.needsUpdate = true;
                    }   // If 26 was the last tunnel adjusted
                }       // then even 23 turns green
            });
            scene.add(tunnels[tunnels.length-1]);
        }
    }
}

I take it .clone() does not make a new copy of the attributes for the new object. What is another method to make a clone where the attributes are not linked?

Firebase Cloud Function Not Sending Cloud Messaging

So as the title says, the cloud function triggers fine, logs are all 200 ok. The code itself works and it does check the Firestore for relevant updates. And I also tried manually send a Cloud Messaging with same tokens and parameters through Firebase Console, and I recieved the message but not with the Cloud Function, why?

Is it because I have 2 collection dependencies? I made sure the conditions are met, so I dont understand really. Here is the Function code:

exports.visitorNotification = functions.firestore
  .document('posts/{postId}')
  .onUpdate(async (change, context) => {
    const newValue = change.after.data();
    const oldValue = change.before.data();
    const userId = newValue.userId;

    console.log(`new value: ${JSON.stringify(newValue)} old value ${JSON.stringify(oldValue)}`);

    // Check if the post views reach 5, 10, 50, and 100, 500, 1000, 2500, 5000, 10000
    const viewsThresholds = [5, 10, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
    for (const threshold of viewsThresholds) {
      if (newValue.views >= threshold && oldValue.views < threshold) {
        const userRef = admin.firestore().doc(`notifications/${userId}`);
        const doc = await userRef.get();

        if (doc.exists && doc.data().visitorNotification) {
          console.log(`Doc exists and notifications enabled`);
          const message = {
            notification: {
              title: 'Hello',
              body: `Your post "${newValue.title}" has ${threshold} views.`,
            },
            token: doc.data().currentToken,
          };

          try {
            const response = await admin.messaging().send(message);
            console.log('Successfully sent message:', response);
          } catch (error) {
            console.log('Error sending message:', error);
          }
        }
      }
    }

    return null;
  });