Imitate webserver for tests with Jest

I have a bit of a weird question: I have a program for scraping data from webpages (just the actual HTML pages, not API responses).

I need to write end-to-end tests for this program with the Jest library. In order to test the functionality consistently, I need to make sure that the referred web pages don’t change, which would be almost impossible to achieve with resources on the web.

I wondered how good of a practice it is to spin up a new webserver locally with express/fastify/etc. to serve static HTML pages before running the tests and then shut the server down once the tests pass.

What I am looking for is a light web server with a single task – serve static html+css pages.
Are there any better ways to achieve what I mentioned? Thank you in advance!

How to insert image in table JS

I need create a table with rows

ID | Image | Info about image

and it’s a code:

<form>
        <input type = "text" name="info">
        <input type = "file" name = "pic" accept="image/png, image/jpeg">
        <input type = "button" onclick="add(this.form)" value = "Add" /> <br>
        <input type = "button" onclick="del(this.form)" value = "Clear" />
    </form>
    <script>
        function add(form)
        {
            table1 = getElementById('mytable');
            row1 = table1.insertRow(table1.rows.length);
            cell1 = row1.insertCell(row1.cell.length);
            cell1 = row1.rowIndex;
        }
    </script>

I coded only ID. Now I need to insert picture. And I don’t know how to do it…

React executing code before the previous function call has finished

I’m trying to write a record to a database but need to find the next Id in the sequence. I wrote a function to find the highest Id number in the database, increment it and return it.

The calling function then uses that to write the new record. Problem is that it is calling the write function before the maxIDFetch function has completed and returned the variable.

I’ve tried loads of different combinations but I can’t get it to work. Please help

Calling function

function AddNewMember({forename,surname}) {
    const nextId=maxIDFetch();
      writePlayer(true, {
      id: nextId,
      id: uuidV4(),
      forename
    });
  }

maxIDFetch function

import { useState, useEffect } from "react";
import setNewMember from "../App";
import writeMax from "./writeMax";

const CosmosClient = require("@azure/cosmos").CosmosClient;
const configMemberIDConnection = require("../configMemberIDConnection");
const dbContext = require("../contexts/databaseContext");

export default async function maxIDFetch() {
  const { endpoint, key, databaseId, containerId } = configMemberIDConnection;
  const client = new CosmosClient({ endpoint, key });
  const database = client.database(databaseId);
  const container = database.container(containerId);

  try {

    const querySpec = {
      query: "SELECT VALUE MAX(c.memberidnum) from c",
    };

    const { resources: items } = await client
      .database(databaseId)
      .container(containerId)
      .items.query(querySpec)
      .fetchAll();

    let newMax = Number(items) + 1;
    writeMax(newMax);
    return newMax;
    //  console.log(items);
  } catch (err) {
    console.log(err.message);
  }
}

Passport.js Spotify Strategy Only WORKS For A Single User, FAILS To Fetch Other Users’ Profiles

So I am using passport.js to authenticate my users, and the setup works….. but only for one user, (which is my Spotify account). When I tried to login/register with other Spotify accounts I always get the error “InternalOAuthError: failed to fetch user profile”. The error doesn’t really give me any insight to where the problem could be occurring so I troubleshot the best I could. Some troubleshooting I did:

  1. I removed the working account to see if maybe it was something about account limits on Spotify’s side.
  2. I checked to see if the credentials I provided I supplied were incorrect.
  3. I thought maybe it had to do with the fact that I didn’t have a session store initialized, but when established the error persisted.
  4. And my final, and ultimate, attempt… I StackOverflowed but bore no fruit 🙁 I couldn’t even find a post of someone having the same problem.

Here’s my relevant code:

***PASSPORT.JS***

const db  = require('../models');
const passport = require('passport');
require('dotenv').config();
const { nanoid } = require('nanoid');



const SpotifyStrategy = require('passport-spotify').Strategy;

passport.serializeUser((user, done)=>{
    done(null, user);
});
passport.deserializeUser((user, done)=>{
    done(null, user);
});

