Run javascript function on page reload but dont show onbeforeunload event popup

I want disconect the user on page reload but dont want to show this popup
enter image description here

Here is my code ==>

useEffect(()=>{

const disconnect = (event) => {
  event?.preventDefault();
  socketRef.current.disconnect();
  return undefined;
}

window.addEventListener('beforeunload', disconnect);
return () => {
  window.removeEventListener('beforeunload',disconnect);
}

},[navigate])

“this” is undefined in an array of functions [duplicate]

When I run the example in Firefox the correct function is executed from the array of functions. However in the f0 function this is undefined. Functions are first class in JS, so having a function in an array and invoking it should work.

The example is based on a real code where this works as expected, and arrays in the class are used in functions. The array data is in the class,as are f0 and f1, so why is this undefined when execution occurs?

Example

class unfun {
  data = ["a", "b"];
  f0() {
    return this.data[0];
  }
  f1() {
    return this.data[1];
  }
  abc = [this.f0, this.f1];
  act(x) {
    let f = this.abc[x];
    return f();
  }
}

let u = new unfun;
console.log(u.act(0));

How to update the homepage items when dates are picked

I have a javascript date range picker with this structure

$(document).ready(function() {
    var start = moment().subtract(29, 'days');
    var end = moment();

    function calender(start, end) {
        $('#reportrange span').html(start.format('D MMM YYYY') + ' - ' + end.format('D MMM YYYY'));
        fetchRecords(start, end);
    }

    $('#reportrange').daterangepicker({
        
        ranges: {
           'Today': [moment(), moment()],
           'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           'Last 7 Days': [moment().subtract(6, 'days'), moment()],
           'Last 30 Days': [moment().subtract(29, 'days'), moment()],
           'This Month': [moment().startOf('month'), moment().endOf('month')],
           'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        "startDate": start,
        "endDate": end,
        "opens": "left"
    }, calender);

    calender(start, end);

    $('#prevMonth').on('click', function() {
        start.subtract(1, 'month');
        end.subtract(1, 'month');
        $('#reportrange').data('daterangepicker').setStartDate(start);
        $('#reportrange').data('daterangepicker').setEndDate(end);
        calender(start, end);
    });

    $('#nextMonth').on('click', function() {
        start.add(1, 'month');
        end.add(1, 'month');
        $('#reportrange').data('daterangepicker').setStartDate(start);
        $('#reportrange').data('daterangepicker').setEndDate(end);
        calender(start, end);
    });
    
    function fetchRecords(startDate, endDate) {
        $.ajax({
            type: 'GET',
            url: '/record/', 
            data: {
                startDate: startDate.format('YYYY-MM-DD'),
                endDate: endDate.format('YYYY-MM-DD')
            },
            success: function (response) {
                console.log('Records fetched successfully:', response);
                updateRecordsOnPage(response);
            },
            error: function (error) {
                console.error('Error fetching records:', error);
            }
        });
    }

    function updateRecordsOnPage(recordsHtml) {
        $('#records-container').html(recordsHtml);
    }
});

Once I picked the dates it will past the start and end date to the index controller

public function index(Request $request) {
      $user = Auth::user();

      $startDate = $request->input('startDate');
      $endDate = $request->input('endDate');

      $startDate = $startDate ? Carbon::parse($startDate)->startOfDay() : now()->startOfMonth();
      $endDate = $endDate ? Carbon::parse($endDate)->endOfDay() : now()->endOfMonth();

      $records = Record::where('user_id', $user->id)
           ->whereBetween('datetime', [$startDate, $endDate])
           ->paginate(14);

      return view('record.index', compact('records'));
}

How can update the record list after picking the dates into the homepage below without reload the page

<div class="flex items-center datepicker">
     <i class="fa fa-caret-left ml-2 cursor-pointer" id="prevMonth"></i>
     <div id="reportrange" class="flex mx-auto rounded-md border-0 items-center">
          <span></span>
     </div>
     <i class="fa fa-caret-right mr-2 cursor-pointer" id="nextMonth"></i>
</div>
<div class="records" id="records-container">
    @foreach ($records as $record)
          <!-- record list -->
    @endforeach
</div>

I have tried updating the record list through Ajax in the date range picker js above by using updateRecordsOnPage(response);, but it keeps looping and duplicating my current view until the page crashes. Any solution to make the data lists update after picking the date without reloading the page?

auto-import entire folder in nuxt 3 (server side)

I need to import all script files inside a server folder server/models

and i tried these inside nuxt.config file:

  nitro: {
    plugins: ['~/server/index.ts'],
    scanDirs: ['~/server/models']
  },
  imports: {
    dirs: [
      '~/server/models',
      // '~/server/models/**',
    ],
    global: true
  }

also defined modules like:

(options, nuxt) => {
      const { resolve } = createResolver(import.meta.url)
      addServerImportsDir(resolve('./server/models'))
      // nuxt.hooks.hook('nitro:config', (config) => {
      //   config.plugins = config.plugins || []
      //   config.plugins.push(resolve('server/models'))
      // })
}

but none of them imported exported model files automatically and globally for server codes

TypeScript/VSCode bug? Building key names from const arrays don’t show the correct Intellisense options

I have the following function in a typescript file:

export function buildEnvTests<T extends ReadonlyArray<string>>(environments: T) {
    const r = {} as {[K in T[number] as `is${K}`]: () => boolean};
    for (let e of environments) {
        r[`is${e}`] = () => '' === e;
    }
    return r;
}

If I were to import this function into a TS file, Intellisense in VS Code correctly reports the derived keys in the return value. For example:

import { buildEnvTests } from "./test.js";

const x = ['A', 'B', 'C'] as const;
const r = buildEnvTests(x);
r. // Here, properties named isA, isB and isC show up as expected.

If I do the same in a JavaScript file, however, I get no suggestions:

import { buildEnvTests } from "./test.js";

const x = ['A', 'B', 'C'];
const r = buildEnvTests(x);
r. // Here:  No Intellisense.

How to deploy the open-source SuiteCRM project (https://github.com/salesagility/SuiteCRM)?

I downloaded the project and can’t deploy it, maybe someone has encountered the same problem. Visited the site
https://docs.suitecrm.com/developer/

but there is no information on how to run the project on a local machine so that it can be modified. And make some changes. Thank you.

I tried to re-read the documentation https://docs.suitecrm.com/developer/ and the forum https://community.suitecrm.com/
Didn’t find the information I needed

Rebooting issue with Galaxy note 9 due to some error in execution of doInBackgroung()

I’m having problem with rebooting my Samsung Galaxy note 9. It’s showing following error as given in pic. I don’t wanna loose my data so can anyone help me with this so I can avoid factory resetthe error showing in rescue log tab

I have tried rebooting multiple times
I have cleared cache partition
I tried to access safe mode option but can’t access that either the page where I’m stuck

Google Integrated Auth JWT Validation Failure

Any idea where I am going wrong in verifying the JWT I get back from integrated Google Auth? My React web app receives the token, which I pass to my Node.js backend, where I attempt to verify the token. I have decoded the token and all the info I would expect to be in the payload is there. But when I attempt to verify the token, I get the error, “Invalid token signature”. As you can see in the code below, I have tried using Google’s package, ‘google-auth-library’, and as an alternate approach I manually downloaded the Google public key and using the package ‘jsonwebtoken’. Both report the token as invalid. I’m pretty sure the token / signature is not invalid, so there must be something I’m doing wrong. I double checked, and the Google client ID I use in my React app matches what I’m using in my Node.js backend.

One other bit of background, I’ve setup a project in Google Cloud, and in the Credentials section, have configured an “OAuth 2.0 Client ID” which is where my google client Id referenced in the code comes from, and as far as I can tell, I have followed the instructions provided by Google here

import * as jwt from 'jsonwebtoken'
import { OAuth2Client } from 'google-auth-library'
import { getConfig } from '../tools/config'

export const verifyGoogleJwt = async (token: string) => {
  // Try to use 'google-auth-library' to verify
  try {
    const config = await getConfig()
    const client = new OAuth2Client(config.googleClientId)
    const ticket = await client.verifyIdToken({
      idToken: token,
      audience: config.googleClientId,
    })
    return ticket.getPayload()
  } catch (error) {
    console.error('OAuth2Client.verifyIdToken failed:', error.message)
  }

  // Try to use 'jsonwebtoken' to manually verify with Public Key
  try {
    // From https://www.googleapis.com/oauth2/v1/certs
    const googlePublicKey =
      '-----BEGIN CERTIFICATE-----nMIIDJzCCAg+gAwIBAgIJAO5q5hCX9S+zMA0GCSqGSIb3DQEBBQUAMDYxNDAyBgNVnBAMMK2ZlZGVyYXRlZC1zaWdub24uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wnHhcNMjMxMTA0MDQzODA0WhcNMjMxMTIwMTY1MzA0WjA2MTQwMgYDVQQDDCtmZWRlncmF0ZWQtc2lnbm9uLnN5c3RlbS5nc2VydmljZWFjY291bnQuY29tMIIBIjANBgkqnhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuB+3s136B/Vcme1zGQEg+Avs31/voau8nBPKtvbYhB0QOHTtrXCF/wxIH5vWjl+5ts8up8Iy2kVnaItsecGohBAy/0kRgq8oin+n/cZ0i5bspAX5VW0peh/QU3KTlKSBaz3ZD9xMCDWuJFFniHuxLtJ4QtL4v2oDD3npBPNRPyIcZ/LKhH3+Jm+EAvubI5+6lB01zkP5x8f2mp2upqAmyex0jKFka2e0DOBnavmGsGvKHKtTnE9oSOTDlhINgQPohoSmir89NRbEqqzeZVb55LWRl/hkiDDOZmcMn/oJ8iUbm6vQu3YwCy+ef9wGYEij5GOWLmpYsws5vLVtTE2U+0C/ItQIDAQABozgwnNjAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIHgDAWBgNVHSUBAf8EDDAKBggrnBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOCAQEAifQankV6Ca4UQ9MvTX4KlsaVV6WRn1FL2ZwRPHwFQnw3hFJrHKdQBvCS1339G1uguCOi0CQQJmQauSvRureJ/80Fc/j3cnwEWQgBhuKCHiQbIMFpVoljsVsF91E0FvZ8eJJ5/y7QB3Ww68FavXNjZ62GaYp8awnEdqJdqNFaIv7yWzOO27filjzF3H6VJG7ucx0P6JCCCC6HSii3o1lkRISvSTcevqZnsFdbJEqtVU70siOHxWxMqRopetiTEAsbvwiicdZ6flZqtnxKqB6YEb6TocWpzGvdnVKxzByXdPJbyYvAnvusborJZPHKbleZjyonK+cmsOU6N1Yn/FUxKKhFXEg==n-----END CERTIFICATE-----n'
    return jwt.verify(token, googlePublicKey)
  } catch (error) {
    console.error('jsonwebtoken.verify failed:', error.message)
  }
}

Why am I not able to fetch email with the following code (the second console statement not giving me anything)?

I’m trying to get the email printed in the console that is entered in a form. My code seems right, it is compiling fine but it is not fetching the email. I want to use nodemailer to send emails upon registration, but I’m not able to get the data from frontend to backend. What looks wrong with the code?

import React, { useState } from 'react'  
import './LoginSignUp.css'  
import email_icon from '../Assets/email_icon.png'  
import person_icon from '../Assets/person_icon.png'  
import { Link, useNavigate } from 'react-router-dom'  
import Validation from './SignUpValidation';  
import axios from 'axios'  

export const SignUp = () => {

  const [values, setValues] = useState({
    name: '',
    email: '',
    password: ''
  })

  const navigate = useNavigate();
  const [errors, setErrors] = useState({})

  const handleInput = (event) => {  
    setValues(prev => ({ ...prev, [event.target.name]: [event.target.value] }))  
  }

  const handleSubmit = (event) => {  
    event.preventDefault();  
    setErrors(Validation(values));  
    if (errors.name === "" && errors.email === "" && errors.password === "") {  
      axios.post('http://localhost:8081/signup', values)  
        .then(res => {  
          navigate('/');  
        }  
        )  
        .catch(err => console.log(err));  
    }  
  }   

  const [email, setEmail] = useState("");  
  console.log(email);  

  const sendEmail = async (e) => {  
    e.preventDefault();  

    const res = await fetch("/signup", {
      method: "POST",
      header: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        email
      })
    });
    //I'm not getting anything printed after clicking the Sign Up button
    console.log(res)
  }

  return (
    <div className='container'>
      <div className="header">
        <div className="text">Sign Up</div>
        <div className="underline"></div>
      </div>
      //input fields
      <form className="inputs" action="" onSubmit={handleSubmit}>

        <div className="row">
          <div className="input">
            <img src={person_icon} alt="" style={{ width: '20px', height: '20px' }} />
            <input type="text" placeholder="Name" name='name' onChange={handleInput} />
            {errors.name && <span className='text-danger'>{errors.name}</span>}
          </div>

          <div className="input">
            <img src={email_icon} alt="" style={{ width: '20px', height: '20px' }} />
            <input type="email" placeholder="Email" name='email' value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
        </div>
        //submit button
        <div className="submit-container">
          <button type='submit' className="submit-button" onClick={sendEmail}>Sign Up</button>
          <Link to="/" className="submit-button">Login</Link>
        </div>

      </form>


    </div>
  )
}

