Clicked div works unless clicked multiple times before timeout which resets the original div image to the previously clicked one

I’m trying to code a card game i made using html, css, and js for practice, and i am trying to get clicked card divs to display in the center of the board, and it works for clicking once, but if the user clicks multiple times within the set timeout, it resets the original div image to the one selected before. I tried using a boolean if statement to return out of the function if within the 3 seconds, but it can’t access the variable if i initialize outside of the function.

let clickCard = true;

function clickedCard(clicked) {
    if (!clickCard) {
        return;
    }

    let ogStyle = window.getComputedStyle(document.getElementById("playerPlayed"));
    let ogImg = ogStyle.getPropertyValue("background-image");
    let clickedStyle = window.getComputedStyle(clicked);
    let backImg = clickedStyle.getPropertyValue("background-image");
    let playedDiv = document.getElementById("playerPlayed");
    playedDiv.style.backgroundImage = backImg;
    playedDiv.style.backgroundColor = "azure";

    let cpuCard = cpuPlayCard();
    let cpuArr = document.getElementsByClassName("cpuCard");
    let cpuArrIndex = cpuCard - 1;
    let cpuOgStyle = window.getComputedStyle(document.getElementById("cpuPlayed"));
    let cpuOgImg = cpuOgStyle.getPropertyValue("background-image");
    let cpuStyle = window.getComputedStyle(cpuArr[cpuArrIndex]);
    let cpuBackImg = cpuStyle.getPropertyValue("background-image");
    let cpuDiv = document.getElementById("cpuPlayed");
    cpuDiv.style.backgroundImage = cpuBackImg;
    cpuDiv.style.backgroundColor = "azure";

    clickCard = false;

    setTimeout(function () {
        playedDiv.style.backgroundImage = ogImg;
        playedDiv.style.backgroundColor = "none";
        clickCard = true;
    }, 3000);

    setTimeout(function () {
        cpuDiv.style.backgroundImage = cpuOgImg;
        cpuDiv.style.backgroundColor = "none";
        clickCard = true;
    }, 3000);

    let playerCard = clicked.dataset.card;
}

function cpuPlayCard() {
    let cards = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5];
    let rand = Math.floor(Math.random() * cards.length);
    let cpuCard = cards[rand];
    return cpuCard;
}

I’ve tried setting it as var and putting the variable inside the statement but that just sets it to true whenever the divs are clicked anyway. The error says, “cannot access clickCard before initialization.” Also I use onclick within the div tag in html. I am both confused and new to this and it is my first personal project.

Custom script on browser?

Is it possible to add my own custom script(js) to my browser to run when I visit a specific website?

I tried using extensions Tampermonkey. But for some reason it doesn’t run my script until I restart my browser.

Thanks in advance for your help

Unable to extract value from below json response

I have below JSON response from the request. I want to extract value term_no from the ticket list key json response. Tried using json path finder and not getting the correct value. Could some one help me to get the correct output.

Json Response

{
data: {
action: "xxxxx",
method: "ancvfdf",
content: "{"action":"","ticket_version":"1233","payment_version":"1223","purchase_version":"12123",
            "responselist":[{"seq_no":"45454","bank_resp_code":"0","transid":"27344650","auth_code":"xxxx","amount":"","paymethod_id":"*****","payment_no":""}],
            "ticketlist":[{"seq_no":"5656","trx_no":"2434","term_no":"2001","sale_no":"1","ticket_no":"1","ticket_amount":"210","start_validity":"20240127002022","end_validity":"20250126002022","tt_id":"12010","printed_serial_number":"8692","trx_seq_id":"1100430673","bus_zone":"9","active_ticket_duration":"165","exception_data":"","zip_code":"07001"},
            {"seq_no":"xcxcx","trx_no":"xxx","term_no":"2001","sale_no":"1","ticket_no":"1","ticket_amount":"0","start_validity":"20240127002022","end_validity":"20250126002022","tt_id":"12010","printed_serial_number":"8692","trx_seq_id":"1100430673","bus_zone":"9","active_ticket_duration":"165","exception_data":"","zip_code":"07001"}],
            "status_msg":"Success","status_code":"0","version":"1.0","site_id":"1_N","term_no":"2001"}",
status_msg: "Success",
status_code: "0",
version: "1.0",
site_id: "1_N"
}
}

Used below way

pm.expect(responseJson.data.content.action.ticketlist[0].term_no).to.eql('2001');

Getting the below Error