passport.use(

  new SpotifyStrategy(
    {
      clientID: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      callbackURL: 'http://localhost:5000/authorize',
    },
    async (accessToken, refreshToken, expires_in, profile, done)=> {
    try {
        console.log(accessToken); // this is just getting access tokens without having to make ui 
        db.User.findOrCreate({where: {email: profile.emails[0].value},
            defaults:{
                user_id: nanoid(),
                display_name: profile.displayName,
                profile_img: profile.photos[0].value,
                refresh_token: refreshToken
            }
        }).then((data)=>{
            const [user, created] = data;
            return done(null, user);
        });
    } catch (error) {
        return done(error);
    }
}));

***APP.JS***

const express = require('express');
const app = express();
const auth = require('./routes/auth');
const regLogin = require('./routes/regLogin');
const suggestion = require('./routes/suggestion')
const cors = require('cors');
const { corsOptions } = require('./corsOptions/config');
const passport = require('passport');
const session = require('express-session');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const db = require('./models');
require('dotenv').config();
import('./passport/passport.mw.js');


app.use(cors(corsOptions));



app.use(express.urlencoded({extended: false}));
app.use(express.json());

const store = new SequelizeStore({ db: db.sequelize })

app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    store: store,
    cookie:{
        maxAge: 1000 * 60 * 60 * 24
    }
}));

store.sync();

app.use(passport.initialize());
app.use(passport.session());


app.use('/authorize', auth);
app.use('/registration', regLogin);
app.use('/suggestion', suggestion);

app.get('/logout', function(req, res){
    req.logout();
    res.redirect('/authorize/passport');
});


const PORT = process.env.PORT || 5000;
app.listen(PORT, ()=>{
    console.log(`listening on port: ${PORT}`)
});

Why doesn’t this code update “All is well” to “Red Alert: hit by phaser fire!”

Why doesn’t this code update “All is well” to “Red Alert: hit by phaser fire!”?

What is wrong with it? I did it like the book’s instruction, but don’t get the expected result.

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Planets</title>
        <script>
            var planet;
            function init() {
                var Planet = document.getElementById("greenplanet");
                planet.innerHTML = "Red Alert: hit by phaser fire!";
            }
            window.onload= init;
        </script>
    </head>
    <body>
        <h1>greenplanet</h1>
        <p id="greenplanet">All is well</p>
        <h1>redplanet</h1>
        <p id="redplanet">Nothing to report</p>
        <h1>blueplanet</h1>
        <p id="blueplanet">All system A-OK</p>
    </body>
    </html>

How can I track and send custom events with the new Google Analytics 4?

I have an old website that’s using the old Google Analytics code from last decade, and I need help using the new GA4.

Old Code (2016)

To send custom events and pageviews to Google, I would use the global ga() function from their <script> snippet:

// Event
ga('send', 'event', {
    eventAction: 'click',
    eventCategory: 'social',
    eventLabel: 'twitter'
});

// Pageview
ga('send', {
    hitType: 'pageview',
    page: 'Video page',
    title: 'Intro video'
});

New Code (2022)

Google Analytics says that all old properties will stop working on July 1, 2023, so we need to switch to the new Google Analytics 4 property, the <script> snippet in the header has changed a bit, now it creates gtag():

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=X-XXX123456"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'X-XXX123456');
</script>

But upon trying to use gtag("send") like I used to, it looks like nothing gets transmitted to Google anymore. I’ve tried looking it up, but all tutorials/articles still demonstrate the old approach. How can I send custom events using the new GA4?

fetching from an api – state react context

I am working on an app that fetches current weather for a specified location.

I want to display current time but i have to use “splice()” method to get rid of the first part of the string that looks like this: “localtime: ‘2022-05-12 13:39’ “.

The problem is with useEffect() and states in the context file.

import axios from "axios";
import { createContext, useEffect, useState } from "react";

const Context = createContext({
  weather: {},
  place: {},
});

