React: un-invoked useState variables unavailable in event handler in debugger

First ever SO question! Hope I’m doing this right.

Question is, when I am in an event handler’s debugger in browser (Chrome), why are useState variables unused by the event handler unavailable?

E.g. in debugger, testBoolean is unavailable. (In “Watch” tab, shows <not available> and in console, shows Uncaught ReferenceError: testBoolean is not defined).

If I comment out the console.log line, the count variable also becomes unavailable.

import { useState } from 'react';
import Game from './Game';

export default function App() {
    const [testBoolean, setTestBoolean] = useState(true);
    const [count, setCount] = useState(0);

    const handleClick = () => {
        setCount(c => c + 1);
        console.log(count);
        debugger
    }

    return (
        <div>
            <button onClick={handleClick}>Clicked {count} times</button>
        </div>
    )
}

Have tried searching e.g. react debugger unused useState variables not available in event handler but most threads I find deal with event handlers having stale useState values which is an entirely different topic. Some thoughts:

  • handleClick is an arrow function, so I believe it should close over other consts in the function component?
  • when handleClick is invoked, the component function has run and returned the virtual DOM elements, so the useState variables should have already been declared.

Looking forward to any insights, seems crucial to understanding event flow / React and would love to understand going forward. Thank you.

Issues with Image Handling and Form Submission in JavaScript Code

what is wrong with this when submitting?
I’m currently working on a library management website where the admin can add books through a form. I’m encountering several issues with image handling and form submission in my JavaScript code.

Here’s a breakdown of the problems I’m facing:

Image Handling in Form:

I’ve implemented functionality to allow the user to upload an image for the book cover. The image is displayed in the form upon upload, but I’m unsure how to properly save the uploaded image along with the book information and use it in another webpage.

Form Submission:

I want to ensure that each book has a unique ID before adding it to the book list. If the entered ID matches any existing IDs in the book list, I want to prevent form submission and prompt the user to enter a new ID. Despite implementing this validation, I encountered a strange behavior where form submission was allowed even when the ID matched an existing one, but only when window.location.href was uncommented.

Here’s a snippet of my JavaScript code:

// Image Handling
document.getElementById("upImg").addEventListener("change", function(event) {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = function(e) {
        const imgData = e.target.result;

        document.getElementById("img").setAttribute("src", imgData);

        sessionStorage.setItem("uploadedImageData", imgData);
    };

    reader.readAsDataURL(file);
});

// Form Submission
const addBookForm = document.getElementById('addBookForm');
if (addBookForm) {
    addBookForm.addEventListener('submit', function(event) {
        event.preventDefault();

        const bookID = document.getElementById("bookID").value;
        const isBookIDExists = booksList.some(book => book.id === bookID);
        if (isBookIDExists) {
            alert("Book ID already exists. Please enter a new ID.");
        } else {
            // Book details retrieval
            const bookName = document.getElementById("bookName").value;
            const author = document.getElementById("author").value;
            // Retrieve other book details similarly

            // Book creation
            const newBook = new Book(
                bookID,
                bookName,
                author,
                // Include other book details here
            );

            // Add book to the list
            booksList.push(newBook);

            // Inform user about book addition
            alert("Book added successfully!");

            // Redirect to allBooks.html after a slight delay
            setTimeout(function() {
                window.location.href = '../pages/allBooks.html';
            }, 1000);
        }
    });
}

Could you please assist me in resolving these issues? I’m particularly concerned about properly saving the uploaded image with the book information and ensuring accurate form submission validation. Thank you.

Additional Information:

This is only the frontend part of the application; backend integration will be handled later.
The Book class and booksList are imported from another module.
The Book object contains properties such as id, name, author, etc.
The booksList array holds instances of Book objects representing all books in the library.
`

Arrow buttons (Prev and Next) with breadcrumbs

I’m trying to build arrow buttons to navigate to Next and Prev pages with a breadcrumb path to show the user which page they are on. I can’t seem to get it right. The problems that I’m encountering is that the arrow buttons are not working rigth. The next button will only go to page 2 and not 3 or 4. The prev button don’t work at all and the breadcrumbs won’t display the pages you went to.

I tried this and it seem to work, but my arrow will disappear with this code:

const previousButton = document.querySelector(".arrow-button.previous");
const nextButton = document.querySelector(".arrow-button.next");
const breadcrumbs = document.querySelector(".breadcrumbs");

// Initial state (assuming you start on the first page)
let currentPage = 1;
const maxPages = 5; // Adjust this based on your actual number of pages

// Update breadcrumbs based on current page
function updateBreadcrumbs() {
breadcrumbs.innerHTML = ""; // Clear existing breadcrumbs

for (let i = 1; i <= currentPage; i++) {
const listItem = document.createElement("li");
const link = document.createElement("a");
link.textContent = `Page ${i}`; // Customize link text if needed
link.href = `#page-${i}`; // Set appropriate links for your pages

if (i === currentPage) {
  listItem.classList.add("active"); // Mark current page as active
  link.removeAttribute("href"); // Remove link for current page
}

listItem.appendChild(link);
breadcrumbs.appendChild(listItem);

 }
}

// Handle previous button click
previousButton.addEventListener("click", () => {
if (currentPage > 1) {
currentPage--;
updateBreadcrumbs();
// Handle page content transition here (e.g., using AJAX or DOM manipulation)
console.log(`Switched to page ${currentPage}`); // For demonstration purposes
}

// Disable previous button if on the first page
previousButton.disable = currentPage === 1;
});

// Handle next button click
nextButton.addEventListener("click", () => {
if (currentPage < maxPages) {
currentPage++;
updateBreadcrumbs();
// Handle page content transition here
console.log(`Switched to page ${currentPage}`);
 }

// Disable next button if on the last page
nextButton.disabled = currentPage === maxPages;
});

// Update breadcrumbs initially
updateBreadcrumbs();

I’ve also tried this:

const previousButton = document.querySelector(".left-arrow");
const nextButton = document.querySelector(".right-arrow");
const breadcrumbs = document.querySelector(".breadcrumbsDisplay");

 // Initial state (assuming you start on the first page)
let currentPage = 1;
const maxPages = 4; // Adjust this based on your actual number of pages
const pages = [
{ text: 'Home |', href: './index1.html' },
{ text: 'About |', href: './index2.html' },
{ text: 'Portfolio |', href: './index3.html' },
{ text: 'Contact |', href: './index4.html' },
]
// Handle previous button click
previousButton.addEventListener("click", () => {
if (currentPage > 1) {
currentPage--;
updateBreadcrumbs();
window.location.href = pages[currentPage-1].href;
}
 previousButton.disabled = currentPage === 1;
});

// Handle next button click
nextButton.addEventListener("click", () => {
if (currentPage < maxPages) {
currentPage++;
updateBreadcrumbs();
window.location.href = pages[currentPage-1].href;
}
nextButton.disabled = currentPage === maxPages;
});
// Update breadcrumbs based on current page
function updateBreadcrumbs() {
breadcrumbs.innerHTML = ""; // Clear existing breadcrumbs

for (let i = 1; i <= maxPages; i++) { // Change this line
const listItem = document.createElement("li");
const link = document.createElement("a");
listItem.classList.add("breadcrumb-item");
link.textContent = pages[i-1].text;
link.href = pages[i-1].href;

if (i === currentPage) {
  listItem.classList.add("active"); // Mark current page as active
  link.removeAttribute("href"); // Remove link for current page
}

listItem.appendChild(link);
breadcrumbs.appendChild(listItem);
 }
}

// Initial setup
updateBreadcrumbs();
previousButton.disabled = currentPage === 1;
nextButton.disabled = currentPage === maxPages;

Salesforce LWC using my own javascript file

I built a classic html page with lots of js features and wants to transfer it into Lwc version through uploaded static resource js file,
The uploaded css file as static resource works just fine.
But the js file doesn’t work. The js codes have lots of functions with perimeters and none function ones.

1/3. Here is my js file being uploaded:

    let Tag2  = document.querySelector(".myClass2"); 
    let date  = new Date(); 

    document.getElementById("myID").innerHTML = "Test 1: " +  date;
    Tag2.innerHTML = myFunction(date);

    function myFunction(dt){    
        dt = "Test 2: " +  dt 
        return dt             
    }

