In JavaScript, what sets apart the usage of “let” and “var”? [duplicate]

What distinctions exist between the “let” and “var” keywords in the JavaScript language when assigning values, and under what circumstances should each be employed?

In this code snippet, can you clarify the appropriate instances for using “let” or “var”? Create a function called ‘processNumbers’ that takes an array of numbers as a parameter. Inside the function, declare a variable named total to store the sum of all the numbers. Additionally, create a variable named counter to keep track of the number of elements processed. Your task is to implement the function for both total and counter.

How to make the onClick event only fire when the element is deliberately clicked and not when the click “started” from another element

In the snippet below, if you:

  • Click down in the red <div> and hold the click down
  • Then move the cursor to the blue <body> (without releasing yet)
  • Then release the click when you are in the blue <body>

Then e.target counts the click as a click on the <body> even though the click actually happened to the <div> element

My scenario is a side menu which should close when the body is clicked, however, I do NOT want the menu to close if the click originated from the menu but was released over the body like what is happening in my snippet. Is this possible to do?

PS: Just to clarify, I am just trying to understand this behavior and how you could get the click’s start element instead of whatever it is that is going on right now. I am not asking how to build the menu or anything.

I am also noticing that if you start the click in the <body> and then release it over the <div>, it still counts as a click to the <body>. This is the opposite effect of what I demonstrated above which is confusing me even further. Is this because it always chooses the greater ancestor of the start and release elements?? I can`t seem to get any results about this when Googling.

PS: I am using google chrome in case this behavior is browser specific.

document.body.addEventListener("click", (e) => {
  console.log(e.target);
});
body {
  height: 10rem;
  background: turquoise;
}
.div {
  height: 5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background: salmon;
}
<div class="div">Click Down Here</div>
Release Here

Invariant Violation: requireNativeComponent: “RNSScreenStackHeaderConfig” was not found in the UIManager in Expo

I just switched from Expo Go to an Expo development build. But now there seems to be a problem with createNativeStackNavigator. I always get either the error:

Invariant Violation: requireNativeComponent: “RNSScreenStackHeaderConfig” was not found in the UIManager in Expo

or
Invariant Violation: requireNativeComponent: “RNSScreen” was not found in the UIManager in Expo

As you can see I have already installed the required packages

– react-native-screens

– react-native-safe-area-context

I have also rebuilt the app after installation

import React from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { Text, View } from 'react-native';

const AppNavigationContainer = () => {

    const Stack = createNativeStackNavigator();

    return (
        <Stack.Navigator screenOptions={{ headerShown: false }}>
            <Stack.Screen name="Tabs" component={TabNavigationContainer} />
        </Stack.Navigator>
    );
};

function TabNavigationContainer() {

    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Text>Test</Text>
        </View>
    );

}

export default AppNavigationContainer;

Here my dependencies:

{
"name": "spot-finder",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
   "start": "expo start",
  "android": "expo start --android",
  "ios": "expo start --ios",
  "web": "expo start --web"
},
"dependencies": {
  "@expo/webpack-config": "^19.0.0",
  "@react-native-async-storage/async-storage": "1.18.2",
  "@react-native-community/datetimepicker": "7.2.0",
  "@react-native-masked-view/masked-view": "0.2.9",
  "@react-native-community/slider": "4.4.2",
  "@react-navigation/material-bottom-tabs": "^6.2.17",
  "@react-navigation/native": "^6.1.9",
  "@react-navigation/native-stack": "^6.9.17",
  "@react-navigation/stack": "^6.3.20",
  "expo": "~49.0.13",
  "expo-barcode-scanner": "~12.5.3",
  "expo-blur": "~12.4.1",
  "expo-clipboard": "~4.3.1",
  "expo-dev-client": "~2.4.12",
  "expo-haptics": "~12.4.0",
  "expo-image": "~1.3.5",
  "expo-image-manipulator": "~11.3.0",
  "expo-image-picker": "~14.3.2",
  "expo-linear-gradient": "~12.3.0",
  "expo-location": "~16.1.0",
  "expo-mail-composer": "~12.3.0",
  "expo-splash-screen": "~0.20.5",
  "expo-status-bar": "~1.6.0",
  "expo-web-browser": "~12.3.2",
  "firebase": "^10.7.0",
  "geofire-common": "^6.0.0",
  "react": "18.2.0",
  "react-dom": "18.2.0",
  "react-native": "0.72.6",
  "react-native-confetti-cannon": "^1.5.2",
  "react-native-gesture-handler": "~2.12.0",
  "react-native-maps": "1.7.1",
  "react-native-paper": "^5.10.6",
  "react-native-qrcode-svg": "^6.2.0",
  "react-native-reanimated": "~3.3.0",
  "react-native-reanimated-carousel": "^3.5.1",
  "react-native-safe-area-context": "4.6.3",
  "react-native-screens": "~3.22.0",
  "react-native-star-rating-widget": "^1.7.2",
  "react-native-step-indicator": "^1.0.3",
  "react-native-vector-icons": "^10.0.0",
  "react-native-web": "~0.19.6"
},
"devDependencies": {
  "@babel/core": "^7.20.0"
},
"private": true
}

and here the App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';

import AppNavigationContainer from './src'

export default function App() {

    return (
      <GestureHandlerRootView style={{ flex: 1 }}>
        <NavigationContainer>
          <AppNavigationContainer />
        </NavigationContainer>
      </GestureHandlerRootView>
    );
  }

How to run an OnEdit function to other sheets with Libraries

I have 8 different Sheets with the same format and i have to run one OnEdit script in each and every one of them

I also dont want the users to Edit the script because of sensitive data

I created a new appscript project from google drive pasted my script there and individually went to all other sheets and added the Library

Do i have to call for that on edit in script or am i missing something

Thank you for the help

ThreeJs: How to rotate an already animated object

I have created an object (spaceship) in Blender, animated its movements (make it wobble/rotate a bit randomly) and exported the 3D model to ThreeJs.

If the user presses LEFT ARROW, the model should rotate towards its left on the X-Y plane, and similarly for RIGHT ARROW.

HOWEVER, due to the animation, the rotation coordinates keep getting reset. The following images will clarify the issue:

This is from the console where I’m printing out the rotation of my spaceship mesh:
rotation successfully changed to 30, 0, 0

HOWEVER, immediately afterwards:
rotation changed back as the mesh is animated

What I want: is for the mesh to rotate when I rotate it, and then wobble ABOUT that new axis, rather than just about its original orientation. In other words, the animation should have relative rotation, not absolute rotation. Is that possible?

My react.js application showing 404 not found when it is navigated and then reloaded in hostinger server

My web-app is navigating into another page but when I’m trying to reload it then its showing “404- oops! looks like page is lost”. Subpages are not loading in my project and I’ve tried deleting and posting it a few times too.

—> Oops, looks like the page is lost.
This is not a fault, just an accident that was not intentional.

is there anyone who can find solution to this problem.

Can’t web scrape website without Javascript enabled – Laravel

I am trying to web scrape this website with Laravel: https://datacvr.virk.dk/soegeresultater?sideIndex=0&enhedstype=virksomhed&antalAnsatte=ANTAL_20_49&virksomhedsstatus=aktiv%252Cnormal&size=10

With other websites, e.g. Wikipedia, the following code works smoothly. However, on this website it returns an error HTML page, where the following error gets shown:
“We’re sorry but client doesn’t work properly without JavaScript enabled. Please enable it to continue.”
I suppose the reason Javescript is not enabled is because I use Laravel Symfony to web scrape, which is shown below.

<?php

namespace AppHttpControllers;

use SymfonyComponentHttpClientHttpClient;
use SymfonyComponentBrowserKitHttpBrowser;

class CompaniesController extends Controller
{
    public function index() {
        $client = new HttpBrowser(HttpClient::create());
        $crawler = $client->request('GET', 'https://datacvr.virk.dk/soegeresultater?sideIndex=0&enhedstype=virksomhed&antalAnsatte=ANTAL_20_49&virksomhedsstatus=aktiv%252Cnormal&size=10');            
        
        return $crawler->html();
    }
}

I also tried following this tutorial: https://webmobtuts.com/backend-development/using-laravel-and-symfony-panther-to-scrape-javascript-websites/
Where I tried using the Symfony Panther Client to mock/create a Chrome Client. You can see my code here:

<?php

namespace AppHttpControllers;

use SymfonyComponentPantherClient;

class CompaniesController extends Controller
{
    public function index() {

        $client = Client::createChromeClient();    // create a chrome client

        $crawler = $client->request('GET', 'https://datacvr.virk.dk/soegeresultater?sideIndex=0&enhedstype=virksomhed&antalAnsatte=ANTAL_20_49&virksomhedsstatus=aktiv%252Cnormal&size=10');            

        $client->waitFor('div');
        
        return $crawler->html();
    }
}

However, this returns a similar error: “Enable JavaScript and cookies to continue” within an HTML page.

How can you enable JavaScript on web scraping? Do I need to add something to the header of the request, or use a different library?

Custom Card Component with individual Controllers in SAPUI5 Application

I want to create a FIORI Overview Page with SAPUI5 1.84 and ​I followed this Tutorial to add custom cards to the application. After adding the first custom card, everything worked just fine. It showed the card with its custom UI elements and used the custom controller. The Component.js looked like this:

(function () {
    "use strict";

    jQuery.sap.declare("myApp.ext.customcard1.Component");
    jQuery.sap.require("sap.ovp.cards.generic.Component");

    sap.ovp.cards.generic.Component.extend("myApp.ext.customcard1.Component", {
        metadata: {
            properties: {
                "contentFragment": {
                    "type": "string",
                    "defaultValue": "myApp.ext.customcard1.customcard1"
                }
            },
            version: "1.44.10",
            library: "sap.ovp",
            includes: [],
            dependencies: {
                libs: ["sap.m"],
                components: []
            },
            config: {},
            customizing: {
                "sap.ui.controllerExtensions": {
                    "sap.ovp.cards.generic.Card": {
                        controllerName: "myApp.ext.customCard1.customcard1"
                    }
                }
            }
        }
    });
})();

The custom card files look like this:

webapp
-ext
--customcard1
---Component.js
---customcard1.controller.js
---customcard1.fragment.xml

Then I wanted to add a second custom card to the application. I created it just liked the first custom card. When starting the application, the second card is shown, but I soon realized that both cards use the same controller class. The customcard1.controller.js was also used as the controller for the customcard2 instead of customcard2.controller.js. The sources tab in chrome debug tools also shows that only code from the files customcard1/Component.js, customcard2/Component.js and customcard1.controller.js is being executed.

I tried debugging into the framework and soon realized that somewhere in the code it looks up the controller for the custom components by the class name sap.ovp.cards.generic.Card wich returned an instance of the customcard1.controller.js for both custom cards.

I then found the Sample Code for custom cards and realized that the controller is linked to the custom component differently than in the tutorial I originally used.

Instead of the customizing:

customizing: {
  "sap.ui.controllerExtensions": {
    "sap.ovp.cards.generic.Card": {
      controllerName: "myApp.ext.customCard1.customcard1"
    }
  }
}

they set the controller as a metadata property in the Component.js:

metadata: {
  properties: {
    "controllerName": {
      "type": "string",
      "defaultValue": "test.testovp.ext.myCustomCard.MyCustomCard"
}

I tried changing my Component.js and removed the customizing section and added the controller name in the metadata like this:

(function () {
    "use strict";

    jQuery.sap.declare("myApp.ext.customcard2.Component");
    jQuery.sap.require("sap.ovp.cards.generic.Component");

    sap.ovp.cards.generic.Component.extend("myApp.ext.customcard2.Component", {
        metadata: {
            properties: {
                "contentFragment": {
                    "type": "string",
                    "defaultValue": "myApp.ext.customcard2.customcard2"
                },
                "controllerName": {
                    "type": "string",
                    "defaultValue": "myApp.ext.customcard2.customcard2"
                },
            },
            version: "1.44.10",
            library: "sap.ovp",
            includes: [],
            dependencies: {
                libs: ["sap.m"],
                components: []
            },
            config: {},
        }
    });
})();

With both Component.js setup like this, both custom cards use their correct individual controllers.

However, I now realized that I do not extend the generic custom card class sap.ovp.cards.generic.Card anymore. This means that I do not have access to any properties of this class in my custom controllers.

What am I doing wrong and how can I setup my application with multiple custom cards that each use their individual controller that still inherits all functions and properties from the generic card class?

Handling simple hydration mismatch after fetch in Nuxt 3

I am making a simpe “email confirm” page.
It gets confirm key from URL, sends a POST request to API which returns true or nothing.
If key is correct the API removes it from database and returns true so the page can show success message:

// pages/confirm/[key].vue

<script setup>
    const route = useRoute();
    const key = route.params.key;

    const confirmed = ref(false);

    try
    {
        const result = await $fetch('/api/confirm', {
            method: 'post',
            body: { key: key },
        });

        confirmed.value = !!result;
    } catch {}
</script>

<template>
        <div v-if="confirmed">Email confirmed!</div>
</template>

The problem is when I open the page in browser with correct key passed in URL I only see “Email confirmed” message for a few milliseconds and then it disappears with “hydration mismatch” warning in console.

As far as I understand, Nuxt renders the page on server where the page has “Email confirmed” message. But after API call information about confrim keys gets deleted from database so when it comes to browser render it calls for API once again, this time it gets an empty response (because there is no such email confirm key anymore) and removes successs message.

How can I fix it?
Maybe there is a way to make only one API call or somehow save its result?
I am new to Nuxt and I really don’t know how to propely work with this “double rendering” thing…

dispatch an action only on react component unmount

I am using multiple tabs in react-js and each tab content is a component like below profile component that contains multiple input controls.
I want to dispatch an updateUser action when tab will be changed or component will be destroyed.

I am using useEffect, so by passing an empty dependency array ([]) to the useEffect, i can ensure that the effect runs only once when the component is mounted, and the cleanup function runs when the component is unmounted but i want to dispatch my action only on unmount the component.

Anyone please help me to achive this.!

import React, { useEffect, useState } from 'react';
import '../User.scss';
import iconPhone from '../../../images/icon-phone.png';
import iconMail1 from '../../../images/icon-mail-01.png';
import iconMessageTextSquare1 from '../../../images/icon-message-text-square-01.png';
import { useAppDispatch, useAppSelector } from '../../../hooks/storeHooks';
import { UserDetails } from '../model/userDetails';
import { updateUser } from '../UserSlice';
import { isEqual } from 'lodash';

const Profile: React.FC = () => {
  const [phoneExtension, setPhoneExtension] = useState('000');
  const dispatch = useAppDispatch();

  const currentUser = useAppSelector((state) => state.user.currentUser);
  const initialUserState = currentUser || undefined;
  const [user, setUser] = useState<UserDetails | undefined>(initialUserState);
  const handleInputChange = (id: string, value: string) => {
    setUser((prevUser) => ({
      ...(prevUser as UserDetails),
      [id]: value,
    }));
  };

  useEffect(() => {
    let isMounted = true;
    return () => {
      isMounted = false;
      if (currentUser && currentUser.id && user && isMounted) {
        if (!isEqual(currentUser, user)) {
          console.log('Changes detected. Dispatching update.');
          dispatch(updateUser({ id: currentUser.id, user }));
        } else {
          console.log('No changes detected.');
        }
      }
    };
  }, []);

  useEffect(() => {
    return () => {
      if (currentUser && currentUser.id && user) {
        if (!isEqual(currentUser, user)) {
          console.log('Changes detected. Dispatching update.');
          dispatch(updateUser({ id: currentUser.id, user }));
        } else {
          console.log('No changes detected.');
        }
      }
    };
  }, []);

  return (
    <div className='flex flex-row flex-grow profile-block'>
      <div className='card profile-card'>
        <div className='header'>
          <span className='title'>Profile</span>
          <div>update your personal and company details here.</div>
        </div>
        <div className='body'>
          <div className='profile-info'>
            <div className='protext'>
              <div className='text'>Personal info</div>
              <p>Personal details and profile picture</p>
            </div>
            <div className='card'>
              <form className='register-form'>
                <div className='form-row'>
                  <div className='form-col'>
                    <label htmlFor='firstName'>First Name:</label>
                    <input
                      type='text'
                      id='firstName'
                      className='custom-input'
                      value={user?.firstName || ''}
                      onChange={(e) => {
                        handleInputChange('firstName', e.target.value);
                      }}
                      readOnly={false}
                    />
                  </div>
                  <div className='form-col'>
                    <label htmlFor='lastName'>Last Name:</label>
                    <input
                      type='text'
                      id='lastName'
                      className='custom-input'
                      value={user?.lastName || ''}
                      onChange={(e) => {
                        handleInputChange('lastName', e.target.value);
                      }}
                    />
                  </div>
                </div>
                <div className='form-row'>
                  <div className='form-col full-col'>
                    <label htmlFor='jobtitle'>Job Title:</label>
                    <input
                      type='text'
                      id='jobtitle'
                      className='custom-input'
                      value={user?.jobTitle || ''}
                      onChange={(e) => {
                        handleInputChange('jobTitle', e.target.value);
                      }}
                    />
                  </div>
                </div>
                <div className='form-row'>
                  <div className='form-col col60'>
                    <label htmlFor='phoneNumber'>Office Number</label>
                    <div className='input-group'>
                      <div className='icon-block'>
                        <img src={iconPhone} alt='icon phone' />
                      </div>
                      <input
                        type='text'
                        id='phoneNumber'
                        className='custom-input'
                        value={user?.phoneNumber || ''}
                        onChange={(e) => {
                          handleInputChange('phoneNumber', e.target.value);
                        }}
                      />
                    </div>
                  </div>
                  <div className='form-col col40'>
                    <label htmlFor='phoneExtension'>Phone Extension:</label>
                    <input
                      type='text'
                      id='phoneExtension'
                      className='custom-input'
                      value={phoneExtension}
                      onChange={(e) => {
                        setPhoneExtension(e.target.value);
                      }}
                    />
                  </div>
                </div>
              </form>
            </div>
          </div>
          <br />
          <div className='divider'></div>
          <br />
          <br />
          <div className='profile-info'>
            <div className='protext'>
              <div className='text'>Notification Contact Information</div>
              <p>Details here will be blah blah blah for contact information for notifications. </p>
            </div>
            <div className='card'>
              <form className='register-form'>
                <div className='form-row'>
                  <div className='form-col full-col'>
                    <label htmlFor='notifyEmail'>Notify me by email</label>
                    <div className='input-group'>
                      <div className='icon-block'>
                        <img src={iconMail1} alt='icon email' />
                      </div>
                      <input
                        type='text'
                        id='notifyEmail'
                        className='custom-input'
                        value={user?.email || ''}
                        onChange={(e) => {
                          handleInputChange('email', e.target.value);
                        }}
                      />
                    </div>
                  </div>
                  <div className='form-col full-col'>
                    <label htmlFor='notifySms'>Notify me by sms</label>
                    <div className='input-group'>
                      <div className='icon-block'>
                        <img src={iconMessageTextSquare1} alt='icon sms' />
                      </div>
                      <input
                        type='text'
                        id='notifySms'
                        className='custom-input'
                        value={user?.phoneNumber || ''}
                        onChange={(e) => {
                          handleInputChange('phoneNumber', e.target.value);
                        }}
                      />
                    </div>
                  </div>
                  <div className='form-col full-col'>
                    <label htmlFor='notifySms'>Notify me by dialer</label>
                    <div className='input-group'>
                      <div className='icon-block'>
                        <img src={iconMessageTextSquare1} alt='icon sms' />
                      </div>
                      <input
                        type='text'
                        id='notifySms'
                        className='custom-input'
                        value={user?.dialer || ''}
                        onChange={(e) => {
                          handleInputChange('dialer', e.target.value);
                        }}
                      />
                    </div>
                  </div>
                  <div className='form-col full-col'>
                    <label htmlFor='notifySms'>Notify me by pager</label>
                    <div className='input-group'>
                      <div className='icon-block'>
                        <img src={iconMessageTextSquare1} alt='icon sms' />
                      </div>
                      <input
                        type='text'
                        id='notifySms'
                        className='custom-input'
                        value={user?.pager || ''}
                        onChange={(e) => {
                          handleInputChange('pager', e.target.value);
                        }}
                      />
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Profile;

sending data via ajax to controller is always null

I’m trying to create a function for adding events in my asp.net core MVC app via ajax:

View.cshtml:

function Add() {
            var eventdto = {};
            eventdto.id = "F51B27EE-27F6-4C50-BD81-08DBF0494506";
            eventdto.Title = $('#Title').val();
            eventdto.Description = $('#Description').val();
            eventdto.Start = $('#Start').val();
            eventdto.End = $('#End').val();
            eventdto.AllDay = $('#AllDay').val();
            eventdto.Url = $('#Url').val();
            eventdto.BackgroundColor = $('#BackgroundColor').val();

            $.ajax({
                type: "POST",
                url: "/Home/JsonTest",
                data: '{eventdto: ' + JSON.stringify(eventdto) + '}',
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    $('#schedule').modal('hide');
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
        }

Controller.cs:

[HttpPost]
        public JsonResult JsonTest(EventDTO eventdto)
        {
           return Json(eventdto);
        }

and in view eventdto generated successfully:
eventdto in view

but in my controller eventdto is always null:
eventdto in controller

i trying sending data like:

data: eventdto,

data: {eventdto},

data: {eventdto: eventdto},

data: { eventdto:
                         {
                            "title" : "asdasd",
                            description : "asdasd",
                            start : "asdasd",
                            end : "asdasd",
                            allDay : "asdasd",
                            url : "asdasd",
                            backgroundColor : "asdasd"
                    }
                },

I have tried various solutions I found on the web ([FormBody], change name of eventdo property to “data” and some others), but value is always null. what im doing wrong?