The response has all properties | TypeError: Cannot read properties of undefined (reading ‘ticketlist’)

When I scroll for one time, it doesn’t work for the second time, but it works for the third time,

When I scroll for one time, it doesn’t work for the second time, but it works for the third time, and so on
i have this function

  const scrollToElement = (id) => {
const element = document.getElementById(id);
if (element) {
  element.scrollIntoView({ behavior: "smooth" });
}

};
this function get id from tag and scroll
and i have this code

  async function handleLength(input, name1, message) {
if (input == null || input.length === 0 || input == "انتخاب نشده") {
  setErrorF((prevState) => ({ ...prevState, [name1]: message }));
  scrollToElement(name1);
} else {
  setErrorF((prevState) => ({ ...prevState, [name1]: "" }));
}

}
when i called for one time function is good and scroll but when called for tow time not work and get this error in the console

Scroll anchoring was disabled in a scroll container because of too many consecutive adjustments (10) with too little total distance (-0.659999990463257 px average, -6.6 px total).

How to send files from frontend (Next.js) to backend (express)?

I am using useFormState hook to send the formdata to express backend and in is logging the ‘image’ file on the frontend . But in the express backend , i unable to get any field like ‘image’ in the req body .

const[state,formAction] =useFormState(actions,{success:false,status:null})

This the my form component:

 <form ref={formRef}encType='multipart/form-data'  action={formAction} >
    <input
    name="title"
    type='text'
      className="w-full p-2 border rounded mb-4"
      rows="4"
      placeholder="Title" 
    ></input>
   {renderErrors('title')}
    <textarea
    type='text'
    name="description"
      className="w-full p-2 border rounded mb-4"
      rows="4"
      placeholder="Whats on your mind"
      // value={postContent}
      // onChange={(e) => setPostContent(e.target.value)}
    ></textarea>
     {renderErrors('description')}
    
    <div className="mb-4">
      <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="fileInput">
        Upload a file:
      </label>
      <input
        type="file"
        id="fileInput"
        name='image'
        className="w-full border rounded py-2 px-3"
        // onChange={(e) => setSelectedFile(e.target.files[0])}
      />
    </div>
    <div className="flex items-center justify-between">
      <button
        type="submit"
        className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
      >
        Post
      </button>
    </div>
  </form>

And this is my action :

 "use server"
import axios from "axios";
export  async function actions(prevstate,formdata) {
    try {
        const { title, description,image } = Object.fromEntries(formdata);
        console.log(image);
        const response = await axios.post('http://localhost:8080/api/add-post', { title, description,image, author: "gaurav" });
        return {...prevstate, success: true ,status:Object.keys(response.data)[0] };
    } catch (error) {
        console.log(error.response.data);
        return { ...prevstate,success: false, status: error.response.data };
    }
   

}

To be noted that i am able to log the image in the action , but the req.file in the express backend returns undefined . I am handling the image upload using muter package. Also when I am using postman , it works fine (File gets stored in MongoDb). Is there any issue with how am am using the useFormState hook?

I know storing files in mongodb is not recommended , but i am just learning and trying to understand the whole thing (self learning).

For the reference of how i am using the multer package, below the the code for it:

const express = require('express');
const router = express.Router();
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
const postController = require('../controller/postController')
router.post('/api/add-post', upload.single('image'), postController.addPost)
module.exports = router

And below the the controller:

const { User, Post } = require('../models');

exports.addPost = async (req, res) => {
    try {            // return res.status(400).json({ haha: error });

        const { title, description, author } = req.body;
        const post = new Post({ title, description, author });
        console.log("file",req.file);
        post.image.data = req.file.buffer;
        savedPost = await post.save();
        return res.status(200).json({ "Post added": savedPost });
    } catch (error) {
        console.error(error);
        if (error.name === 'ValidationError') {
            // Mongoose validation error
            const validationErrors = Object.entries(error.errors).map(([name, errorObject]) => ({
                [name]: errorObject.message,
            }));            
            
            return res.status(400).json({  errors: validationErrors });

        }
        else{
            return res.status(500).json({  error: "Internal Server Error" });
        }
    }
};

If undefined throws an exception how can you test for it in Javascript [duplicate]

I am a bit lost here. I have the below code:

        if (profileChart === undefined) {
            profileChart.destroy();
        } else {
            let profileChart = new Chart(
               pisteElevationProfileChart,
               configPiste
            );
        }

I get an error stating, myscript.js?ver=1.0:335 Uncaught ReferenceError: profileChart is not defined… but that is what I want to test for. I see many references stating above is how to check for it but does not work. Any pointers appreciated.