export const ContextProvider = ({ children }) => {
  const [weather, setWeather] = useState({});
  const [place, setPlace] = useState({});

  useEffect(() => {
    const getWeatherData = async () => {
      try {
        const request = await axios.get(
          "http://api.weatherstack.com/current"
        );

        const currentWeather = request.data.current;
        const currentPlace = request.data.location;

        setWeather(currentWeather);
        setPlace(currentPlace);
      } catch (err) {
        console.log(err);
      }
    };

    getWeatherData();
  }, []);

  console.log(weather);
  console.log(place);

  const context = {
    weather,
    place,
  };
  return <Context.Provider value={context}>{children}</Context.Provider>;
};

export default Context;

When i console.log my states (lines 33 & 34 in context file) i get this result:

result

So on the first render they’re undefined but then useEffect runs and update them.

I assume that this is why my “splice()” method does not work properly.

import styled from "styled-components";
import IconWind from "../icons/icon-wind";
import IconWindDirection from "../icons/icon-wind-direction";
// import IconHumidity from "../icons/icon-humidity";
import { useContext } from "react";
import Context from "../../store/context";

const WeatherDisplay = () => {
  const current = useContext(Context);

  const currentDay = new Date(current.place.localtime).toLocaleString("en-us", {
    weekday: "long",
  });

  const currentTime = current.place.localtime.splice(10);

  return (
    <Wrapper>
      <div>
        <PrimaryInfo>
          <h1>{current.place.name},</h1>
          <h2>{current.weather.temperature}°</h2>
          <p>
            {currentDay}, {currentTime}
          </p>
        </PrimaryInfo>
        <AdditionalInfo>
          <p>
            <IconWind /> Wind Speed: {current.weather.wind_speed}
          </p>
          <p>
            <IconWindDirection /> Wind Direction: {current.weather.wind_dir}
          </p>
          <p>Atmospheric pressure: {current.weather.pressure}</p>
          <p>Humidity: {current.weather.humidity}</p>
        </AdditionalInfo>
      </div>
    </Wrapper>
  );
};

const Wrapper = styled.section`
  width: 50%;
  border-radius: 10px 0 0 10px;

  & > div {
    height: 100%;
    padding-left: 4rem;
    display: flex;
    justify-content: center;
    flex-direction: column;
  }
`;

const PrimaryInfo = styled.section`
  margin-bottom: 10rem;
  h1 {
    font-size: 5rem;
  }

  h2 {
    font-size: 4rem;
    margin: 1rem 0rem;
  }

  p {
    font-size: 2.4rem;
  }
`;

const AdditionalInfo = styled.div`
  p {
    margin: 1rem 0rem;
    font-size: 1.2rem;

    display: flex;
    align-items: center;
  }
`;
export default WeatherDisplay;

splice logs

I tried to check if they already have content but still didnt work:

import styled from "styled-components";
import IconWind from "../icons/icon-wind";
import IconWindDirection from "../icons/icon-wind-direction";
// import IconHumidity from "../icons/icon-humidity";
import { useContext } from "react";
import Context from "../../store/context";

const WeatherDisplay = () => {
  const current = useContext(Context);

  let currentDay;
  let currentTime;

  if (current.place.length > 0 && current.weather.length > 0) {
    currentDay = new Date(current.place.localtime).toLocaleString("en-us", {
      weekday: "long",
    });

    currentTime = current.place.localtime.splice(10);
  }

  console.log( currentDay);
  console.log( currentTime);

  return (
    <Wrapper>
      <div>
        <PrimaryInfo>
          <h1>{current.place.name},</h1>
          <h2>{current.weather.temperature}°</h2>
          <p>
            {currentDay}, {currentTime}
          </p>
        </PrimaryInfo>
        <AdditionalInfo>
          <p>
            <IconWind /> Wind Speed: {current.weather.wind_speed}
          </p>
          <p>
            <IconWindDirection /> Wind Direction: {current.weather.wind_dir}
          </p>
          <p>Atmospheric pressure: {current.weather.pressure}</p>
          <p>Humidity: {current.weather.humidity}</p>
        </AdditionalInfo>
      </div>
    </Wrapper>
  );
};