How to solve race condition with socket.io in edge

In my socket.io code, I have a race condition between handling a reconnect, and a disconnect
section of server.js

io.on("connection", (socket) => {
    let UID = socket.id
    console.log("A user connected");
    socket.emit("SendUID");
    socket.on("ReturnUID", newUID =>{
        if (!newUID){
            console.log("NEW user");
            socket.emit("UID", socket.id);
            newUID = socket.id;
            storedUID[newUID] = {"disconnecttimer":null};
        }
        else{
            if (storedUID[newUID]){
                console.log("Reconnecting..");
                clearTimeout(storedUID[newUID].disconnecttimer)
                storedUID[newUID].disconnecttimer = null;
            }
            else{
                console.log("New user");
                socket.emit("UID", socket.id);
                newUID = socket.id;
                storedUID[newUID] = {"disconnecttimer":null};
            }
        }
        UID = newUID;
    });
    socket.on("disconnect", ()=>{
        console.log("User disconnected");
        storedUID[UID].disconnecttimer = setTimeout(() => {
            console.log("User deleted");
            delete storedUID[UID];
        }, 10000);
        console.log("user");
    });
});

app.js(all html files have this as an import)

socket.on("UID", (UID) =>{
    localStorage.setItem("UID",UID);
});
socket.on("SendUID", () =>{
    socket.emit("ReturnUID",localStorage.getItem("UID"));
})
socket.on("Delete", () =>{
    localStorage.removeItem("UID");
});

