Cypress execute another test to re-login in the middle of a running spec, when auth token expires, and resume previous session

I’m testing a web app, the user authentication of which is handled via firebase, however the problem is due to certain business logic, the authentication token expires after a random interval, causing the requests to throw 412 error, I’ve intercepted all requests to track whenever a request responds with 412, I then have to run a test that signs in the user, then resume the session where it previously was on. But the problem I’m facing is that cypress once loads a spec, it follows the order in the spec, and doesn’t run my test for Sign in. Here’s the code I’ve tried

cy.intercept("*", (req) => {
    if (req.response && req.response.statusCode === 412) {
      SignIn();
    }
  });

I also need to store the state to resume from where the session had expired to continue running the tests

Authenticating via Keycloak in an iframe

I am trying to include authentication via keycloak in an existing software that is extendable via custom javascript. Other solutions like the Google AAI work just fine, but I am having issues with keycloak. Problem is that the extendable authentication widget is displayed in an iframe, thus the standard keycloak.login() method does not work because displaying of keycloak in an iframe is disabled, which as I understand is also the correct behaviour.

Trying to work around that I used the keycloak.createLoginUrl() to open the authentication in a new window, which also works and lets me successfully authenticate via my third party. But now I need to access the token that is returned upon successful login via keycloak to start an authenticated session in my software, which is the point I am struggling with right now. I believe I am missing something obvious in the workings of keycloak, maybe somebody sees the error in my ways. The following code is the entire login procedure, where window.parent.postMessage(message, "*"); passes the token back to the software.

window.onload =  function () {
        keycloak = new Keycloak({...
        });

        keycloak.onTokenExpired = function () {
          keycloak
            .updateToken(30)
            .success(() => {
              console.log("Successfully got a new token", keycloak.token);
              let message = {
                type: "customAuthentication",
                token: keycloak.token,
              };
              window.parent.postMessage(message, "*");
            })
            .error(() => {
              console.log("Error upon refreshing the keycloak token");
            });
        };

       keycloak
          .init({
            checkLoginIframe: false,
          })
          .then(function (authenticated) {
            if (authenticated) {
              console.log(keycloak);
              let message = {
                token: keycloak.token,
              };

              if (window.opener) {
                message.type = "keycloakAuthSuccess";
                window.opener.postMessage(message, "*");
                window.close();
              } else {
                message.type = "customAuthentication";
                window.parent.postMessage(message, "*");
              }
            } else {
              const button = document.getElementById(
                "button-custom-keycloak-login"
              );
              button.onclick = function () {
                window.open(keycloak.createLoginUrl({
                    redirectUri : "..."
                }), "Keycloak login popup");
              };
            }
          });

        window.addEventListener("message", (event) => {
          let message = event.data;
          if (message && message.type === "signOut") {
            keycloak.logout();
          } else if (message && message.type === "keycloakAuthSuccess") {
            keycloak.login();
          }
        });
      };

import com.itextpdf.html2pdf.attach.impl.layout.HtmlPageHeader;

import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.html2pdf.attach.impl.layout.HtmlPageHeader; import com.itextpdf.layout.element.Paragraph;