2/3. Here is my html of LWC version:

    <template>
        <lightning-card title="">
            <div class="myClass1">Here to test Css</div-->
            <div    id="myID">    Here is Test 1</div>
            <div class="myClass2">Here is Test 2</div>
        </lightning-card>  
    </template>

3/3. Here is my js of LWC version:

    import { LightningElement } from 'lwc';
    import File_CSS from '@salesforce/resourceUrl/my_file_css' 
    import File_JS from '@salesforce/resourceUrl/my_file_js' 
    import {loadScript, loadStyle} from 'lightning/platformResourceLoader'

    export default class myPage extends LightningElement {
    renderedCallback(){ 
            if(this.isLibLoaded){ 
                return
            } 
            else {      
                Promise.all([
                   loadScript(this, File_JS),               
                    loadStyle(this, File_CSS)                
                ])
                //.then(()=>{ this.setDateOnScreen() }) 
                .catch(error=>{ console.error(error) })

                this.isLibLoaded = true  
            }
        }
    }

I’m hoping to reuse the original js codes as much as possible.
Please help and thanks so much!

Using javascript to transform/manipulate data in google cloud dataform (sqlx)

im trying to use a javascript function to test if i can manipulate data in dataform from a query, however compilator says that “color” is not defined (one of the fields im trying to manipulate), I have not been able to find any example on how to do use the functions, only seen examples with js constants but not data manipulation, here is how I am trying (notice when im calling the function “addcolor” on the query SELECT):

config {
    type: "view",
    name: "available_bicycles_dataform"
}

SELECT
  ab.bicycle_id,
  ab.manufacturer,
  ab.color as color,
  ${addcolor(color)} AS added_color
FROM
  `learn-project.bicycles.available_bicycles` AS ab
LEFT JOIN
  `learn-project.bicycles_scheduled.scheduled_job_used_bicycles` AS abdf
ON
  ab.bicycle_id = abdf.bike_id
WHERE
  abdf.bike_id IS NULL


js {
    function addcolor(color) {
        return color + "hi";
    }
}

useState set method not changing my state – react native

I’m working on a part of an application dealing with a deck of cards. For however many cards a player is supposed to have, I am looping through a deck of cards held in a state, randomly picking a card, assigning it to that player and then removing it from the deck. This all works correctly but when the deck is empty (.length === 0), I want to invoke a shuffle() method that will set the deck equal to the discard pile which is also an array held in a useState. The discard pile is also working as expected but for some reason when trying to set the currentDeck to the discard pile, using setCurrentDeck(discardPile), the currentDeck array remains empty. (I’ve also tried setCurrentDeck([…discardPile])).

I know this mostly likely has to do with how React handles batching hook calls, and that the value of currentDeck is not what I think it is because of the other setCurrentDeck() calls, but I’m still not able to figure out what’s going on.

My code (simplified):

const [currentDeck, setCurrentDeck] = useState(deck) // 'deck' is a hard coded array of cards
const [discardPile, setDiscardPile] = useState([])
const [faceUpCard, setFaceUpCard] = useState(null)

  useEffect(() => {
    if (currentDeck.length === 0) {
      const temp = discardPile;
      setCurrentDeck([...temp]);
      setDiscardPile([]);
    }
  }, [currentDeck]);

  function deal() {
    if (readyToDeal) {
      for (let i = 0; i < round + 2; i++) {
        for (let j = 0; j < players.length; j++) {
          const rand = Math.floor(Math.random() * currentDeck.length);
          // players are assigned cards
          currentDeck.splice(rand, 1); // card that was assigned is removed from deck
          setCurrentDeck([...currentDeck]);
        }
      }
      const rand = Math.floor(Math.random() * currentDeck.length);
      setFaceUpCard(currentDeck[rand]);
      currentDeck.splice(rand, 1);
      setCurrentDeck([...currentDeck]);
      setReadyToDeal(false);
    }
  }

