How can I pass properties from a mapped Div to a function when a button is clicked?

I am mapping cards from an array in divs using the map() function, and I am trying to have each div include a button that will make a post request to an api. Each card in the array has a card id, which I am able to display when creating the divs using “card.id”. When I press the button, however, the addToCollection2 function is telling me that “card.id” is undefined. Can anyone tell me why it is said to be undefined?

Here is the html code:

<div className="cardImages">
        {cardsFetched ? (
          cards.data.map((card) => (
            <div className="searchedCards" key={card.id}>
              <div className="singleCard">
                <img src={card.images.small} />
                <p>Card ID : {card.id}</p>
                <button onClick={() => addToCollection2(card.id)}>
                  Add Card
                </button>
              </div>
            </div>
          ))
        ) : (
          <div>Searched cards will appear below</div>
        )}
      </div>

Here is the addToCollection2() JavaScript function:

async function addToCollection2(cardId) {
    //e.preventDefault;
    console.log(cardId);
    try {
      const body = { collection_id, cardId };
      const response = await fetch("https://tcgdex.herokuapp.com/collection", {
        mode: "cors",
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      console.log(response);
    } catch (err) {
      console.error(err.message);
    }
    return false;
  }

How to make clickable Header in React

I am trying to make my Header clickable to navigate to homepage but the code below is not working, I’m sure that there should be a really easy way to do it.

const Header = () => {
  const navigate = useNavigate()

  return (
    <div>
      <h1 className="font-weight-light display-1 text-center" onClick={navigate('/')}>
        The X app
      </h1>
    </div>
  )
}

Passing data up through nested functions in .js

Coding beginner here. I’ve got a page-js script below which when a dropdown is changed it triggers function getDrawNumOne, which in turn runs a function and retrieves two pieces of data from a GoogleSheet (drawNumReturnOne[0] & [1]). I want to pass the returned drawNumReturnOne[1] up through getDrawOneNum and then on into doStuff for use there – but am struggling on how to do this in a slick way, given I cannot call variables outside of their function scope. Do I need multiple returns up through the function stack or is there another, better way? All advice gratefully accepted, thanks.

document.getElementById("btn").addEventListener("click",doStuff);
document.getElementById("m_p1").addEventListener("onchange",getDrawNumOne);
   
function doStuff(){    
   var userInfo ={};
   userInfo.m_p1 = document.getElementById("m_p1").value;
   userInfo.m_s1 = ######;
   google.script.run.userClicked(userInfo);
    
   }
   
function getDrawNumOne(){
var drawNumOne = document.getElementById("m_p1").value;
   google.script.run.withSuccessHandler(updateDrawNumOne).getDrawNo(drawNumOne); 
   
}
function updateDrawNumOne(drawNumReturnOne){
   document.getElementById("draw1").value = drawNumReturnOne[0];
   ###### = drawNumReturnOne[1];
}

How to filter in grpahql github api by MergeableState

So I have the following block of code that returns me list of PR with their mergeability status such as ‘MERGEABLE’, ‘CONFLICTING’, etc. I want to understand if there is anyway to filter inline by mergeablestate. I can filter the result obtained after this using js or anything else. I wanted to understand for any way to do it directly in graphql script. Looked up the docs could not find a way

{
      repository(owner: "fireship-io", name: "git-sticker") {
        pullRequests(first: 1, states: [OPEN]) {
          nodes {
            id
            number
            changedFiles
            deletions
            mergeable
            author {
              url
            }
          }
        }
      }
    }

I tried

pullRequests(first: 1, states: [OPEN], mergeable: [MERGEABLE))

But got an error saying mergeable is not a valid argument for pullRequests.

Alpine.js – show/hide div based from select input values

I’m trying to show and hide div’s based from a select box selected value. I have my select boxes working so that it changes the value like so:

// x-data="{ week: false, day: false }

            <select @change="week = $event.target.value">
                <option x-bind:value="Week 1">Week 1</option>
                <option x-bind:value="Week 2">Week 2</option>
                <option x-bind:value="Week 3">Week 3</option>
            </select>
            <select @change="day = $event.target.value">
                <option x-bind:value="1">Monday</option>
                <option x-bind:value="2">Tuesday</option>
                <option x-bind:value="3">Wednesday</option>
                <option x-bind:value="4">Thursday</option>
                <option x-bind:value="5">Friday</option>
            </select>
            <span x-text="'option '+ week"></span>
            <span x-text="'option '+ day"></span>

I am then trying to show and hide divs based on the selections like so, but having no luck.

<div :class="week !== {{ $week['name'] }} ? 'hidden' : 'block'">
     <p>{{ $week['name'] }}</p>
</div>

How can I correctly set the class?

I want to run my react native code synchronously

Im new to react native and Im working on a react native program, Im trying to run my code synchronously using useEffect, I tried to use await and promises but didn’t work, this is how the code looks like

useEffect(() => {
    dashBoard();
    ret3();
  }, []);

  const [flag, setFlag] = useState(false);
  const [within, setWitin] = useState(0);
  const [above, setAbove] = useState(0);
  const [under, setUnder] = useState(0);
  const [bgArr, setBgArr] = useState([]);
  const [lastBG, setLastBG] = useState(0);
  const [lastBGtime, setLastBGtime] = useState('');
  const [addBGlevel, setAddBGlevel] = useState(0);
  const [startBG, setSBGP] = useState(0);
  const [reason, setReason] = useState('');

  //===========================Functions===============

  const addBG = () => {
    var time = new Date(); // Mon Jan 31 2022 23:07:59 GMT+0300 (+03)
    var timeString = time.toString();

    try {
      db.transaction(tx => {
        tx.executeSql(
          'INSERT INTO BGLevel (UserID, BGlevel, DateTime) VALUES (?,?,?)',
          [222, addBGlevel, timeString],
        );
        console.log('inserted!!');
      });
    } catch (error) {
      console.log(error);
    }

    if (addBGlevel <= 70) {
      navigation.navigate('hypo');
    } else if (addBGlevel > startBG) {
      //startbgcorr =150
      navigation.navigate('Calc');
    }else if (reason == '1'){
      navigation.navigate('Calc');
    }
  };

  const dashBoard = async () => {
    await retrieveDash2();

    var w = 0;
    var a = 0;
    var u = 0;

    for (let i = 0; i < bgArr.length; i++) {
      if (bgArr[i] >= fromBGHome && bgArr[i] <= toBGHome) {
        w++;
      } else if (bgArr[i] > toBGHome) {
        a++;
      } else if (bgArr[i] < fromBGHome) {
        u++;
      }
    }

    var total = w + a + u;
    var m = (a / total) * 100;
    if (m >= 50) {
      setFlag(true);
    } else {
      setFlag(false);
    }

    setWitin(w);
    setAbove(a);
    setUnder(u);
  };
  //==================================================
  //===========================RETRIVE================
  const retrieveDash = () => {
    // insulinPen table
    try {
      db.transaction(tx => {
        tx.executeSql(
          'SELECT UserID, fromBG, toBG FROM patientprofile',
          [],
          (tx, results) => {
            var rows = results.rows;

            for (let i = 0; i < rows.length; i++) {
              var userid = rows.item(i).UserID;

              if (userid == 222) {
                fromBGHome = rows.item(i).fromBG;
                toBGHome = rows.item(i).toBG;

                return;
              }
            }
          },
        );
      });
    } catch (error) {
      console.log(error);
    }
  };

  //==================================================
  const retrieveDash2 = async () => {
    await retrieveDash();
    var time = new Date(); // Mon Jan 31 2022 23:07:59 GMT+0300 (+03)
    var bgArr1 = [];
    // insulinPen table
    try {
      db.transaction(tx => {
        tx.executeSql(
          'SELECT UserID, BGlevel, DateTime FROM BGLevel',
          [],
          (tx, results) => {
            var rows = results.rows;
            var lastString = rows.item(rows.length - 1).DateTime;
            var d = new Date(lastString);
            var momFormat = moment(d).format('yyyy/MM/DD  hh:mm a');

            setLastBGtime(momFormat);
            setLastBG(rows.item(rows.length - 1).BGlevel);

            for (let i = 0; i < rows.length; i++) {
              var timeString = rows.item(i).DateTime;
              var toObj = new Date(timeString);
              var bgHome = rows.item(i).BGlevel;
              var userid = rows.item(i).UserID;
              console.log((time - toObj) / (1000 * 60 * 60));

              if ((time - toObj) / (1000 * 60 * 60) <= 168) {
                //168 is the last 7 days in hours

                bgArr1.push(bgHome);
              }
            }
            setBgArr(bgArr1);
            console.log(bgArr1 + '   This is bg array');
            console.log(
              fromBGHome + '  ' + toBGHome + '   This is from and to',
            );
          },
        );
      });
    } catch (error) {
      console.log(error);
    }
  };

  //==================================================
  const ret3 = () => {
    try {
      db.transaction(tx => {
        tx.executeSql(
          'SELECT UserID startBG_correct FROM patientprofile',
          [],
          (tx, results) => {
            var rows = results.rows;
            for (let i = 0; i < rows.length; i++) {
              var UID = rows.item(i).UserID;
              if (UID == 222) {
                

                var start = rows.item(i).startBG_correct;
                setSBGP(start);
              }
            }
          },
        );
      });
    } catch (error) {
      console.log(error);
    }
  };

and I want the functions to run before the interface is completely loaded so I used the following way

{bgArr.length > 0 && (within > 0 || above > 0 || under > 0) ? (
          <PieChart
            data={data}
            width={widthScreen}
            height={150}
            chartConfig={chartConfig}
            accessor={'population'}
            backgroundColor={'#ECECEC'}

            //absolute
          />
        ) : (
          <ActivityIndicator size="large" />
        )}

but it keeps loading and never show the interface until I run the program again
I need the code to work directly when loading the page in the following order
1-retrieveDash
2-retrieveDash2
3-dashBoard

THREE.FontLoader() doesn’t work in Three JS

I’m new in Three JS and I would like to create a 3D text. I followed most of the tuto to create it, but I have an error even if I follow all the steps or copy/past the tuto’s code.
This is my component :

import * as THREE from "three";
import bumped from "../Bumped.json";

const Text = () => {
  const font = new THREE.FontLoader().parse(bumped);

  const textOptions = {
    font,
    size: 5,
    height: 1,
  };

  return (
    <mesh>
      <textGeometry attach="geometry" args={["three.js", textOptions]} />
      <meshStandardMaterial attach="material" />
    </mesh>
  );
};

export default Text;

My errors :
//THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js

//Uncaught TypeError: (intermediate value).parse is not a function

Of course, this component will be inside a Canvas element in the main page.
My console Errors : My console Errors

How to connect button to local storage?

I am a beginner and learning using tutorials. This tutorial involves using an API to display pictures. I have included a modal that has a button.

My question is, how would I make the button connect with local storage so it could save the image that is clicked to favourites?

Do I have the right idea in having a function on the button, adding event listener click to add to favourites?

Appreciate any help and examples, thanks.

https://jsfiddle.net/neg4byd5

      <div id="myModal" class="modal">
        <span class="close">&times;</span>
        <img class="modal-content" id="img01">
        <span><button>Add To Favourites</button></span>
        <div id="caption"></div>
      </div>  
// Save Text
    const saveText = document.createElement("p");
    saveText.classList.add("clickable");
    if (page === "results") {
      saveText.textContent = "Add To Favorites";
      saveText.setAttribute("onclick", `saveFavorite('${result.url}')`);
    } else {
      saveText.textContent = "Remove Favorite";
      saveText.setAttribute("onclick", `removeFavorite('${result.url}')`);
    }


// Update the DOM
function updateDOM(page) {
  // Get favorites from local storage
  if (localStorage.getItem("nasaFavorites")) {
    favorites = JSON.parse(localStorage.getItem("nasaFavorites"));
  }
  imagesContainer.textContent = "";
  createDOMNodes(page);
  showContent(page);
}


// Add result to favorites
function saveFavorite(itemUrl) {
  // Loop through the results array to select favorite
  resultsArray.forEach((item) => {
    if (item.url.includes(itemUrl) && !favorites[itemUrl]) {
      favorites[itemUrl] = item;
      // Show save confirmation for 2 seconds
      saveConfirmed.hidden = false;
      setTimeout(() => {
        saveConfirmed.hidden = true;
      }, 2000);
      // Set Favorites in Local Storage
      localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
    }
  });
}

// Remove item from favorites
function removeFavorite(itemUrl) {
  if (favorites[itemUrl]) {
    delete favorites[itemUrl];
    localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
    updateDOM("favorites");
  }
}

// On Load
getNasaPictures();

Select multiple options by default using chosen plugin

I am using a chosen plugin for my multi-select list. Here I want to select various options by default. I tried to follow some responses from this thread, and ended up using:

$("#laptop_product").val("Macbook 12").trigger('change');
$('#laptop_product').trigger('chosen:updated');

where laptop_product is the id of the select element:

<select name="products" multiple class="standardSelect" id="laptop_product" onchange="tableRefresh()" tabindex="5">

and Macbook 12 is one of the values in the dropdown list. However, this is not working and the options don’t appear on the website.

Discord WebHook weiter leitung

Ich habe das Problem das ich von einer Website zu einem Discord Server weiterleiten möchte.
Code: code pen . io /TheBrain04/pen/QWOgKeO
Wenn ich auf senden clicke kommet die nachricht nur an ohne die input eingaben.

How to display data from database to chart using chart.js and ajax?

I want to display data from a database in a chart.
I want to display the data with date type input.
Whichever date value I select, the data for that date should be displayed. Ajax function sends the selected date to statisztika_datum_lekerdez.php with parameter q.
I tried it out to see if it really returns the received date value data. Using this:

  print json_encode($kiadas_ertek_osszes);
  print json_encode($kiadas_nev_osszes);

I get this back: [[1000],[8000]][[“food”],[“sport”]]
So the result is good. The problem is that it doesn’t show up in the chart.
How can I make the queried data appear in the chart?

Here is my code:

<?php
session_start();
require_once('connection.php');
?>
<!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">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="../css/statisztika.css">
    <title>Statisztika</title>
</head>

<body>

    <main id="main">

        <div class="container">


            <div id="tartarom">

                <!--?=============== Dátum ===============-->
                <form action="statisztika_datum_lekerdez.php" method="POST" id="statisztika_datum_form">
                    <input type="date" name="datum_lekerdezes" onchange="showData(this.value)" class="datum" id="datum_lekerdezes" required>
                </form>

                <div id="diagram_helye"> </div>

            </div>

        </div>

    </main>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="import { Chart, LineController, LineElement, PointElement, LinearScale, Title } from `chart.js`"></script>
    <script>
        function showData(str) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("diagram_helye").innerHTML = this.responseText;
                }
            };
            xmlhttp.open("GET", "statisztika_datum_lekerdez.php?q=" + str, true);
            xmlhttp.send();
        }
    </script>