const Wrapper = styled.section`
  width: 50%;
  border-radius: 10px 0 0 10px;

  & > div {
    height: 100%;
    padding-left: 4rem;
    display: flex;
    justify-content: center;
    flex-direction: column;
  }
`;

const PrimaryInfo = styled.section`
  margin-bottom: 10rem;
  h1 {
    font-size: 5rem;
  }

  h2 {
    font-size: 4rem;
    margin: 1rem 0rem;
  }

  p {
    font-size: 2.4rem;
  }
`;

const AdditionalInfo = styled.div`
  p {
    margin: 1rem 0rem;
    font-size: 1.2rem;

    display: flex;
    align-items: center;
  }
`;
export default WeatherDisplay;

It just displays currentDay and currentTime as unfefined.

What am i doing wrong?

How to restrict users to only be able to view a specific folder in a statically served filesystem? Express.js

I have an express application set up to use a filesystem which contains a folder for each user.

app.use(express.static(mainFolder));

The problem is that I can’t seem to restrict users from viewing each others files.

In account A, I have a folder for photos

mainFolder > AccountA > Photos > thePhoto.png

However, After I log into account B I can access this photo by typing in

localhost:8080/AccountA/Photos/thePhoto.png

I have already created a middleware to check that the user is logged in and this stops anyone not logged in from viewing the photo. Now I need a to restrict each user from viewing other accounts files/photos etc.

I am aware that I could do

app.use(express.static(mainFolder/accountA));

However I would have to this for each user. Could I put this in the authentication route so that after a user has authenticated the app uses this file?

I have also looked at How to serve user specific static content in Express.js and this does not help.

Here is the code for my middleware:

function checkAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next()
    } else if(req.url != "/login" && req.url != "/register" && req.url != "/register?" && req.originalUrl != "/register?" ){
        res.redirect('/login');
    } else if(req.url === "/login" || req.url === "/register" || req.url === "/register?" || req.originalUrl === "register"){
        return next()
    }
}

Here is my app.js

//------------------------------------------------------
//                 STORAGE SITE SERVER SIDE
//------------------------------------------------------
// Matthew Haywood

var path = require("path")
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var fs = require("fs-extra");
var methodOverride = require("method-override");
var passport = require("passport");
var session = require('express-session')
var flash = require('express-flash');
var bcrypt = require('bcryptjs');
var csv = require('csv-parser');
var schedule = require('node-schedule');
const { exec } = require('child_process');
var sanitizer = require('sanitize')();
var os = require('os-utils');
var addScheduledWorkflowFromFile = require('./routes/workflow/workflowRoutes').addScheduledWorkflowFromFile;
var middleware = require("./middleware/index");

var workflowRoutes = require('./routes/workflow/workflowRoutes').router;
var storageRoutes = require('./routes/storage/storageRoutes').router;
var codeRoutes = require('./routes/code/codeRoutes').router;

global.testFolder;

//Configure the app based on whether its development or production

if (process.env.NODE_ENV === 'production') {
    testFolder = '/media/pi/ELEMENTS B/';
    string_len = 22;
    production_flag = true
}

if (process.env.NODE_ENV === 'development') {
    testFolder = '/Users/matthaywood/Desktop/StorageSite/StorageSite/public/'
    string_len = 59;
}

//PASSPORT SETUP
const initializePassport = require('./passport-config');
const { stdout, allowedNodeEnvironmentFlags } = require("process");
const { timeStamp } = require("console");
const { ResultWithContext } = require("express-validator/src/chain");
initializePassport(
    passport,
    email => users.find(user => user.email === email),
    id => users.find(user => user.id === id)
)

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(flash())
app.use(session({
    secret: "Once again rusty is the cutest dog",
    resave: false,
    saveUninitialized: false
}))
app.use(passport.initialize());
app.use(passport.session());