I have also tried setting currentDeck with a shuffle method like this:


  function shuffle() {
    const temp = discardPile;
    setCurrentDeck([ ...temp]);
    setDiscardPile([]);
  }

  function deal() {
    if (readyToDeal) {
      for (let i = 0; i < round + 2; i++) {
        for (let j = 0; j < players.length; j++) {
          if (currentDeck.length === 0) {
            shuffle();
          }
          const rand = Math.floor(Math.random() * currentDeck.length);
          // players are assigned cards
          currentDeck.splice(rand, 1); // card that was assigned is removed from deck
          setCurrentDeck([...currentDeck]);
        }
      }
      const rand = Math.floor(Math.random() * currentDeck.length);
      setFaceUpCard(currentDeck[rand]);
      currentDeck.splice(rand, 1);
      setCurrentDeck([...currentDeck]);
      setReadyToDeal(false);
    }
  }

but still no luck. Any help or advice would be appreciated. Thank you!

KINDE TWITTER LOGIN ERROR : Something went wrong. And honestly, we do not know what it was. Try starting a new session

Trouble Implementing Twitter Login with Kinde in Next.js

I’m facing an issue while trying to implement Twitter login using Kinde in a Next.js application. Here’s the error message I’m encountering: “KINDE TWITTER LOGIN ERROR: Something went wrong. And honestly, we do not know what it was. Try starting a new session.”

Click Here For Live Demo

Problem Description

I’ve integrated the Twitter login functionality into my Next.js application using Kinde. However, whenever I attempt to log in using Twitter credentials, I encounter the aforementioned error message. Despite extensive troubleshooting efforts, I haven’t been able to identify the root cause of this issue.

Code Snippets

Here are some relevant code snippets from my application:

#Navbar.tsx

import Link from "next/link";
import { ThemeToggle } from "../components/Themetoggle";
import { Button } from "@/components/ui/button";
import { RegisterLink,LoginLink } from "@kinde-oss/kinde-auth-nextjs/components";
export function Navbar() {
  return (
    <nav className="border-b bg-background h-[10vh] flex items-center">
      <div className="container flex items-center justify-between">
        <Link href="/">
          <h1 className="font-bold text-3xl">ABC</h1>
        </Link>

        <div className="flex items-center gap-x-5">
          <ThemeToggle />
          <div className="flex items-center gap-x-5">
            <LoginLink><Button>Sign in</Button></LoginLink>
            <RegisterLink><Button variant="secondary">Sign up</Button></RegisterLink>
          </div>
        </div>
      </div>
    </nav>
  );
}


#Layout.tsx

import type { Metadata } from "next";
import { Inter as FontSans } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "./components/theme-provider";
import { cn } from "../lib/utils";
import { Navbar } from "./components/Navbar";