</body>

</html>

<?php
session_start();
require_once('connection.php');
?>
<!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">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="../css/statisztika.css">
    <title>Statisztika</title>
</head>

<body>




    <?php
    require_once('connection.php');
    $q = ($_GET['q']);
    $id = $_SESSION['id'];
    $sql = "SELECT kategoria_nev, ertek FROM kiadas_tipusok_naponta WHERE user_id = $id AND datum = '$q'";

    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {

        $kiadas_ertek_osszes = array();

        foreach ($result as $row) {
            $kiadas_ertek_osszes[] = [
                $row["ertek"] * (-1)

            ];
        }
        foreach ($result as $row) {
            $kiadas_nev_osszes[] = [
                $row["kategoria_nev"]
            ];
        }
    } else {
        $kiadas_ertek_osszes[] = 0;
        $kiadas_nev_osszes[] = 0;
    }

    print json_encode($kiadas_ertek_osszes);
    print json_encode($kiadas_nev_osszes);

    ?>

    <div class="diagram_div">
        <canvas id="myChart_kiadasok"></canvas>
    </div>

    <script>
        const ctx = document.getElementById('myChart_kiadasok');
        const myChart_kiadasok = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: <?= json_encode($kiadas_nev_osszes) ?>,
                datasets: [{
                    label: 'Kiadások (Ft)',
                    data: <?= json_encode($kiadas_ertek_osszes) ?>,
                    backgroundColor: [
                        '#fea37f86',
                        '#fbc53193',
                        '#3171fb93',
                        '#ffa600b6',
                        '#5fa8d398',
                        '#50db268e',
                        '#eb4e4b94',
                        '#3fd5e698'
                    ],
                    hoverOffset: 6,
                    borderColor: [
                        'white'
                    ],
                    borderWidth: 0.8,
                    Fontsize: 30
                }]
            },
            options: {
                plugins: {
                    title: {
                        display: true,
                        text: 'Kiadások típusai'
                    },
                    legend: {
                        display: true,
                        position: 'bottom'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    </script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="import { Chart, LineController, LineElement, PointElement, LinearScale, Title } from `chart.js`"></script>



</body>

</html>

Getting a null value of input fields on mobile, but getting value on desktop

I am setting some values of input fields in local storage through JavaScript, it is working fine on desktop but when i check it on mobile i am getting null values.

Here is my code:

function reserve() {
  let date = document.getElementById("start").value;
  alert(date)
}
<input type="date" class="date" id="start" placeholder="Move Date">
<a href="/request"><input type="button" name="" value="Reserve Now" onclick="reserve()"></a>

Now i am getting null on mobile but get a value in alert on desktop.

How to make a working POST request in node.js bettween server and client. Express

MY CODE

To run:

  1. Open CMD on your laptop.
  2. (Assuming you have everything installed) Navigate to the project folder in CMD using cd.
  3. Type: node index.ts
  4. Go to a browser of your choice.
  5. Click on the address bar.
  6. Type localhost:3000
  7. Your good to go!

What i’m using:

  • Node.js
  • Express
  • Html
  • Typescript
  • Javascript
  • Fetch Api
  • (and if it helps) VS Code

What i’m trying to do:

  • I’m trying to make a POST request from public/index.html to index.ts using fetch.

The problem:

I get this as an output:

{I got a request!!}
{}

The empty {} should house a latitude & longitude as well as a status.


What I have tried:

  • I have tried changing the data that I am fetching (in index.html).
  • I have tried hard coding some values/strings in the fetched variables.
  • I have tried rearranging the code.

NOTHING WORKS!!!

What does “Convert overload list to single signature” mean?

I am still learning some basics of javascript programming (and programming in general).

In my Angular Firebase project, I get the following typescript error (or rather proposed change in visual studio code, i.e. the lightbulb icon):

Convert overload list to single signature

It is referring to the following code:

  updateUser(user: UserDocument): Observable<any> {
    const ref = doc(this.firestore, 'users', user.uid);
    return from(updateDoc(ref, { ...user }));
  }

When I convert it, it appears like this:

  updateUser(...args: [user: UserDocument]): Observable<any> {
    const ref = doc(this.firestore, 'users', user.uid);
    return from(updateDoc(ref, { ...user }));
  }

But now instead it is complaining Remove unused declaration of args and also it complains about the last bid { ...user } giving another lightbulb Import user from module "rxfire/auth"

I would appreciate it very much if someone gave a short explanation of what is going on?

Thank you!

EDIT: here are two screenshots just for extra clarity

enter image description here

enter image description here

Matter.js light bulb pull

I want it to react when I pull the light bulb

What’s the problem?

I want an alarm to come when I pull the light bulb

but got a error

Uncaught TypeError: Cannot read properties of undefined (reading ‘position’)

    group = Body.nextGroup(true);

  var ropeB = Composites.stack(width/2, 100, 10, 1, 10, 10, function(x, y) {
    return Bodies.rectangle(x , y, 20, 4, {
      collisionFilter: { 
       group: group 
      }, 
      render : ropeRenderStyle
    });
  });

  const lamp =  Matter.Bodies.circle(width/2, 210, 30, {
      density: 0.0005,
                frictionAir: 0.06,
                restitution: 0.3,
                friction: 0.01,
                render: {
                    sprite: {
                        texture: './img/lamp.png',
                        xScale: 0.12,
                        yScale: 0.14
                    }
                }
    })

  Composite.add(ropeB, lamp);

  Composites.chain(ropeB, 0.5, 0, -0.5, 0, {
      stiffness: 0.8,
      length: 1,
      render: ropeRenderStyle
    });

  Composite.add(
      ropeB,
      Constraint.create({
        bodyB: ropeB.bodies[0],
        pointB: { x: 0, y: 0 },
        pointA: { x: ropeB.bodies[0].position.x, y: ropeB.bodies[0].position.y },
        stiffness: 0.5,
        render : ropeRenderStyle
      })
    );

    Events.on(engine, 'collisionStart', () => {
      const { bodies } = engine.world;
      const lamp = bodies.find(body => body.label === 'Circle Body');
      if (lamp.position.y < height) {
        alert("click");
      }   
    });