HtmlPageHeader header = new HtmlPageHeader();
header.setScript(“../../hisglobal/js/jquery-main.min.js”);
document.add(header);`

but I’m not able to find a jar with this, where I can import these imports.
I have tried I io-7.1.9, and itext 5 .. jar
not html2pdf 7.2.0 where I can download this jar and use it without error.

Removing a particular component from DOM

I am working on a component which will act like a desktop screen. It can contain several app windows which will be resizable and draggable (i.e. All the windows will not be identical)

I decided to store the active window in an Array of window details Object:

const [activeWindows, setActiveWindows] = useState([
   {
    index: 1,
    title: 'App1',
    isMinimized: false,
    dimensions: {
      ...
    }
  },
  {
    index: 2,
    title: 'App2',
    isMinimized: false,
    dimensions: {
      ...
    }
  },
])

In my screen component, I am mapping over these arrays to render each of them:

{
        activeWindows.map((window) => (
          <AppWindow 
            idx={window.index}
            title={window.title}
            dimensions={window.dimensions} //Initial dimension
            handleClose={handleClose}
          />
        ))
}

handleClose is a very straightforward function that just updates the array to remove the target object from the list.

The issue comes when I do change my AppWindow position and dimensions and then I close the window, the window Object gets removed from the list but that specific component doesn’t. This causes the last AppWindow component to be removed and the updated activeWindows data is mapped to the existing components which causes the content swapping (for example: If there are 4 active window and I remove window 2 (i.e. removing its object from activeWindows), then the object rendered in window 3 will move to window 2 hence the dimension and the position of my App 3 will change).

I am not sure if this is the best approach to tackle these kinds of scenarios, but my main aim is to be able to achieve this in a way that is memory efficient as well so that my DOM/VDOM doesn’t get filled with unnecessary elements.

how to solve this uncaught error in react typescript

I wrote a program in react typescript, but I got an error called uncaught error and I did run and debug tests and searched on google, but I am unable to solve this error, so I need help from anyone who can solve this error. here is my program

react with typescript

import { createContext, useContext, useMemo, } from "react"

type ComplexObject = {
  kind:string
}

const Context = createContext<ComplexObject | null >(null)
const useGetComplexObject=()=>{
  const object=useContext(Context)
  if(!object)
  {
    throw new Error("useGetComplexObject must be used within the parameter");
    return object
  }
}

export default function MyApp()
{
  const object  =useMemo(()=>({kind:"complex"}),[])
  return (
    
      <Context.Provider value={object}>
    <MyComponent />
      </Context.Provider>
    
  )
}

function MyComponent()
{
  const object=useGetComplexObject()
  return (
    <div>
      <p>current object : {object.kind}</p>
    </div>
  )
}

I searched this uncaught error on google but I cannot find solution for this error, what I am expecting is to anyone who knows react with typescript can help me to solve this uncaught TypeError and improve this program

libsignal-protocol-javascript outdated/alternateive

I am currently working on an chat-web-app and I have trouble to find good Encryption Libraries for js. Till I found out about the libsignal-protocol-javascript . But it is old and seems to no work properly.
Is there a good or at least a updated alternative/version.

This is a piece of an example that I gave tried to get working:

<head>
    <script src="{{ url_for('static', filename='libsignal-protocol-javascript.js') }}"></script>
    <script src="{{ url_for('static', filename='InMemorySignalProtocolStore.js') }}"></script>
</head>

<body>

</body>
<script>
    var KeyHelper = libsignal.KeyHelper;

    function generateIdentity(store) {
        return Promise.all([
            KeyHelper.generateIdentityKeyPair(),
            KeyHelper.generateRegistrationId(),
        ]).then(function (result) {
            store.put('identityKey', result[0]);
            store.put('registrationId', result[1]);
        });
    }

    function generatePreKeyBundle(store, preKeyId, signedPreKeyId) {
        return Promise.all([
            store.getIdentityKeyPair(),
            store.getLocalRegistrationId()
        ]).then(function (result) {
            var identity = result[0];
            var registrationId = result[1];

            return Promise.all([
                KeyHelper.generatePreKey(preKeyId),
                KeyHelper.generateSignedPreKey(identity, signedPreKeyId),
            ]).then(function (keys) {
                var preKey = keys[0]
                var signedPreKey = keys[1];

                store.storePreKey(preKeyId, preKey.keyPair);
                store.storeSignedPreKey(signedPreKeyId, signedPreKey.keyPair);

                return {
                    identityKey: identity.pubKey,
                    registrationId: registrationId,
                    preKey: {
                        keyId: preKeyId,
                        publicKey: preKey.keyPair.pubKey
                    },
                    signedPreKey: {
                        keyId: signedPreKeyId,
                        publicKey: signedPreKey.keyPair.pubKey,
                        signature: signedPreKey.signature
                    }
                };
            });
        });
    }

    var ALICE_ADDRESS = new libsignal.SignalProtocolAddress("xxxxxxxxx", 1);
    var BOB_ADDRESS = new libsignal.SignalProtocolAddress("yyyyyyyyyyyyy", 1);

    var aliceStore = new libsignal.SignalProtocolStore(); // Here does it fail

    var bobStore = new libsignal.SignalProtocolStore(); // And heere

Every time I run it it throws this error:
Uncaught TypeError: libsignal.SignalProtocolStore is not a constructor

But it is also not a function. I am sure that I Overseeing something. But I could not figure out what.
And I feel not well to use this old project. Maybe through the fact that it does not receive updates since 6 – 8 years, I could get some minus points for using it. But if there is no alternative and I could get it working, I would use it.

Getting default image when streaming a video onto the webpage through django

My moto:-* create a webpage which accepts a video file and once submitted through submit button, the video(in form of frames) will display within samepage in another div section. reason for displaying as frames is i need to process each frame. (Rendering frames onto webpage).*

My django code:def gen(request): if request.method == 'POST': try: video_file = request.FILES["video"] if video_file: video_filename = "temp_video.mp4" video_filepath = os.path.join(settings.STATIC_ROOT, video_filename) with open(video_filepath, 'wb') as destination: for chunk in video_file.chunks(): destination.write(chunk) video_cap = cv2.VideoCapture(video_filepath) if not video_cap.isOpened(): print("Error: Could not open video file") return "Error in processing video." while True: ret, frame = video_cap.read() if not ret: break else: #cv2.imshow("output",frame) tried this too but not working. frame_bytes = frame.tobytes() yield (b'--framern' b'Content-Type: image/jpegrnrn' + frame_bytes + b'rnrn') else: print("no video file") except Exception as e: print("An error occurred:", e) return "An error occurred while processing the video." def process_video(request): return StreamingHttpResponse(gen(request),content_type='multipart/x-mixed-replace; boundary=frame')

My javascript(in html file):-<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script> document.getElementById('uploadForm').addEventListener('submit', function (event) { event.preventDefault(); // Prevent default form submission behavior const formData = new FormData(this); fetch(this.action, { method: this.method, body: formData}) .then(response => { // Handle response // Define a function to handle each frame received function handleFrame(frameUrl) { // Create a new image element var img = $('<img>') .attr('src', frameUrl) .attr('height', '100px') .attr('width', '100px'); $('#video-display').empty().append(img);} // Create a function to process the streaming response function processResponse(response) { var contentType = response.headers.get('content-type'); if (contentType && contentType.indexOf('multipart/x-mixed-replace') !== -1) {const reader = response.body.getReader(); async function read() { while (true) { // Read the next chunk const { done, value } = await reader.read(); // If the chunk is done, break the loop if (done) { break;} // Convert the chunk to a blob and create a URL for it const blob = new Blob([value], { type: 'image/jpeg' }); const imageUrl = URL.createObjectURL(blob); // Handle the frame handleFrame(imageUrl);}} // Start reading chunks read();}} // Process the streaming response processResponse(response);}) .catch(error => { console.error('Error:', error);});}); </script>
My html:-

{% load static %}
<!DOCTYPE html>
<form class="home-form" id="uploadForm" action="{% url 'process_video' %}" method="post"
                        enctype="multipart/form-data">
                        {% csrf_token %}
                        <input type="file" accept="video" id="video-file" name="video"
                            placeholder="Enter your video here" class="home-input input" />
                        <div class="home-container08">
                            <button type="reset" class="home-button button">
                                <span>
                                    <span>Reset</span>
                                    <br />
                                </span>
                            </button>
                            <button type="submit" class="home-button1 button">Submit</button>
                        </div>
                    </form> <div id="video-display" class="home-container16">
                </div>

My terminal:-

February 19, 2024 - 16:04:33
Django version 5.0.2, using settings 'final.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

[19/Feb/2024 16:04:50] "GET / HTTP/1.1" 200 9358
[19/Feb/2024 16:05:07] "POST /process-video/ HTTP/1.1" 200 846041346

urls.py in my app:-

from django.urls import path
from . import views
urlpatterns= [
    path("",views.home,name="home"),
     path('process-video/', views.process_video, name='process_video'),]

urls.py in django project:-

from django.contrib import admin
from django.urls import path,include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("myapp.urls"))
]
# Add staticfiles_urlpatterns to urlpatterns
urlpatterns += staticfiles_urlpatterns()

The output was like this enter image description here
This is my file structure enter image description here

The icon image was updating too but the images are not being displayed, the video is being stored in static files as expected too.

please help me out. thanks in advance.

Sequelize Models, registered, synced, but how to do CRUD-Operations?

i used a course on udemy to make my first steps with sequelize: https://github.com/DavidArmendariz/sequelize-course/tree/master

Because I only want to use ES-Modules I had to make a few adjustments.

My register models Code:

import Quote from './quote.js';
import Variant from './variant.js';
import Version from './version.js';
import Log from './log.js';

let imports = [Variant, Version, Log, Quote]; 
let models = {};

export function registerModels(sequelize) {
  
  imports.forEach((item) => {
    models[item.constructor.name] = item(sequelize);
  } ) 
  
  

  sequelize.models = models;
}

export default models;

The models are ES6-Classes. For example:

import { Model, DataTypes } from 'sequelize';

export default (sequelize) => {
  class Log extends Model {
    static associate(models) {
      Log.Quote_id = Quote.hasOne(models.Version);
    }

    static async newEntry() {
      return sequelize.transaction(async() => {
        // here we put all the logic, when we create a new quote
        await Log.create({queueMicrotaskuote_id, user, action});

      })
     }

  }

  Log.init({
    id:{
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
  },
  quote_id: {
      type: DataTypes.INTEGER,
      allowNull: false
  },
  user: {
      type: DataTypes.INTEGER,
      allowNull: false
  },
  action: {
      type: DataTypes.TEXT,
      allowNull: false
  }
  }, { sequelize, modelName: 'Log' }
  );
  return Log;
}

After registering the models I sync it, and get tables in my database:

// Register the models
    registerModels(this.connection);

    // Sync the models
    await this.sync();
  }

My Problem

Now I want to use that class and it´s methods:

import { Router } from 'express';
import Quote from '../models/quote.js';
import asyncWrapper from '../utils/asyncWrapper.js';

const router = Router();

router.get('/', asyncWrapper(async (req, res) => {

  await Quote.addQuote();
  return res.status(200).send({success: true})

}))

export { router };

This is just an example, i don´t want to add a quote with a get request. Error:
Quote.addQuote is not a function

The original Code from the course (example):

import { Router } from 'express';
import models from '../../models';
import asyncWrapper from '../../utils/asyncWrapper';
import JWTUtils from '../../utils/jwt-utils';

const router = Router();
const { User } = models;

router.post(
  '/register',
  asyncWrapper(async (req, res) => {
    const { email } = req.body;
    const user = await User.findOne({ where: { email } });

    if (user) {
      return res
        .status(200)
        .send({ success: false, message: 'User already exists' });
    }

    const payload = { email };
    const accessToken = JWTUtils.generateAccessToken(payload);
    const refreshToken = JWTUtils.generateRefreshToken(payload);
    await User.createNewUser({ ...req.body, refreshToken });

    return res.status(200).send({
      success: true,
      message: 'User successfully registered',
      data: {
        accessToken,
        refreshToken,
      },
    });
  })
);

export default router;

I usually code PHP and my experience with JS is limited to client-side use.
So I would very much appreciate every help to get this work, and understand where I did things wrong.

programmatically focused link gets focused, but the style doesn’t apply

I want to focus a link programmatically. The following stackblitz shows the behavior:

https://stackblitz.com/edit/angular-9jocb8?file=src%2Fmain.ts,package.json

if you click on the button, the link should get focused. It actually gets the focus, but you cannot see it.
If you change the code, so the button focuses the nearby input field, everything works well.
One more thing I noticed is that when the focus is actually on the button when you click it, the focus on the link works perfectly fine.

Steps to reproduce:

  • Open the link
  • click on the button

Expected Behavior: Link is visually focused

Actual Behavior: Link is focused, but you cannot see it (tab back and forth shows the actual focus)

Does anyone know how to fix this problem?

I simplified the example a bit, in my real app I want to focus a link inside an innerHtml div in the onInit hook (or any other angular hook – none worked for me). So I just render a component with a div that gets filled by a server response. The server response includes a link and I want to focus the first link when the component is initialized.

The relevant code looks like this:

@Input
message: string;

ngOnInit(): void {
  setTimeout(() => {
    document.querySelector<HTMLLinkElement>('.some-container a')?.focus();
  }, 0);
}

the html:

<div #someId [innerHTML]="message" aria-live="assertive" class="some-container" role="alert">
</div>

the component only gets rendered, when message is filled (*ngIf="message" when using the component in its parent)

Passing rendered string to exec() doesn’t escape ` ” `

I have a nunjucks template. When I render it, I get the following string =>

something something '{"firstName": "john", "lastName": "doe", "age": 12}'

But when i pass it to exec() it’s treated as =>

something something '{firstName: john, lastName: doe, age: 12}'

Is there a way to avoid that?

Sample code =>

function getCommand(){
    // render template
    return renderedString;
}

const command = getCommand();
exec(command);

How to fix ffmpeg,js length error in react-js project | fix error in react project

I’ve tried to import the ffmpeg js library into my react-typescript project, I can’t really update my project’s react version or react-scripts due to the current code base.

Error

./node_modules/@ffmpeg/ffmpeg/dist/umd/ffmpeg.js
TypeError: [email protected]: Cannot read properties of undefined (reading 'length')

Code

import React, { useEffect, useRef, useState } from 'react';
import { FFmpeg } from '@ffmpeg/ffmpeg';

/* MORE CODE HERE */

const ffmpeg = new FFmpeg();
const baseURL = 'https://unpkg.com/@ffmpeg/[email protected]/dist/umd';
const coreURL = `${baseURL}/ffmpeg-core.js`;
const wasmURL = `${baseURL}/ffmpeg-core.wasm`;
const coreData = await fromURLToBlob(coreURL);
const wasmData = await fromURLToBlob(wasmURL);
const coreBlob = new Blob([coreData], { type: "text/javascript"});
const wasmBlob = new Blob([wasmData], { type: "application/wasm"});
await ffmpeg.load({
    coreURL: fromBlobToURL(coreBlob),
    wasmURL: fromBlobToURL(wasmBlob),
});       

/* MORE CODE HERE */

Versions

npm v8.19.4
node v16.20.2

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.4",
    "@emotion/styled": "^11.10.4",
    "@ffmpeg/ffmpeg": "^0.12.10",
    "@material-ui/core": "^4.12.3",
    "@mui/base": "^5.0.0-beta.36",
    "@mui/icons-material": "^5.10.3",
    "@mui/material": "^5.15.10",
    "@mui/x-data-grid": "^6.19.2",
    "@mui/x-data-grid-pro": "^6.19.2",
    "@reduxjs/toolkit": "^1.8.5",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "@toast-ui/editor": "^3.1.3",
    "@toast-ui/react-editor": "^3.1.3",
    "@types/jest": "^29.0.1",
    "@types/node": "^18.7.17",
    "@types/react": "^17.0.49",
    "@types/react-dom": "^18.0.6",
    "@zalando/oauth2-client-js": "^0.0.18",
    "ajv": "^8.12.0",
    "ajv-errors": "^3.0.0",
    "apexcharts": "^3.28.1",
    "arraybuffer-concat": "^0.0.1",
    "axios": "^1.4.0",
    "base64-blob": "^1.4.1",
    "bootstrap": "^5.1.1",
    "datetime-diff": "^0.2.1",
    "fuzzy-time": "^1.0.7",
    "jquery": "^3.6.0",
    "jso": "^4.1.1",
    "luxon": "^2.3.0",
    "pretty-bytes": "^5.6.0",
    "react": "^17.0.2",
    "react-apexcharts": "^1.3.9",
    "react-beautiful-dnd": "^13.1.0",
    "react-bootstrap": "^2.0.0-rc.0",
    "react-dom": "^17.0.2",
    "react-export-excel": "^0.5.3",
    "react-facebook": "^9.0.12",
    "react-helmet": "^6.1.0",
    "react-icons": "^4.3.1",
    "react-media-recorder": "^1.6.6",
    "react-notifications": "^1.7.2",
    "react-pages": "^0.4.4",
    "react-redux": "^7.2.8",
    "react-router": "^5.2.1",
    "react-router-dom": "^5.2.1",
    "react-scripts": "4.0.3",
    "react-toastify": "^8.0.2",
    "react-tooltip": "^4.2.21",
    "react-webcam": "^6.0.0",
    "recharts": "^2.1.8",
    "redux": "^4.2.0",
    "redux-thunk": "^2.4.1",
    "typescript": "^4.8.3",
    "web-vitals": "^1.1.2",
    "website-popup": "^3.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "set NODE_OPTIONS=--max-old-space-size=4096 && react-scripts build --GENERATE_SOURCEMAP=false",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6"
  }
}

How to disable checkboxes universally for all languages using CSS?

I have a web application with checkboxes that I want to universally disable using CSS, regardless of the language displayed on the page. I initially used the following CSS to disable checkboxes with specific aria-label attributes, but it does not work for all languages:

label[aria-label="Select All"] {
  display: none;
  pointer-events: none;
}

I want to disable checkboxes for all languages without considering the text content. How can I achieve this using CSS?

Here is an example of a label in French which is still visible.

<label class="label_label__1lyg41o0 base_componentBase__159h7ep0 label_variant_regular__1lyg41o1 checkbox_checkbox__1tqnmmh3 base_componentBase__159h7ep0" aria-label="Sélectionner tout"

Deployed version not showing correct responsive design

I have a web app made with React.
Basically the navbar is causing issues. I am using conditional rendering to trigger responsiveness in the navbar. It is working fine on the local host but the deployed version is triggering the mobile navbar for pcs and vice versa.
Here is how it looks on the local host. The mobile version:

local mobile version
The pc version:
local pc version
Which is how it is supposed to work.

This is the deployed version. The mobile version:
deployed mobile version
And the pc version:
deployed pc version

This is the code for header:


function Header({scrolling}) {

  var [isBurger, setIsBurger] = useState(false);
  var [isNav, setIsNav] = useState(false);
  var [isSearchBar, setIsSearchBar] = useState(false);
  var [isScreenSize, setIsScreenSize] = useState(0);

  

  const { width } = useWindowSize();

  //Nav button-----------------------------------
  var handleClickOnBurger = () => {
    setIsBurger((prevIsBurger) => !prevIsBurger);
    setIsNav((prevIsNav) => !prevIsNav);
  }


  //-----------------------------------------------
  //Search bar ------------------------
  var handleClickOnSearch = () => {
    setIsSearchBar((prevIsSearchbar) => !prevIsSearchbar)
  }
  //-----------------------------------
  function checkWidth() {
    if (isScreenSize >= 768) {
      setIsSearchBar(false);
      setIsBurger(false);
      setIsNav(true);
    }
  }

  useEffect(() => {
    setIsScreenSize(width);
    checkWidth();
  });
  return (
    <div className="d-flex flex-row flex-wrap justify-content-between align-items-center py-md-4 px-md-5 my-3 shadow-sm headerBody">
      <Navbar callFunc={handleClickOnBurger} btnHook={isBurger} navHook={isNav}
      scroller={scrolling}
      />
      {!isSearchBar && <Logo />}
      <Searchbar callFunc={handleClickOnSearch} btnHook={isSearchBar} />
    </div>
  );
}

function useWindowSize() {
  // Initialize state with undefined width/height so server and client renders match

  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

  useEffect(() => {
    // Handler to call on window resize
    function handleResize() {
      // Set window width/height to state
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }

    // Add event listener
    window.addEventListener("resize", handleResize);

    // Call handler right away so state gets updated with initial window size
    handleResize();

    // Remove event listener on cleanup
    return () => window.removeEventListener("resize", handleResize);
  }, []); // Empty array ensures that effect is only run on mount


  return windowSize;
}

export default Header;

This is the navbar:

import NavigationLinks from "./NavigationLinks";
import { Icon } from "@iconify/react";



function Navbar(props) {

    var icon;
    var burgerIcon = "iconamoon:menu-burger-horizontal-bold";
    var xIcon = "tabler:x";

    const navBarLinks = [
        {
            text: "home",
            path: "/#heroHome"
        },
        {
            text: "about",
            path: "/#about"
        },
        {
            text: "for partners",
            path: "/#partners"
        }
    ]
    const styleMid = "visibilityHiddenMid";
    const styleSmall = "visibilityHiddenSmall navbarSmall";
    var styleFinal;
    


    return (
        <>
            <span className="visually-hidden">
                {styleFinal = props.btnHook ? styleSmall : styleMid}
                {icon = props.btnHook ? xIcon : burgerIcon}
            </span>
            <button className="bg bg-transparent ms-2 border border-0 visibilityHiddenSmall"
                onClick={props.callFunc}
            >
                <Icon icon={icon}
                    className="color text-black fs-1 fw-lighter bg-transparent" />
            </button>
            <div className={"col-12 col-md-4 " + styleFinal}>


                <div
                    className="d-flex flex-column flex-md-row justify-content-start justify-content-md-left mx-3 my-4 my-md-0 align-items-strat align-items-md-center">
                    {navBarLinks.map((link, index) => {
                        return (<NavigationLinks text={link.text} path={link.path} key={index} />)

                    })}

                </div>
            </div>
        </>
    );
}

export default Navbar;

Search bar is somewhat similar to this code as well. If I can correct navbar, then I can correct the search bar as well.

At first I thought this was due to me not passing keys. However, even after providing keys it was not fixed.

From what I can tell, the state hooks are not properly being set in the deployed version. I do not have any idea why it is doing that when it is working on local version.

If a table is fed to the DataTable() constructor, can I get the DataTable instance from the table?

I am working with a large legacy application. It uses the DataTables jQuery plugin, and at some point — somewhere — a DataTable is created, impacting the content of a table whose ID I know.

Unfortunately, I cannot easily find where in the application the DataTable is being defined. I’ve grepped all over the place for the string new DataTable(, and I simply cannot locate it.

So my question is this: If I want to apply a callback to an event — in this case, the draw event — on my DataTable, is there a way I can get the DataTable instance from the table DOM object itself?

Here’s what I’ve tried (which does not work, as there is no property called dataTable):

var myTable = $('#myTable')[0];
var myDataTableInstance = myTable.dataTable;
myTable.on('draw', function () {
    console.log('Redraw occurred at: ' + new Date().getTime());
});

I’m assuming there might be a way to do this. I’m just not seeing it when I dump out myTable in the console.