In chrome, the code executes in the proper order: [console output]: User disconnected, A User connected, Reconnecting…
However in Edge, the code executes in the order: A user connected, reconnecting…, user disconnected.
This causes the code to stop functioning correctly

I have tried changing the position of the socket.on(“disconnect”), yet the issue persists.

Oracle APEX X-Frame-Options:DENY

Encountering the following error with Oracle APEX 22.2, ORDS 19.1, and DB 21c. Cleared the browser cache and tested on a different browser, but no luck

using Microsoft Edge :
X-Content-Type-Options:nosniff X-Xss-Protection:1; mode=block Referrer-Policy:strict-origin Pragma:no-cache Expires:Sun, 27 Jul 1997 13:00:00 GMT X-Frame-Options:DENY

using Chorom:
Pragma:no-cache Expires:Sun, 27 Jul 1997 13:00:00 GMT.
X-Frame-Options:DENY

enter image description here

How to make listener re-render only if changes made on navigation

I am trying to make my app only re-render when a change has been made, I have got it so that when I add a new workout, the item re-renders on the navigation back to the original page but when I go to add a new workout and click the back button without adding a new workout, the app still re-renders and adds the original workout again so it is duplicated

  const [workoutSlides, setWorkoutSlides] = useState([]);

  useEffect(() => {
    const didFocus = navigation.addListener(
      'focus',
      () => { load(); }
    )
    return didFocus;
  }, [navigation]);

  const load = async () => {
    try {
      const storedSlides = await AsyncStorage.getItem('workoutSlides');
      if (storedSlides) {
        const parsedSlides = JSON.parse(storedSlides);
        setWorkoutSlides(parsedSlides);
      }
      const name = await AsyncStorage.getItem('WorkoutName');
      const sets = await AsyncStorage.getItem('WorkoutSets');
      const reps = await AsyncStorage.getItem('WorkoutReps');
      const weight = await AsyncStorage.getItem('WorkoutWeight');
      if (name, reps, sets, weight) {
        setWorkoutSlides((prevSlides) => [
          ...prevSlides,
          {
            name: name,
            reps: reps,
            sets: sets,
            weight: weight,
          },
        ]);
      }
    } catch (error) {
      alert(error);
    }
  };

  useEffect(() => {
    const storeData = async () => {
      try {
        await AsyncStorage.setItem('workoutSlides',
          JSON.stringify(workoutSlides));
      } catch (err) {
        console.log(err);
      }
    };
    storeData();
  }, [workoutSlides]);

