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>

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!!!

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.

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");
      }   
    });

Javascript: object cannot be updated

I have an object named “order”, and I am trying to change some values within in. Below is the code that I use, but it is showing me some weird behaviour.

All console.log output are included as comments after the corresponding line. As far as I can tell, the code is working because when I try to console.log the new value, it is correctly printed on the console.

The problem happens at my last line of code. When I am printing the entire object on console, and navigate to the two values that I just changed, they are both showing the old value “0.60”, instead of the new value “1.00”.

What is causing this bug?

console.log("this.calculate_discount(product)", this.calculate_discount(product)); // 0.40
console.log("order.SubTotalDiscount", this.order.SubTotalDiscount); // 0.60
this.order.SubTotalDiscount = parseFloat(this.calculate_discount(product)) +
                              parseFloat(this.order.SubTotalDiscount);
this.order.SubTotalDiscount = parseFloat(this.order.SubTotalDiscount).toFixed(2);
console.log("order.SubTotalDiscount", this.order.SubTotalDiscount); // 1.00
console.log("order.totals[TOTAL_CODE_MAP.get('discount_b')].Amount",
                this.order.totals[TOTAL_CODE_MAP.get('discount_b')].Amount); // 0.60
this.order.totals[TOTAL_CODE_MAP.get('discount_b')].Amount = 
                parseFloat(this.calculate_discount(product)) +
                parseFloat(this.order.totals[TOTAL_CODE_MAP.get('discount_b')].Amount);
this.order.totals[TOTAL_CODE_MAP.get('discount_b')].Amount =
                parseFloat(this.order.totals[TOTAL_CODE_MAP.get('discount_b')].Amount).toFixed(2);
console.log("order.totals[TOTAL_CODE_MAP.get('discount_b')].Amount",
                this.order.totals[TOTAL_CODE_MAP.get('discount_b')].Amount); // 1.00
console.log("order", this.order);

Thank you!

Can play button be added to this code structure? (Shopify)

My following codes provide to show html video between the product images. In the mobile view, the play button is located in the middle of the video. Do you think it is possible to do the same in desktop view?

<div class="owl-carousel">
{% for image in product.images %}
{% if forloop.first == true %}
<figure>            
<img src="{{ image.src | img_url: '1024x1024' }}" alt="{{ image.alt | escape }}" class="product_variant_image">
</figure>
{% else %}
<figure>            
<img src="{{ image.src | img_url: '1024x1024' }}" alt="{{ image.alt | escape }}">
</figure>
{% endif %}
{% endfor %}
{% for media in product.media %}
{% if media.media_type == 'video' %}
{{ media | video_tag: controls: true, preload: true, image_size: "768x" }}
{% endif %}
{% endfor %}
</div>

What I want to see is ;

enter image description here

How to make angular find imports automatically in vs code

I have a angular project generated with nrwl/nx, I generated an model folder manually, but if I try to import something from it I have to do it manually. Is there anyway to make a file where I can put the path to my models and it will automatically be found?

I looked a bit and found this in my tsconfig.base.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "lib": ["es2017", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@moniesta-admin/auth-lib": ["libs/auth-lib/src/index.ts"],
    }
  },
  "exclude": ["node_modules", "tmp"]
}

I tried to add it like my auth-lib folder but that does not work either. This is how the index.ts of auth-lib looks:

export * from './lib/auth-lib.module';