app.use(methodOverride("_method"));

app.use(function (req, res, next) {
    res.locals.currentUser = req.user;
    next();
});

function checkAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next()
    } else if(req.url != "/login" && req.url != "/register" && req.url != "/register?" && req.originalUrl != "/register?" ){
        res.redirect('/login');
    } else if(req.url === "/login" || req.url === "/register" || req.url === "/register?" || req.originalUrl === "register"){
        return next()
    }
}

function checkUser(req,res,next){

    if(req.body.currentPath != undefined){
        console.log('CheckUser function ' + req.body.currentPath)
        var endDir = req.body.currentPath.replace(testFolder, '');
        var user = endDir.split('/')[1]
        if(user == req.user.name){
            console.log("USER " + user + " AUTHORISED FOR " + req.body.currentPath + " DIRECTORY")
            return next()
        } else {
            res.redirect("/Unauthorised");
            return "Failed";
        }
    } else {
        next();
    }
}

app.use(checkAuthenticated);
app.use(checkUser);

global.users = [];
global.scheduledWorkflows = []

//LOAD USERS IN FROM JSON FILE
var loadedData = JSON.parse(fs.readFileSync("users.json"))
console.log(loadedData.Users)
users = loadedData.Users
addScheduledWorkflowFromFile()

app.use(express.static(__dirname + "/public"));
app.use('/modules', express.static("modules"));


app.use("/", workflowRoutes);
app.use("/", storageRoutes);
app.use("/", codeRoutes);
    
//----------------------------------------------------------
//                          ROUTES
//----------------------------------------------------------

app.get("/", function (req, res) {
    res.render("clusterHome.ejs");
})

//Settings Route for displaying current connected HDD
app.get("/settings", function (req, res) {
    res.render("settings.ejs");
})

//--------------------------------------------------------------------
//                  ROUTES FOR USERS AND LOGIN 
//--------------------------------------------------------------------

//Register 
app.get("/register", function (req, res) {
    res.render("register.ejs");
})

app.post("/register", function (req, res) {
    var password = req.body.password;
    // var name = sanitizer.value(req.body.name,String);
    var name = req.body.name;
    // var email = sanitizer.value(req.body.email,String);
    var email = req.body.email;
    var the_hash;

    console.log('CREATING NEW ACCOUNT')

    bcrypt.hash(password, 10, function (err, hash) {

        console.log(err)

        the_hash = hash;
        the_id = Date.now().toString();
        users.push({
            id: the_id,
            name: name,
            email: email,
            password: hash
        })
        fs.mkdirSync(testFolder + name);
        fs.mkdirSync(testFolder + name + "/" + "Workflows");
        fs.mkdirSync(testFolder + name + "/Workflows/Logs" );
        fs.mkdirSync(testFolder + name + "/" + "Code");

        var data = JSON.parse(fs.readFileSync("users.json"))

        data.Users.push({
            id: the_id,
            name: name,
            email: email,
            password: hash
        })

        data = JSON.stringify(data, null, 2)
        fs.writeFileSync("users.json", data)

        passport.authenticate('local')(req, res, function () {
            res.redirect("/");
        })

        if (err) {
            console.log(err)
            res.redirect('/register');
        } 
    })
})

//----------------------------------------------------------
//                   LOGIN/LOGOUT ROUTES
//----------------------------------------------------------

app.get("/login", function (req, res) {
    res.render("login.ejs");
})

app.post("/login", passport.authenticate('local'), function (req, res) {
    app.use(express.static(testFolder+"/"+req.user.name));
    res.redirect("/");
})

//Logout
app.delete("/logout", function (req, res) {
    req.logOut();
    res.redirect('/login')
})

//Unauthorised Route
app.get("/unauthorized", function(req, res){
    res.render("unauthorised.ejs");
})

//----------------------------------------------------------
//                  LOG ROUTES
//----------------------------------------------------------

