The data I got dynamically didn’t work in the tailwind library. How can I solve it?

I added the initial data as a class. I coded the incoming data to cross out the label if it exists in the class, but it didn’t work. It doesn’t give an error either.

import { useState } from "react";
export default function ShopList({ item, index }) {
const [checkValue,setCheckValue] = useState('');
  return (
    <div>
      <div className="mb-[0.125rem] block min-h-[1.5rem] pl-[1.5rem]" data-index={index}>
        <input type="checkbox" onChange={(e)=> setCheckValue(e.target.checked)} />
        <label 
        className={`inline-block pl-[0.15rem] hover:cursor-pointer ${checkValue} true:line-through `}>
          {item}
        </label>
      </div>
    </div>
  );
}

How can I solve it?

How can I display a variable value in multiple places within my HTML tag?

How do I return a variable value (test) in multiple places in my HTML <p> tag.

The variable displays correctly in the first instance but is blank in the second. What am I doing wrong?

var name = document.querySelector("#NameInput").value;

function fillData() {
  document.querySelector("#nameOutput").innerHTML = name;
}
<p>I understand your name is <span><output id="name"></output></span>.</p>
<p>It's nice to meet you `your text`<span><output id="name"></output></span>.</p>

How to download a file and send data with jQuery & AJAX. Why does it see the button as clicked? [duplicate]

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample download</title>
</head>

<body>
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>

<span id="paperlink">
<a href="https://www.google.com/linktoapdffile.pdf" class="btn btn-danger btn-lrg doajax" >Download</a>
</span>

<script>

function doajax(){
    $.ajax({
    type: "POST",
    url: "https://www.google.com/scripts/custom.php",
    dataType: "text",
    data: {"wp_title": "Multi-Party Orchestration Platform", "cf_company": "MPO"}
    });
}

var link = document.getElementById('paperlink');
link.onclick = doajax();
// $("#paperlink").html('The button was clicked');

</script>

</body>
</html>

I am trying to submit a form to download a pdf file and send some data back to the server using php, json and curl. One button click, two actions. When I load the above, it sends the data regardless of whether the download button is clicked. I would like to only send data if the button is clicked and the download viewed. I cannot add an ID to the button, that’s why I added the span with an ID.

for…of .for is not iterable (on an array???)

let collection = [{
    name: 'music',
    views: 20
  },
  {
    name: 'abc',
    views: 32
  },
  {

    name: 'bob',
    views: 20
  }
]

for (const [k, v] of collection) {
  console.log(k, v)
}

console.log(Array.isArray(collection))

Error: .for is not iterable

Array.isArray(collection) returns true

How can an array not be iterable?

Do I really need to resort to this to “get” the index of each item?

for (let i = 0; i < collection.length; i++){
    console.log(i, collection[i])
        
}

nvm …it works fine with forEach

collection.forEach((k, v) => {
    console.log(k,v)
})

What’s going with for…of here?

Note: I can’t use for…in b/c i need the order to be guaranteed

Javascript Mongoose get the employees with the birthday between 2 date range

I want to get all of “birthDate” in a mongoose “profile” model that is between a start date (birthDateStart) and end date (birthDateEnd)

profile schema

{
_id:"1",
birthDate:"1990-05-02T04:00:00.000+00:00"
}

As you know, we check only the DAY and MONTH to see if the birthday is between START and END for a birthday and ignore the year.

for example, the birthday is 1990-05-02 (yyyy-mm-dd)
and we should find it in the range of 2023-01-01 till 2023-06-01
because 05-02 is between 01-01 and 06-01 (dd-mm)

but should not find it between 2023-01-04 and 2023-04-30
because 05-02 is not between 01-04 and 04-30 (dd-mm)

my try is not working as follow:

if (birthDateStart) {
const currentYear = dayjs().year();
search.birthDate = {
$gte: dayjs(birthDateStart).set('year', currentYear).toDate(),
};
}

if (birthDateEnd) {
const currentYear = dayjs().year();
search.birthDate = {
$lte: dayjs(birthDateEnd).set('year', currentYear).toDate(),
};
}

Please advise

Mock Jest Function Instance Doesn’t Carry Over to Call in Other File

Mock Jest function instance doesn’t seem to carry over to an imported module

I have a function “sendDataHandler” that calls “sendToEH”

I want to write jest test that makes sure calls to “sendDataHandler” make calls to “sendToEH”

So my implementation:

app.sendToEH = jest.fn();

await app.sendDataHandler(req, res, next);

expect(app.sendToEH).toHaveBeenCalled();

This test fails. When I go into debug mode and follow the sequential operations, “sendDataHandler” calls “sendToEH” from the module instead of the defined mock function.

If I write:

app.sendToEH = jest.fn();

await app.sendToEH('asdf');

await app.sendDataHandler(req, res, next);

expect(app.sendToEH).toHaveBeenCalled();

The test passes.

Why does the instance of the mock function not carry through to the other file/module? How do I fix this issue?

Rendered more hooks than during the previous render. And other errors in hooks

This is my StateContext

import { atom, useAtom } from 'jotai';

export const userRoleAtom = atom([]);

export const useData = () => {
  const [userRole, setUserRole] = useAtom(userRoleAtom);
  return { userRole, setUserRole };
};

This is how I get the data using laravel api endpoint in DefaultLayout as the parent of all components.

const { setUserRole } = useData();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axiosClient.get('/getUserRole');
        const data = response.data;
        setUserRole(data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [setUserRole]);

And when I try to get the userRole using useData. It will return to me as an empty array twice at first and then the actual data. This is how I fetch it in my Plan function:

const { userRole } = useData();

  useEffect(() => {
    console.log(userRole);
  }, [userRole]);

Without the useEffect, it would return empty array 4 time and then the actual data 8 times mostly.
I don’t get why ~

I don’t want fetching empty array, since I would need to loop it for granting access. Advide in this part also pls.

Why can I not access querySelectors out of scope?

I’m working on a HTML/CSS/React/JS project, and want to refactor the duplicate lines I have assigning variables to different class-elements. In this example, I have an event-listener that changes the scale of a div based on the window size.

import React from 'react';

function Home() {
  const [scrollX, setScrollX] = React.useState(document.body.scrollWidth);
  const [scrollY, setScrollY] = React.useState(document.body.scrollHeight);

  const resizeCallback = () => {
    const rotateName = document.querySelector('.rotateName');
    const y = document.body.scrollHeight / scrollY;
    const x = document.body.scrollWidth / scrollX;

    rotateName.style.scale = x * y * 1.2;
  };

  React.useEffect(() => {
    window.addEventListener('resize', resizeCallback);

    return () => {
      window.removeEventListener('resize', resizeCallback);
    };
  }, []);

  return (
    <div className="home">
      <div className="rotateName">
        <p>My name is</p>
        <div className="firstN"><h1>John</h1></div>
        <div className="lastN"><h1>Doe</h1></div>
      </div>
    </div>
  );
}

export default Home;

When I place rotateName on Line 8 (inside resizeCallback) to the outer-most scope in the Home function like Line 6, it stops working. My understanding of scopes and closures is that variables declared outside of a block can be used in inner functions?

Does this problem have to do with the processes of React.useEffect(), or is it a conceptual misunderstanding of closures on my part?

onerror Event for Classes and Web Components?

Following this other question about tracking errors in JS, I’m trying to use something similar to window.onerror to track only the errors pertinent to the context of my class or Web Component, since my components are meant to be used in other websites.

Is that possible right now?

(If there are any services that do this right now, it would also be nice to know.)

For example, I would like to track all the errors coming from my class or its inheritors:

abstract class Trackable extends HTMLElement {
  override connectedCallback() {
    this.onerror = (
      message?: string,
      file?: string,
      line?: number,
      column?: number,
      error?: Error
    ) => {
      console.log(error.cause);
    };
  }
}

However, this doesn’t seem work. And if I use window instead of this, then any errors on the window will run into this listener, which is not what I want.

how to keep last content with scrolltrigger

I saw a pen with scrolltrigger and wanna use it. But before first scroll content(I mean text in bright green area) is invisible and when I scroll to the bottom content became invisible. how to keep the last content?

here is the pen