How do I pass my state from a child component to a parent component, then to another child component of a different parent component?

Currently working on a CV Creator as a mini React project, these are my current Components:

Creator
Form
Input
CvDisplay
(DisplayComponents)

I have a state in my Input component that updates upon every change in the input box, this is a simplified example of the component:

export default function Input() {
  const [inputValue, setInputValue] = useState("");

  const handleInputChange(e) => {
    setInputValue(e.target.value);
  }

  return (
    <div>
      <input type="text" onChange={handleInputChange} />
    </div>
  )
}

I am trying to get the inputValue state to the Creator component, and then into the CvDisplay component, so when the inputValue changes from the Input component, the changes will display in real time in the CvDisplay component. An example of it being done would be here: https://cv-app-eta.vercel.app/

Beginner here so I would appreciate any advice, thank you!

I tried using a callback function, but it did not work as expected as there are multiple Input Components in the Form component.

Also tried lifting up the state, but could not manage to make it work as it’s technically a “grandparent to child” component instead of a parent to child component.

why is email.js not picking up my post route for send-email?

trying to get email.js to work with my application. I am using react.js on the front end. I am using a contact form to send me email when someone wants to connect or speak with me. just email, name, message and emailjs should send me a message.i keep receiving an error as shown below

POST http://localhost:3000/send-email 404 (Not Found)
handleFormSubmit @ Contact.jsx:14

heres my server.js

import express from 'express';
import emailjs from 'emailjs-com';
import dotenv from 'dotenv';
import cors from 'cors'; // Import the cors middleware

const app = express();

// Load environment variables from .env file
dotenv.config();

app.use(express.json());

// Use the cors middleware to allow requests from all origins
app.use(cors());

app.post('/send-email', async (req, res) => {
  const { name, email, message } = req.body;

  try {
    // Send email using emailjs
    await emailjs.send(
      's*****', // Replace with your service ID. hidden from public
      '****', // Replace with your template ID hidden from public
      { 
        from_name: name,
        reply_to: email,
        message: message
      },
      process.env.EMAILJS_USER_ID // Accessing emailjs user ID from environment variable
    );

    console.log('Email sent successfully');
    res.status(200).send('Email sent successfully');
  } catch (error) {
    console.log("error:",error)
    console.error('Error sending email:', error);
    
    res.status(500).send('Failed to send email');
  }
});

const PORT =  3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

heres my contac.jsx that holds my contact form

import React, { useState } from "react";
import './contact.css';

const Contact = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [formError, setFormError] = useState("");

  const handleFormSubmit = async (event) => {
    event.preventDefault();

    try {
      const response = await fetch('/send-email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, email, message }),
      });

      if (response.ok) {
        // Email sent successfully
        console.log('Email sent successfully');
        setName('');
        setEmail('');
        setMessage('');
        setFormError('');
      } else {
        const errorMessage = await response.text();
        setFormError(errorMessage || 'Failed to send email');
      }
    } catch (error) {
      console.error('Error sending email:', error);
      setFormError('Failed to send email');
    }
  };

  return (
    <div className="contact-container" id="Contact">
      <br />
      <h2 id="contact-me" className="bib">Let's Connect!</h2>
      <br />
      <form className="contact-form" onSubmit={handleFormSubmit}>
        <div className="form-group">
          <div className="input-group">
            <input
              type="text"
              placeholder="Enter your name"
              value={name}
              onChange={(event) => setName(event.target.value)}
            />
          </div>
        </div>
        <div className="form-group">
          <div className="input-group">
            <input
              type="email"
              placeholder="Enter your email"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
            />
          </div>
        </div>
        <div className="form-group">
          <div className="txtA">
            <textarea
              placeholder="Type your message here"
              value={message}
              onChange={(event) => setMessage(event.target.value)}
            />
          </div>
        </div>
        <div className="form-group">
          <button type="submit">Submit</button>
        </div>
        {formError && <p className="error-message">{formError}</p>}
      </form>
    </div>
  );
};

export default Contact;

dynamic array of ref in react

in my portaflio iam trying to make a ref for my projects card but I want it to be dynamic not a Collection of static ref ,in the parent component I am made function that take ref from the card component but I getting errors here is the code and error
parent component :