const fontSans = FontSans({
  subsets: ["latin"],
  variable: "--font-sans",
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body
        className={cn(
          "min-h-screen bg-background font-sans antialiased",
          fontSans.variable
        )}
      >
        {" "}
        <ThemeProvider
          attribute="class"
          defaultTheme="system"
          enableSystem
          disableTransitionOnChange
        >
              <Navbar></Navbar>
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}

#.env
KINDE_CLIENT_ID=dfba5a3a*******************
KINDE_CLIENT_SECRET=OGLp********************************
KINDE_ISSUER_URL=https://**************-development.us.kinde.com
KINDE_SITE_URL=http://localhost:3000
KINDE_POST_LOGOUT_REDIRECT_URL=http://localhost:3000
KINDE_POST_LOGIN_REDIRECT_URL=http://localhost:3000/dashboard
  • Recreation of Project: I’ve tried recreating the entire project from scratch to rule out any potential configuration issues.
  • Verification of Callback URLs: I’ve thoroughly checked all callback URLs configured both in the Twitter Developer Portal and within Kinde to ensure they match.
  • Redoing Setup on Kinde: I’ve revisited the setup process on Kinde, double-checking all configuration settings related to Twitter authentication.

Additional Context

Despite these efforts, I’ve been unable to resolve the issue. It’s worth noting that I’m relatively new to integrating authentication systems into Next.js applications, so there might be nuances or best practices that I’m overlooking.

Request for Assistance

If anyone has encountered a similar problem or has suggestions on how to troubleshoot this further, I’d greatly appreciate your insights. Additionally, if you need further details or code snippets to provide assistance, please let me know, and I’ll be happy to provide them.

Thanks in advance for any help you can offer!

What learning path to take to develop a game with AI powered mechanics and 2D/3D graphics?

I’m a Jr/Mid-level Software Developer specializing in Full Stack Development(TS), I had a game idea for a long time and want to start developing it. It’s going to be an AI-powered simulation game, but I have no experience or knowledge in game development or machine learning. I’m looking for a learning path to start developing this game. I would appreciate some advice from the community.

My main questions are:

  1. What tech stack should I use to develop this game? (I know that the best option for game dev is C++/C#, but because of my background I decided to go with the web version for now, and maybe later I will learn C++ and develop the mobile version)
  2. What learning path to take? (The game is gonna have 2D and 3D graphics (I’ll start with the 2D version) with many animations and AI-powered mechanics)

default pnotify notification on page load

I recently install pnotify on my project and when i add css and js files it shows following notification on every page load on every page. I try to remove it using different scripts but cant

enter image description here
I want to remove this notification which shows on every page load. thanks in advance

Calling HTML/CSS Gods [closed]

not sure where and how i made this mistake, but for last 3 hours i tried fixing it, and I just need another pair of eyes and extra brain.

website – https://pavlobondarenko.co/index.html

github repo – https://github.com/OfficialCodeVoyage/pavlobondarenko.co

Problem I’m facing – here picture – the text is not white and looks like z-index problem(but it’s not)

Ideally i need this text in white.

Big thank you in advance!

Tried adding !importand and changing z-index

React Native FlatList – How to effectivly filter and load more data?

I am trying to filter data and also only pass up to 5 items to FlatList. Onscroll when end is reached, I want to load more data. If I pass more and more data to FlatList (so at first 5 items, then 10, then 15 etc), that seems to be pointless as (I think) it only makes sense if it receives each time only 5 (or no), also I just feel whatever I try, it doesnt seem to increase any effectivity.

Any help or tipps on how to approach this filtering and loading items on scroll, would be very much apreciated!
Thanks a lot!

const getData = () => {
    return (
        [
          {id: "1", country: "France", city: "Paris"}, {id: "1", country: "Italy", city: "Rome"},...
        ]
    )
}
export const AppScreen: () => {
    const [searchQuery, setSearchQuery] = useState('')
    const [data, setData] = useState([])
    const [page, setPage] = useState(0)

    const fetchData = () => {
        const data = getData()
        const filtered = filterData(data).slice(page, page + 5)
        setData([...data, ...filtered])
    }

    const filterData = (data) => data
        .filter(({city}) => city.toLowerCase().includes(searchQuery.toLowerCase()))

    const loadMore = () => {
        setPage(page+5)
    }
    useEffect(() => {
        fetchData()
    }, [page])
    
    useEffect(() => {
       fetchData()
    }, [searchQuery])

    return (
        <>
            <Search setSearchQuery={setSearchQuery} searchQuery={searchQuery} />
            <List data={data} loadMore={loadMore}/>
        </>
    )
}

const List = ({data, loadMore}) => {
    return (
        <FlatList
            data={data}
            renderItem={({item}) => <ListItem item={item} />}
            keyExtractor={item => item.id}
            onEndReached={loadMore}
            onEndReachedThreshold={1}
        />
    )
}

firework-js is not loading in html

I intend to integrate firework-js into simple html side, but the module is not loading.

Using Flask, the project is quite simple:

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route("/")
def hello_world():
    return render_template('index.html')

the index.html is like:

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  </head>

  <body>
    <div class="fireworks-container"
      style="background-size: cover; background-position: 50% 50%; background-repeat: no-repeat;"></div>
    <script type="module" src="{{url_for('static', filename='index.ts')}}"></script>
  </body>

</html>

The project structure is:

main.py
|–templates
| |–index.html
|–static
| |–index.ts

In the browser, there is a warning reporteing:

Module cannot be loaded: „http://127.0.0.1:5000/static/index.ts”.

Flask version:

  • Python 3.8.1
  • Flask 3.0.2
  • Werkzeug 3.0.1

As per my understanding, among the firework-js examples, either the “web” folder or the “with-web-components” folder might be useful, although none of them worked.

Shall the Typescript converted into Javascript to use in simple html-projects?

Playwright – asserting expected validation is matching validation result

I have the following code for asserting that the validation error messages are matching with the elements text contents

test('Assert validations are present on the checkout page', async ({ page }) => {
  await page.goto('private');
 
  await page.getByRole('button', { name: 'Headwear' }).click()
  await page.locator("//a[contains(text(),'Adult')]").click()

  const productGrid = await page.waitForSelector('div[id="productGrid"]');
  const products = await productGrid.$$('div[class="product-card relative w-full"]');
  for (const product of products) {
    const outOfStockLabel = await product.$('div:has-text("Out of stock")');
    if (!outOfStockLabel) {
      await product.click();
      break;
    }
  }

  await page.click('#btnAddToCart');
  await page.locator("//button[@title='Toggle Basket']//*[name()='svg']").click();
  await page.click("#btnCartPopUpCheckout");
  await page.click("#pay-button-container");

    // Step 2: Assert the validation messages for each field
    await page.waitForSelector("#error-for-email");
    await page.waitForSelector("#error-for-TextField1");
    await page.waitForSelector("#error-for-TextField2");
    await page.waitForSelector("#error-for-shipping-address1");
    await page.waitForSelector("#error-for-TextField4");
    await page.waitForSelector("#error-for-TextField5");
    await page.waitForSelector("#error-for-number");
    await page.waitForSelector("#error-for-expiry");
    await page.waitForSelector("#error-for-verification_value");
    await page.waitForSelector("#error-for-name");
  
    const emailValidation = await page.$eval('#error-for-email', (element) => element.textContent);
    const firstNameValidation = await page.$eval('#error-for-TextField1', (element) => element.textContent);
    const lastNameValidation = await page.$eval('#error-for-TextField2', (element) => element.textContent);
    const addressValidation = await page.$eval('#error-for-shipping-address1', (element) => element.textContent);
    const cityValidation = await page.$eval('#error-for-TextField4', (element) => element.textContent);
    const postcodeValidation = await page.$eval('#error-for-TextField5', (element) => element.textContent);
    const cardNumberValidation = await page.$eval('#error-for-number', (element) => element.textContent);
    const expirationDateValidation = await page.$eval('#error-for-expiry', (element) => element.textContent);
    const securityCodeValidation = await page.$eval('#error-for-verification_value', (element) => element.textContent);
    const nameOnCardValidation = await page.$eval('#error-for-name', (element) => element.textContent);
  
    const expectedValidations = {
      email: 'Enter an emdail',
      firstName: 'Enter a first name',
      lastName: 'Enter a last name',
      address: 'Enter an address',
      city: 'Enter a city',
      postcode: 'Enter a ZIP / postal code',
      cardNumber: 'Enter a card number',
      expirationDate: 'Enter a valid expiration date',
      securityCode: 'Enter the CVV or security code on your card',
      nameOnCard: "Enter your name exactly as it’s written on your card",
    };
  
    const validationResults = {
      email: emailValidation,
      firstName: firstNameValidation,
      lastName: lastNameValidation,
      address: addressValidation,
      city: cityValidation,
      postcode: postcodeValidation,
      cardNumber: cardNumberValidation,
      expirationDate: expirationDateValidation,
      securityCode: securityCodeValidation,
      nameOnCard: nameOnCardValidation,
    };
  
    let allValidationsPassed = true;
  
    for (const field in expectedValidations) {
      if (validationResults[field] !== expectedValidations[field]) {
        console.log(`Validation failed for ${field}: Expected "${expectedValidations[field]}", but got "${validationResults[field]}"`);
        allValidationsPassed = false;
      }
    }
  
    if (allValidationsPassed) {
      console.log('All field validations passed!');
    } else {
      console.log('Some field validations failed.');
    }

})

I run the code and it passes the test, even though one of the expected validation messages isn’t correct. I want the test to fail if validations are not matching, what am I doing wrong?

enter image description here