and my own script

        gsap.set('.content',{ autoAlpha: 0 })
        gsap.set('.image',{ autoAlpha: 0 })

        var headlines = gsap.utils.toArray(".text");

        var totalDuration = 8000;
        var singleDuration = totalDuration / headlines.length;

        const lineTimeline = gsap.timeline();

        ScrollTrigger.create({    
        trigger: ".pin-up",
        start: "top top",
        end: "+=" + totalDuration,
        //markers: true,
        pin: true,
        scrub: true,
        animation: lineTimeline,
        });

        headlines.forEach((elem, i) => {    
        
                const smallTimeline = gsap.timeline(); 
                    
                const content = document.querySelector('.content-wrap');
                const relevantContent = content.querySelector('div.content-' + i);  
                
                ScrollTrigger.create({    
                    
                    trigger: "body",                        
                    start: "top -=" + ( singleDuration * i ),
                    end: "+=" + singleDuration,
                    animation: smallTimeline,
                    toggleActions: "play reverse play reverse",
                    
                });   

                smallTimeline
                //.to(elem,{ duration: 0.25, fontSize: "40px", color: "orange"}, 0)  
                .to(elem,{ duration: 0.25, color: "orange"}, 0) 
                .to(elem.firstChild,{ duration: 0.25, backgroundColor: "orange", width: "50px"}, 0)                
                .set(relevantContent,{ autoAlpha: 1 }, 0);
        
        });

how do i add and remove array elements to my json array without making my json file ugly?

i have the following json file:

{
    "username": "Peacey",

    "balance": {
        "Silver": 10
    },

    "inventory": {
        "Wood": 3
    }
}

i wanna be able to add as many items and currencies as i want to “balance” and “inventory” while keeping its readability.

so i wanna say for example when a new item like Stone is added to the user’s inventory, then add “Stone” to the user’s json file’s inventory.
so i want it to look like this:

{
    "username": "Peacey",

    "balance": {
        "Silver": 10
    },

    "inventory": {
        "Wood": 3,
        "Stone": 7
    }
}

so i can add and remove as many items and currencies i want without making my json file ugly, FOREVER! 😀

*edit:
im new in both nodejs and json stuff, im new in codding stuff so the title might be wrong or explained bad.

autofill (jQuery) not working with dynamic added rows in HTML Form

I am trying to autofill my PHP form by retrieving data from mysql table. Its work fine on one row. The problem which I am facing is that : When I dynamically add new rows using java script, than auto fill do not work in dynamically created row. I want to knew how can I do autofill with dynamic created row

this is html code
<td><input type="text" class="form-control text-end" name="scode[]" id="aaa" onkeyup="GetDetail(this.value)" value=""></td> <td><input type="text" class="form-control text-end" name="servproname[]" id="bbb"></td> <td><input type="text" class="form-control text-end" name="qty[]" id="ccc" ></td>``
This is java script for add new row dynamically
function BtnAdd()
`{
/Add Button/
var v = $(“#TRow”).clone().appendTo(“#TBody”) ;
$(v).find(“input”).val(”);
$(v).removeClass(“d-none”);
$(v).find(“th”).first().html($(‘#TBody tr’).length – 1);
}“`

this is jquerry

              `<script>

          // onkeyup event will occur when the user
              // release the key and calls the function
        // assigned to this event
        function GetDetail(str) {
        if (str.length == 0) {
            document.getElementById("bbb").value = "";
            document.getElementById("ccc").value = "";
        

            
            
                return;
        }
        else {

            // Creates a new XMLHttpRequest object
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {

                // Defines a function to be called when
                // the readyState property changes
                if (this.readyState == 4 &&
                        this.status == 200) {
                    
                    // Typical action to be performed
                    // when the document is ready
                    var myObj = JSON.parse(this.responseText);

                    // Returns the response data as a
                    // string and store this array in
                    // a variable assign the value
                    // received to first name input field
                    
                    document.getElementById
                        ("bbb").value = myObj[0];

                        document.getElementById
                        ("ccc").value = myObj[1];

                                
                    

                    

                    }
                 };

               // xhttp.open("GET", "filename", true);
               xmlhttp.open("GET", "gfg.php?user_id=" + str, true);
            
               // Sends the request to the server
               xmlhttp.send();
           }
       }
     </script>`

This is php script

          ``<?php

       // Get the user id
          $user_id = $_REQUEST['user_id'];

           // Database connection
            $con = mysqli_connect("localhost", "root", "", "hmis");

            if ($user_id !== "") {

               // Get corresponding first name and
                 // last name for that user id  
                 $query = mysqli_query($con, "SELECT name, qty1 FROM machine1 WHERE user_id ='$user_id'");

                     $row = mysqli_fetch_array($query);

            // Get the first name
                  $bbb = $row["name"];
              $ccc = $row["qty1"];
    


            }

               // Store it in a array
                  $result = array("$bbb", "$ccc");

                // Send in JSON encoded form
               $myJSON = json_encode($result);
            echo $myJSON;
          ?>`

`