function Projects() {
  let imagesRef = useRef([]);
  let [projectCard, setProjectCard] = useState([]);

  let addrefitem = (img) => {
    imagesRef.current.push(img);
  };

  let showprojects = (start, end) => {
    let show = [];

    for (let i = start; i < end; i++) {
      //there will be one data more if this is disable
      if (i <= data.length - 1) {
        show.push(<ProjectCard {...data[i]} ref={addrefitem} />);
      }
    }

    setProjectCard(show);
  };
return (
    <Box component={"section"} className="projects" id="projects">
      <Container maxWidth={"xl"}>
        {/*Heading*/}
        <Box>
          <Typography variant="h4" color="#fff" textAlign={"center"}>
            My Projects {<GrReactjs />}
          </Typography>
          <Typography variant="body1" color="#fff">
            this is my projects made with js&React {<GrReactjs />}
          </Typography>
        </Box>
        {/* project tab bar*/}
        <ProjectCardtab
          tabclickhandler={tabclickhandler}
          tabscount={tabscount}
        />
        {/* cards */}
        <ThemeProvider theme={theme}>
          <Grid container className="data-card-container" sx={{ flexGrow: 1 }}>
            {projectCard}
          </Grid>
        </ThemeProvider>
      </Container>
    </Box>
  );
}

part of card component

function ProjectCard({...},ref) {

return (
//code 

  <img
          style={{ opacity: 0 }}
          className="img"
          loading="lazy"
          src={require(`../../assets/img/project_image/${imgurl}`)}
          alt="image of project"
          ref={ref}
        />

)
export default React.forwardRef(ProjectCard);

error :
img of errors

my goal is to make a good image loading effect and part of it is that when picture is done loading it show

Frontend Deployment Error: Uncaught ReferenceError: require is not defined with Vite, Chat Engine’s and WebSocket

I’m encountering an issue with my real-time chat application built using Chat Engine. I deployed it on Render.com. The problem is that while the frontend works perfectly on my local system, it fails to work after deployment.

The browser console displays an error message: Uncaught ReferenceError: require is not defined. Upon investigating, I found that the issue lies in the use of require, which is not recognized by the browser.

the error

require("websocket").w3cwebsocket;
var Fw = require("websocket").w3cwebsocket

I’m using Vite for the frontend. Here are the relevant links:

Live deployment: live

GitHub repository: repo

tutorial: link

Any insights on resolving this issue would be greatly appreciated. Thank you!

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘id’) in middleware function express.js

i’m a beginner creating a social media app and currently i want to get posts via route middleware function,

here in the backend controller file named PostController.js the middleware function is

export const getTimelinePosts = async (req, res) => {
  const userId = req.params.id // here is the error displayed cannot read properties of undefined id
  try {
    const currentUserPosts = await PostModel.find({ userId: userId });

    const followingPosts = await UserModel.aggregate([
      { 
        $match: {
          _id: new mongoose.Types.ObjectId(userId),
        },
      },
      {
        $lookup: {
          from: "posts",
          localField: "following",
          foreignField: "userId",
          as: "followingPosts",
        },
      },
      {
        $project: {
          followingPosts: 1,
          _id: 0,
        },
      },
    ]);

    res.status(200).json(
      currentUserPosts
        .concat(...followingPosts[0].followingPosts)
        .sort((a, b) => {
          return new Date(b.createdAt) - new Date(a.createdAt);
        })
    );
  } catch (error) {
    res.status(500).json(error);
  }
};

in the above PostController.js req.params.id is where the error is displayed

here is my routing file PostRoute.js for routing

import express from "express"
import { CreatePost, GetPost, UpdatePost, DeletePost,  getTimelinePosts, likePost, } from "../controllers/PostController.js"

const router = express.Router()

router.post("/", CreatePost)
router.get("/:id", GetPost)
router.put("/:id", UpdatePost)
router.delete("/:id", DeletePost)
router.put('/:id/like', likePost)
router.get('/:id/timeline', getTimelinePosts) // this is the getTimelinePost route 

export default router














here is the error being displayed

enter image description here

this is the console tab in the browser and nothing is being displayed on the page, the page is full blank, idk i do think that my routes are correct and i also have other middleware function(likePost, deletePost etc) that are also retriving id as req.params.id and i beleieve they are all working correct,

do tell me what is wrong and do explain the answer a bit, if u need more information do tell me i will provide it asap

in the protected route console i am getting this error “uncaught TypeError: (intermediate value)(…) is undefined”

in the protected route console i am getting this error “uncaught TypeError: (intermediate value)(…) is undefined” the