app.get("/logs", function (req, res) {
    res.render("logs.ejs")
})

app.get("/logs/get-data", function (req, res) {
    os.cpuUsage(function (v) {
        res.status(200).send({ cpuUsage: v })
    });
})

//----------------------------------------------------------
//                  AUTO GIT PULL SCHEDULE
//----------------------------------------------------------

//Only run this job if in production to pull from github

if (process.env.NODE_ENV === 'production') {
    const job = schedule.scheduleJob('*/5 * * * *', function () {
        exec('git pull', (err, stdout, stderr) => {
            if (err) {
                console.log(err);
            } else {
                console.log("Pulling from git repository")
                console.log(stdout)
                //Restart server if git has pulled changes
                if(!stdout.includes("Already up to date.")){
                    process.exit(1)
                }
            }
        })
    })
}

function serverLog(string){
    //function used to log to a file

    
}

app.listen("8080");

Warning: Text content did not match in React 18

recently the project I am working on has been upgraded to React 18. By then, suddenly a lot of issues with hydration have started to appear as warnings/errors in the console. The one I’m struggling with is “Warning: Text content did not match”:

enter image description here

Code of this component:

 <div className="O75-product-faq__questions is-active accordion--initialized">
                            {
                                dataForSelect.length > 1 && <h4 className="O75-product-faq__questions__name js-category-name">{props.questionsByCategories[selectedCategory?.value].name}</h4>
                            }
                            {
                                props.questionsByCategories[selectedCategory?.value].questions.map((element, i) => (
                                    <div key={i} className="O75-product-faq__questions__item">
                                        {(element.question || props.showOnlyAnswer) && <div className={`O75-product-faq__questions__item__button${openedElement === i ? ' has-accordion-open' : ''}`} onClick={() => openElement(i)}>{element.question}</div>}
                                        <AnimateHeight height={openedElement === i ? 'auto' : 0} duration={transitionDisabled ? 0 : 400}>
                                            <div className="O75-product-faq__questions__item__content" dangerouslySetInnerHTML={{ __html: element.answer }} />
                                        </AnimateHeight>
                                    </div>))
                            }
                        </div>

I know that this issue results from the difference between client and server side rendering, but I don’t know how to fix it and no other similar question contained solution that worked in my case.

Rest of the file, in case if the issue is not with aforementioned part:

import React, { useMemo, useState } from 'react';
import type { ReactElement } from 'react';
import AnimateHeight from 'react-animate-height';
import { BaseSelect, SelectOption } from '../molecules/base-select';
import type { FrequentlyAskedCategory } from './frequentlyAskedQuestion';
import { fromBase64 } from '../shared-services/base64Service';

interface FaqPanelProps {
    mainTitle?: string;
    menuTitle?: string;
    showOnlyAnswer: boolean;
    currentPageUrl: string;
    questionsByCategories: Record<string, FrequentlyAskedCategory>,
    faqStructuredDataBase64: string;
}