Leaflet ‘quick start’ code snippet giving TypeError: Cannot read properties of null when displaying OpenStreetMap in JavaScript application

getting error when using leaflet a javascript library

Uncaught TypeError: Cannot read properties of null (reading 'lat')

I am building an application and using openstreet maps with the help of leaflet (version 1.9.4) javascript library..
But when I am using the quick start code snippet of leaflet in my code it is giving error.

The snippet I am using

var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

L.marker([51.5, -0.09]).addTo(map)
    .bindPopup('A pretty CSS popup.<br> Easily customizable.')
    .openPopup();

The error I am getting

Projection.SphericalMercator.js:24 Uncaught TypeError: Cannot read properties of null (reading 'lat')
    at Object.project (Projection.SphericalMercator.js:24:43)
    at Object.latLngToPoint (CRS.js:28:40)
    at e.project (Map.js:982:27)
    at e._latLngToNewLayerPoint (Map.js:1510:15)
    at e._animateZoom (Marker.js:330:23)
    at e.fire (Events.js:195:9)
    at e._animateZoom (Map.js:1701:8)
    at e.<anonymous> (Map.js:1679:9)

When I am opening the Projection.SphericalMercator file from console to check the error this is what I am getting :-

import {LatLng} from '../LatLng';
import {Bounds} from '../../geometry/Bounds';
import {Point} from '../../geometry/Point';

/*
 * @namespace Projection
 * @projection L.Projection.SphericalMercator
 *
 * Spherical Mercator projection — the most common projection for online maps,
 * used by almost all free and commercial tile providers. Assumes that Earth is
 * a sphere. Used by the `EPSG:3857` CRS.
 */

var earthRadius = 6378137;