I am using react navigation and when I click the back button in the status bar, this is when it re renders the page, i’m thinking of trying to do an if statement with the navigation.addListener hook but i can’t seem to figure one out, i’ve tried multiple ways but nothing seems to have worked

i’m still quite new to coding and this is my first project so i appreciate any help

How to make my product decrement instead of increment?

I’ve created an e-commerce website in html/css/javascript, i have a problem with the decrementation, when i click on “-” to remove the price of the product it keeps incrementing the price in the cart when it should decrement it.

var cartTotal = 0;

    function addToCart(button, price) {
        var quantity = parseInt(button.parentElement.querySelector("span").textContent);
        var totalForProduct = quantity * price;
        cartTotal += totalForProduct;

        var productName = button.parentElement.parentElement.querySelector("h3").textContent;
        var cartList = document.getElementById('cartList');

        var existingCartItem = cartList.querySelector('[data-product-name="' + productName + '"]');
        if (existingCartItem) {
            var existingQuantity = parseInt(existingCartItem.querySelector('.cart-item-quantity').textContent);
            existingQuantity += quantity;
            existingCartItem.querySelector('.cart-item-quantity').textContent = existingQuantity;

            var existingTotal = parseInt(existingCartItem.querySelector('.cart-item-total').textContent);
            existingTotal += totalForProduct;
            existingCartItem.querySelector('.cart-item-total').textContent = existingTotal;
        } else {
            var cartItem = document.createElement('li');
            cartItem.classList.add('cart-item');
            cartItem.setAttribute('data-product-name', productName);
            cartItem.innerHTML =
                productName + ' (' + price + ' lei) x <span class="cart-item-quantity">' + quantity + '</span> = <span class="cart-item-total">' + totalForProduct + '</span> lei' +
                '<button onclick="removeFromCart(this)">Șterge</button>';
            cartList.appendChild(cartItem);
        }

        document.getElementById('total').textContent = cartTotal;
    }

    function removeFromCart(button) {
        var cartItem = button.parentElement;
        var totalForProduct = parseInt(cartItem.querySelector('.cart-item-total').textContent);
        cartTotal -= totalForProduct;
        document.getElementById('total').textContent = cartTotal;
        cartItem.remove();
    }

    function changeQuantity(button, change) {
        const quantityElement = button.parentElement.querySelector("span");
        const quantity = parseInt(quantityElement.textContent);

        if (change === -1 && quantity > 0) {
            quantityElement.textContent = quantity - 1;
        } else if (change === 1) {
            quantityElement.textContent = quantity + 1;
        }
    }

    function clearCart() {
        var cartList = document.getElementById('cartList');
        cartList.innerHTML = '';
        cartTotal = 0;
        document.getElementById('total').textContent = cartTotal;
    }