my expectation is to get user data in the network

  • Define an asynchronous function getUser to fetch user information using an HTTP POST request to the server.

  • Dispatch showLoading action before making the request and hideLoading after receiving the response.

  • If the response is successful, update the user state in the Redux store using the setUser action.

  • If there is an error or the response is not successful, clear local storage and navigate to the login page.

  • Check if there is a valid token in the local storage.

  • If a token exists, render the children components passed to ProtectedRoute.

  • If there is no token, navigate to the login page using Navigate from react-router-dom.

the file extension is jsx

this is the protected route 

import React from "react";
import {useEffect} from "react"
import { Navigate, useNavigate } from "react-router-dom";
import axios from "axios";
import {setUser} from "../redux/userSlice"
import {useDispatch , useSelector} from "react-redux"
import {hideLoading,showLoading} from "../redux/alertsSlice"

function ProtectedRoute(props){
      const {user} = useSelector((state)=>state.user);
      const dispatch = useDispatch();
      const navigate = useNavigate();
     // const [loading, setLoading] = useState(true);
    
      const getUser  = async () =>{
        try{
            dispatch(showLoading())
            
            const response = await axios.post(
                "/api/user/get-user-info-by-id",
                {token:localStorage.getItem("token")},
                {
                    headers:{
                        Authorization:`Bearer ${localStorage.getItem("token")}`,
                    }
                },
                
            );
            console.log("Response from server:", response);  // Log the entire response
            dispatch(hideLoading());
            if(response.data.success){
                dispatch(setUser(response.data.data));
            }else {
                localStorage.clear();
                navigate("/login");
            }

        }catch(error){
            dispatch(hideLoading());
            localStorage.clear()
            navigate("/login");
        }
      };
      useEffect(()=>{
        if(!user){
            getUser();
        }
      },[user]);


      console.log("amen")

    if(localStorage.getItem("token")){
        return props.children
    } else {
        return navigate('/login');
    }
}

export default ProtectedRoute;
this is the app.jsx
import { useState } from 'react'
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { Home } from './pages/Home';
import { Login } from './pages/Login';
import { Button } from "antd";
import { Register } from './pages/Register';
import { Toaster } from "react-hot-toast";
import { useSelector } from "react-redux";
import ProtectedRoute from './component/ProtectedRoute';
import PublicRoute from './component/PublicRoute';
function App() {
  const { loading } = useSelector((state) => state.alerts);

  return (
    <BrowserRouter>
     {loading && (
        <div className="spinner-parent">
          <div class="spinner-border" role="status"></div>
        </div>
      )}
          <Toaster position="top-center" reverseOrder={false} />
    <Routes>
      <Route path='/' element={<ProtectedRoute>
        <Home />
      </ProtectedRoute>} />
      <Route path='/login' element={<PublicRoute>
        <Login />
      </PublicRoute>} />
      <Route path='/register'  element={<PublicRoute>
        <Register />
      </PublicRoute>} />
    </Routes>
    </BrowserRouter>
  )
}

export default App

Lenis js not scrolling

I added this code from lenis documentation on my wordpress theme. It doesn’t show any error, I can even see the console but when I try to scroll from touch pad it doesn’t work but scrolling using arrow keys work.

document.addEventListener("DOMContentLoaded",init);

function init (){
   const lenis = new Lenis()

   lenis.on('scroll', (e) => {
     console.log(e)
   })

  function raf(time) {
    lenis.raf(time)
    requestAnimationFrame(raf)
  }

   requestAnimationFrame(raf)
  }

I have tried adding overflow: scroll as well as this answer but the issue still persists

ReferenceError: Cannot access ‘setTimeout’ before initialization

In my code I am trying to do a javascript exercise. On the second line, I’m trying to get the ogTimeout to store a reference to setTimeout function since I will reassign a new definition to setTimeout.

However I get the error “ReferenceError: Cannot access ‘setTimeout’ before initialization”. I understand that it’s saying that setTimeout should be initialized, but it already is a existing function, so I don’t understand what’s causing the error.

Any help appreciated, thank you!

const timeouts = [];
const ogTimeout = setTimeout; 

let setTimeout = function(method, timeInMs) {
    const timeoutRef = ogTimeout(method, timeInMs);
    timeouts.push(timeoutRef);
}

const clearAllTimeouts = function() {
    while (timeouts.length) {
        const timeoutRef = timeouts.pop();
        clearTimeout(timeoutRef);
    }
}

setTimeout(() => console.log("Callback after 5 seconds."), 5000);

Tried searching referenceerror and its details.