export var SphericalMercator = {

    R: earthRadius,
    MAX_LATITUDE: 85.0511287798,

    project: function (latlng) {
        var d = Math.PI / 180,
            max = this.MAX_LATITUDE,
**line of error ->  lat = Math.max(Math.min(max, latlng.lat), -max),**
            sin = Math.sin(lat * d);

        return new Point(
            this.R * latlng.lng * d,
            this.R * Math.log((1 + sin) / (1 - sin)) / 2);
    },

    unproject: function (point) {
        var d = 180 / Math.PI;

        return new LatLng(
            (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
            point.x * d / this.R);
    },

    bounds: (function () {
        var d = earthRadius * Math.PI;
        return new Bounds([-d, -d], [d, d]);
    })()
};

Dynamic TailwindCSS transition – how to set it on initial load?

I have a button and upon pressing it, it turns a div element transparent. It does so with a transition effect.

I saved the visibility state of the element in cookies (using js-cookie) and I’d like to keep the elements visible upon exiting and re-opening the page. It does so, but it also runs the unnecessary transition.

How should I improve my code, so that the transition only runs when I click the button, and not when the visibility state gets loaded from the cookies?

Here’s my best attempt at solving it..

"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import Cookies from "js-cookie";

const Home = () => {
  const [visible, setVisible] = useState(false);
  const [transition, setTransition] = useState(false);

  useEffect(() => {
    //the state of section visibility
    const visibleState = Cookies.get("visibleState");
    visibleState && setVisible(!!visibleState);

    const transitionState = Cookies.get("transitionState");
    transitionState && setTransition(!!transitionState);

    return () => {
      Cookies.set("transitionState", "false");
    };
  }, []);

  const handleToggleVisibility = () => {
    Cookies.set("visibleState", String(!visible));
    setTransition(!transition);
    setVisible(!visible);
  };

  return (
    <main className="flex h-5/6 flex-col justify-between">
      {/* Who section */}
      <section>
        <div className="flex h-1/6 items-center justify-center text-3xl font-light">
          <span className="text-slate-500">{"< "}</span>
          <button onClick={handleToggleVisibility}>&nbsp;who?&nbsp;</button>
          <span className="text-slate-500">{" />"}</span>
        </div>

        <div
          className={
            "mt-20 flex h-2/6 flex-col items-center justify-center gap-[1px] text-3xl font-light transition-all duration-700 " +
            (visible ? "opacity-100" : "opacity-0") +
            (transition ? " transition-all duration-700" : "")
          }
        >
          <Link
            href="/dev"
            className="mx-auto w-1/4 border border-black p-4 text-center transition-all duration-300 hover:border-slate-500 active:bg-slate-800"
          >
            Software developer
          </Link>
          <Link
            href="/books"
            className="mx-auto w-1/4 border border-black p-4 text-center transition-all duration-300 hover:border-slate-500 active:bg-slate-800"
          >
            Reader
          </Link>
          <Link
            href="dreams"
            className="mx-auto w-1/4 border border-black p-4 text-center transition-all duration-300 hover:border-slate-500 active:bg-slate-800"
          >
            Dreamer
          </Link>
        </div>
      </section>

      {/* Contact footer */}
      <p className="flex items-center justify-center p-6 text-2xl tracking-widest">
        <span className="text-slate-500">{"<"}</span>
        <Link href={"/contact"}>&nbsp;Contact&nbsp;</Link>
        <span className="text-slate-500">{"/>"}</span>
      </p>
    </main>
  );
};

export default Home;

How to get oauth credentials of logged-in firebase authenticated user?

I have created a firebase authentication using google OAuth. When I am signing in for the first time, we have a function that spills the google OAuth’s access-token – I am using this token to call a googleapis. But I am looking for the same access-token when I am coming back to my web-app. I have the currentUser, but I am unable to figure out as on how to get the creds.

 const signInWithGoogle = () => {
    const provider = new GoogleAuthProvider();
    provider.addScope('https://www.googleapis.com/auth/youtube.readonly');
    const auth = getAuth(app);
    signInWithPopup(auth, provider)
      .then(async (result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        console.log("token", token)
        // IdP data available using getAdditionalUserInfo(result)
        // ...
      }).catch((error) => {
        console.log("error", error)
      });
  }

In this code token is giving me the output I want. I want the same thing once I come back or refresh my web-app.
Something that I can fetch with auth.currentUser or something like that.

I tried this code.

auth.currentUser.getIdTokenResult().then((idTokenResult) => {
      const provider = new GoogleAuthProvider();
      const credential = GoogleAuthProvider.credential(idTokenResult);
        // const token = credential.accessToken;
      console.log("idTokenResult", idTokenResult, "-----------------token", credential)
      // Confirm the user is an Admin.
    })

Result

{
    "idToken": {
        "claims": {
            "name": "Shenor shai",
            "picture": "https://lh3.googleusercontent.com/a/AGNmyxMdzHBqcvUriJvQPyYc2PhdjrIA=s96-c",
            "iss": "https://securetoken.google.com/chainlink-hackathon-23",
            "aud": "random",
            "auth_time": 1684419631,
            "user_id": "aofhafihfiafhafia",
            "sub": "aofhafihfiafhafia",
            "iat": 1684421034,
            "exp": 1684424634,
            "email": "[email protected]",
            "email_verified": true,
            "firebase": {
                "identities": {
                    "google.com": [
                        "118112290937553408948"
                    ],
                    "email": [
                        "[email protected]"
                    ]
                },
                "sign_in_provider": "google.com"
            }
        },
        "token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjFiYjI2MzY4YTNkMWExNDg1YmNhNTJiNGY4M2JkYjQ5YjY0ZWM2MmYiLCJ0eXAiOiJKV1QifQ..U5Gmr-vt_paxbUck2UNGlKifrVk2FhygoBGoxatTBcQ_j6wZi9FZs6s6-pajQLq5nrVIMOM_8W9yJN_gCg0V8W0gl2cmAH8uREZDg5G2lWOunTD8Nbze0yrg6us5_hctThZ8uxrXFD_kPvVLJO6tJZeoI8A2eW-kzg7xcP4B8_Y9qc6QpJguJf4PqxE7522bQ7fI3tu_T0vNAk0Bt36o-K-Adr1guL4Mxj3PNs0WKEPen9iiirAoPjOFtVY_Pk46-paXwVtBLP8tC3H1ZN0ysp9DwD99JsejvGUWthlX9Qz_0GqnrDXBrst3O5OFwQKYzbbtv_vs_A8PdJc6A9Uk-A",
        "authTime": "Thu, 18 May 2023 14:20:31 GMT",
        "issuedAtTime": "Thu, 18 May 2023 14:43:54 GMT",
        "expirationTime": "Thu, 18 May 2023 15:43:54 GMT",
        "signInProvider": "google.com",
        "signInSecondFactor": null
    },
    "pendingToken": null,
    "providerId": "google.com",
    "signInMethod": "google.com"
}