</script>

Reset camera-orbit of model-viewer element in a JavaScript function

I am using google’s model-viewer element in my electron/react app in order to render interactable models in 3d.

Currently, I am using the following code, so that when the changeModel function is run, the src attribute of the model-viewer is updated, making it display a different model.

export default function RobotDetails() {
    const [url, setUrl] = useState("../models/test.glb");
    const [cameraOrbit, setCameraOrbit] = useState("45deg 55deg 4m")

    function changeModel(modelName: string) {
        setUrl(`../models/${modelName}.glb`)
        setCameraOrbit("45deg 55deg 4m")
    }

    console.log(url)

    return (
        <div className="modelview-container">
            <ModelViewer modelPath={new URL(url, import.meta.url).href} cameraOrbit={cameraOrbit} />
        </div>
    );
}

ModelViewer.tsx:

declare global {
    namespace JSX {
        interface IntrinsicElements {
            "model-viewer": ModelViewerAttributes;
        }
        interface ModelViewerAttributes {
            src: string;
        }
    }
}

export default function ModelViewer(props: { modelPath: string, cameraOrbit: string }) {
    return ( <model-viewer src={props.modelPath} camera-orbit={props.cameraOrbit} camera-controls touch-action="pan-y" interaction-prompt="none" /> )
}

setCameraOrbit should theoretically reset the camera-orbit property of the model-viewer, however as the orbit value doesn’t actually change when you rotate the model, there isn’t anything to reset.

What method should I be using to reset the camera whenever the changeModel function is run?