const FAQPanel = (props: FaqPanelProps): ReactElement => {
    const categories = Object.keys(props.questionsByCategories);
    const dataForSelect: Array<SelectOption> = categories.map(key => ({ label: props.questionsByCategories[key].name, value: key }));
    const noOpenedElementIndex = -1;

    const [openedElement, setOpenedElement] = useState<number>(-1);
    const [selectedCategory, setSelectedCategory] = useState<SelectOption>(dataForSelect.length > 0 ? dataForSelect[0] : null);
    const [transitionDisabled, setTransitionDisabled] = useState<boolean>(false);
    const parsedStructuredData = useMemo(() => {
        if(props.faqStructuredDataBase64 != null && props.faqStructuredDataBase64 !== ""){
           return fromBase64(props.faqStructuredDataBase64);
        }

        return "";
    }, [props.faqStructuredDataBase64]);

    const selectNewCategory = (option: SelectOption): void => {
        setTransitionDisabled(true);
        setOpenedElement(noOpenedElementIndex);
        setSelectedCategory(option);
    }

    const openElement = (index: number): void => {
        if (transitionDisabled) {
            setTransitionDisabled(false);
        }
        setOpenedElement(index === openedElement ? noOpenedElementIndex : index);
    }

    const speakableJson = JSON.stringify({
        "@context": "https://schema.org/",
        "@type": "WebPage",
        "name": props.mainTitle,
        "speakable":
            [".O75-product-faq__headline",
                ".O75-product-faq__questions__item"],
        "url": props.currentPageUrl
    });

    const hasFAQStructuredData = parsedStructuredData != null && parsedStructuredData !== "";
    return (
        <div className="container">
            <section className="O75-product-faq" >
                {
                    props.mainTitle
                        ? <h2 className="O75-product-faq__headline">{props.mainTitle}</h2>
                        : <h4 className="O75-product-faq__categories-headline">{props.menuTitle}</h4>
                }
                <div className="flex">
                    {dataForSelect.length > 1 &&
                        <div className="O75-product-faq__categories">
                            <div className="filter__list is-hidden-sm filter">
                                {
                                    dataForSelect.map((element, i) => (
                                        <button className={`filter__btn js-filter__btn${element.value === selectedCategory?.value ? " is-active" : ""}`} key={i} onClick={() => selectNewCategory(element)}>
                                            {element.label}
                                        </button>))
                                }
                            </div>
                            <div className="filter__group is-hidden-md">
                                <BaseSelect selectedValue={selectedCategory}
                                    handleChange={selectNewCategory}
                                    options={dataForSelect} />
                            </div>
                        </div>
                    }
                    {categories.length > 0 &&
                        <div  className="O75-product-faq__questions is-active accordion--initialized">
                            {
                                dataForSelect.length > 1 && <h4 className="O75-product-faq__questions__name js-category-name">{props.questionsByCategories[selectedCategory?.value].name}</h4>
                            }
                            {
                                props.questionsByCategories[selectedCategory?.value].questions.map((element, i) => (
                                    <div key={i} className="O75-product-faq__questions__item">
                                        {(element.question || props.showOnlyAnswer) && <div className={`O75-product-faq__questions__item__button${openedElement === i ? ' has-accordion-open' : ''}`} onClick={() => openElement(i)}>{element.question}</div>}
                                        <AnimateHeight height={openedElement === i ? 'auto' : 0} duration={transitionDisabled ? 0 : 400}>
                                            <div className="O75-product-faq__questions__item__content" dangerouslySetInnerHTML={{ __html: element.answer }} />
                                        </AnimateHeight>
                                    </div>))
                            }
                        </div>
                    }
                </div>
                {hasFAQStructuredData && <script suppressHydrationWarning type="application/ld+json" dangerouslySetInnerHTML={{__html:parsedStructuredData } }></script>}
                <script suppressHydrationWarning type="application/ld+json" dangerouslySetInnerHTML={{__html: speakableJson}} ></script>
            </section>
        </div>
    )
}

export { FAQPanel };
export type { FaqPanelProps }

Does anyone knows how to fix it?

scroll to the bottom when dynamic loading

I am trying to scroll to the bottom of the page via JS – https://airtable.com/embed/shrqYt5kSqMzHV9R5/tbl8c8kanuNB6bPYr?backgroundColor=green&viewControls=on

I tried several methods below but none does not work. To test this, you can run it in the chrome console window.

window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });

$('#html, body').scrollTop($('#html, body')[0].scrollHeight);

window.scrollTo(0, document.querySelector(".antiscroll-scrollbar").scrollHeight);

$('.antiscroll-scrollbar').scrollTop(120);

How can i do to access to an array which can be empty?

I am working with an array which can be empty or can have just one element. I tried that code but it does not work :

let myValue;
if(myArray.length === 0){
    myValue = 0}
else{
    myValue = myArray[0]
}

But I got the following error that myArray[0] is undefined.

How can I solve that ?

Thank you very much !