Async function does not return a response

I am new to Javascript. I am trying to read a few files and construct a JSON object response. I am able to run the entire code, however, one last piece is remaining, I am not getting a response from the async function.

const path = require('path')
const fs = require('fs/promises');

const getProductDetailByProductID = async (id) =>{
    const productsFile = path.join(__dirname, 'tasks', 'products.json')
    const customersFile = path.join(__dirname, 'tasks', 'customers.json')
    const reviewsFile = path.join(__dirname, 'tasks', 'reviews.json')
    const imagesFile = path.join(__dirname, 'tasks', 'images.json')

    const product = await fs.readFile(productsFile, 'utf-8').then(res => {
        const data = JSON.parse(res)["products"].filter(product => product.id === id)
        return data[0]
    })

    const response = await fs.readFile(reviewsFile, 'utf-8')
        .then(allReviews => {
            return JSON.parse(allReviews)["reviews"].filter(review => review.product_id === product.id)
        })
        .then(async (productReviews) => {
            const reviewsData = []

            for (const review of productReviews) {
                let customer = await fs.readFile(customersFile, 'utf-8').then(res => {
                    return JSON.parse(res)["customers"].filter(customer => customer.id === review.customer_id)
                })
                if(customer) customer = customer[0]
                const images = await fs.readFile(imagesFile, 'utf-8').then(res => {
                    return JSON.parse(res)["images"].filter(image => review.images.includes(image.id))
                })
                reviewsData.push ({
                    "id": review.id, 
                    "rating": review.rating,
                    "customer": customer,
                    "images": images
                })
            }
            return reviewsData
        })
        .then(reviewsData => {
            return {
                    "id": product.id,
                    "name": product.name,
                    "reviews": reviewsData
                }
        })

    console.log(response) // This is working
    return response
}
getProductDetailByProductID(1) // This does not fetch anything

I am running this file using below command

nodemon task.js
                    

Also, please recommend a better way of writing this code if it is poorly written. Please share a link for the same.

JS has object wrappers to let me check primitive’s “property” exists or not, how do I let TS work like that?

The return value of XMLValidator.validate is either true or ValidationError, which has err propery.

validate(  xmlData: string,  options?: validationOptionsOptional): true | ValidationError

Because javascript uses object wrappers for boolean primitive I can just check the err property exists or not to see if the validation succeeds.

const result = XMLValidator.validate(message)
if (result.err) { // How to I make it work in ts?
   console.log(`invalid XML)
} else {
  console.log(`XML)
}

But typescipt won’t let me do that, it will complain Property 'err' does not exist on type 'true'

I don’t like the idea of checking the return type first because I feel it is wordy. How do I write the ts code here as concise as my js code?

MongoDB: How to create an object that has an array of objects as a field?

I have this schema:

const SingleExerciseSchema = new Schema({
    exerciseName: { type: String },
    setLog: [{
        weight: { type: Number },
        sets: { type: Number },
        reps: { type: Number },
    }],
});

Then I get data like this, as a json:

const DATA = [
    { exerciseName: "Squat",
      setLog: [
        {weight: 65, sets: 1, reps: 5},
        {weight: 55, sets: 2, reps: 5},
        {weight: 45, sets: 1, reps: 5},
      ]
    },
    { exerciseName: "Overhead Press",
      setLog: [
        {weight: 27.5, sets: 1, reps: 5}
      ]
    }
  ];

I want to loop over the data and create my SingleExercise objects from it.

Like this:

const exerciseObjectList = (req.body).map(
    (exerciseLog) => new SingleExercise({
      exerciseName: req.body.exerciseName,
      setLog: // stuck here
    })

However, I’m not sure to update/access the setLog fields, syntax wise. I want something like this:

const exerciseObjectList = (req.body).map(
    (exerciseLog) => new SingleExercise({
      exerciseName: req.body.exerciseName,
      setLog: {
        (req.body.setLog).map(
          (set) => {
            weight: set.weight,
            sets: set.sets,
            reps: set.reps,
          }
        )
      }
    })
  );

but it’s obviously wrong syntax.

Interactive buttons in video player

I am trying to make a simple index.php where I want to display a video but when the video reaches 20 seconds ask the user “Are you listening” or something like this.
After reading so many tutorials I achieved displaying the button on the 20th second but when I click on the button the video is not resuming for the next 20 seconds but for a few milliseconds.
The complete idea is to ask every 20 seconds “Are you listening”
Here is my code now:

<body>
  <div class="video-container">
    <video id="myVideo" controls>
      <source src="video.mp4" type="video/mp4">
    </video>
    <button class="interactive-button" data-time="20">Are you listening carefully?</button>
    
  </div>

  <script>
    document.addEventListener("DOMContentLoaded", function () {
      const video = document.getElementById("myVideo");
      const buttons = document.querySelectorAll(".interactive-button");

      buttons.forEach((button) => {
        const time = parseInt(button.dataset.time);
        button.addEventListener("click", function () {
          if (video.currentTime >= time) {
            video.currentTime = time; 
            video.play(); 
          }
        });
      });

      video.addEventListener("timeupdate", function () {
        const currentTime = video.currentTime;
        buttons.forEach((button) => {
          const time = parseInt(button.dataset.time);
          if (currentTime >= time) {
            button.style.display = "block";
            video.pause();
          } else {
            button.style.display = "none";
          }
        });
      });
    });
  </script>
</body>

how to delete specific image using jquery in sortable jquery

i have an image section in html, where images are shown as grid and user can drag and rearrange, according to the rerrangement the image names are stored in the hidden input box, this is working fine, my code is like below:

$(function() {
  $("#imageListId").sortable({
    update: function(event, ui) {
      getIdsOfImages();
    } //end update  
  });
});

function getIdsOfImages() {
  var values = [];
  $('.listitemClass').each(function(index) {
    values.push($(this).attr("id")
      .replace("im", ""));
  });
  $('#outputvalues').val(values);
}
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


<style>
  /* image dimension */
  
  .listitemClass img {
    height: 200px;
    width: 100%;
  }
  /* imagelistId styling */
  
  #imageListId {
    margin: 0;
    padding: 0;
    list-style-type: none;
  }
  
  #imageListId div {
    margin: 0 4px 4px 4px;
    padding: 0.4em;
    display: inline-block;
  }
  /* Output order styling */
  
  #outputvalues {
    margin: 0 2px 2px 2px;
    padding: 0.4em;
    padding-left: 1.5em;
    width: 250px;
    border: 2px solid dark-green;
    background: gray;
  }
  
  .listitemClass {
    border: 1px solid #006400;
    width: 25%;
  }
  
  .height {
    height: 10px;
  }
</style>

   <b>Drag and drop images to arrange</b>

<div class="height"></div><br>

<div id="imageListId" style="display:flex">

<div id="im1" class="listitemClass">
    <img src="https://picsum.photos/id/237/200/300" alt="">
</div>

<div id="im2" class="listitemClass">
    <img src="https://picsum.photos/id/230/200/300" alt="">
</div>

<div id="im3" class="listitemClass">
    <img src="https://picsum.photos/id/235/200/300" alt="">
</div>
<div id="im4" class="listitemClass">
    <img src="https://picsum.photos/id/233/200/300" alt="">
</div>


  </div>

  <form action="" method="post" enctype="multipart/form-data" style="margin-top:3%">

    <div id="outputDiv">
      <input id="outputvalues" type="hidden" value="" name="nname" />
      <input type="hidden" value="<?=$nname1?>" name="nname1" />
    </div>

    <button type="submit" name="editcategory" class="btn btn-primary">SAVE</button>

  </form>

i want to delete some specific image from this grid, please tell me how do i accomplish this, thanks in advance

Error in inserting data from React Native (Android App) to MySql Database

I am trying to Insert my Form Data from React Native CLI (Android App) to MySQL database but when I press Submit, it always shows a message: “An error has occurred: Network request failed”.
There is an API named as form_insert.php which is meant to insert all the fields of the FormData from React native CLI to mySQL database.
I have tried different combinations of code but everytime error occurs.
Moreover, I tested my API in PostMan tool and the API is working perfectly but with the combination of code snippet of react native app, I am Encountering errors.
Below will be given the Code Snippet of React Native CLI along with the API code.

Code Snippet of React Native CLI Where the API is called:

    `const handleFormSubmit = async () => {
    if (
    customerName &&
    customerNumber &&
    carModel &&
    carNumber &&
    selectedOption &&
    selectedOption2 &&
    selectedOption3
    ) {
    const formData = new FormData();
    formData.append('cusCode', customerCode);
    formData.append('cusName', customerName);
    formData.append('cusNum', customerNumber);
    formData.append('carModel', carModel);
    formData.append('carNum', carNumber);
    formData.append('carBrand', selectedOption);
    formData.append('engineType', selectedOption2);
    formData.append('vehType', selectedOption3);
    formData.append('lubeName', lubeName);
    formData.append('lubeLtr', lubeNumber);
    formData.append('dateTime', new Date().toString());
  
      
    try {
    const response = await fetch('https://10.0.2.2:80/api/form_insert.php', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/x-www-form-urlencoded', // Update the content type
    },
    body: new URLSearchParams(formData), // Use URLSearchParams to format the form data
    });

    if (response.ok) {
    alert('Data inserted successfully');
    console.log(await response.json());
    } else {
    throw new Error('An error occurred during the request');
    }
    } 
    catch (error) {
    console.error(error);
    alert('An error occurred: ' + error.message);
    }

    onSubmit(formData);
    }
    };`
  

API code:

` <?php
// Allow requests from any origin
header(“Access-Control-Allow-Origin: *”);
// Allow specific HTTP methods
header(“Access-Control-Allow-Methods: POST”);
// Allow specific headers
header(“Access-Control-Allow-Headers: Content-Type”);

$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'pso_app';

$conn = new mysqli($hostname, $username, $password, $database);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Retrieve data from the form
$customerCode = isset($_POST['cusCode']) ? $_POST['cusCode'] : null;
$customerName = isset($_POST['cusName']) ? $_POST['cusName'] : null;
$customerNumber = isset($_POST['cusNum']) ? $_POST['cusNum'] : null;
$carModel = isset($_POST['carModel']) ? $_POST['carModel'] : null;
$carNumber = isset($_POST['carNum']) ? $_POST['carNum'] : null;
$carBrand = isset($_POST['carBrand']) ? $_POST['carBrand'] : null;
$engineType = isset($_POST['engineType']) ? $_POST['engineType'] : null;
$vehicleType = isset($_POST['vehType']) ? $_POST['vehType'] : null;
$lubeName = isset($_POST['lubeName']) ? $_POST['lubeName'] : null;
$lubeNumber = isset($_POST['lubeLtr']) ? $_POST['lubeLtr'] : null;
$dateTime = isset($_POST['dateTime']) ? $_POST['dateTime'] : null;

// Prepare and bind the INSERT statement
$stmt = $conn->prepare("INSERT INTO lube_sale (cus_code, cus_name, cus_num, car_model, car_num,     car_brand,     

engine_type, veh_type, lube_name, lube_ltr, date_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssssssss", $customerCode, $customerName, $customerNumber, $carModel, $carNumber,                
$carBrand, $engineType, $vehicleType, $lubeName, $lubeNumber, $dateTime);

// Execute the statement
$stmt->execute();

// Close the statement
$stmt->close();

// Close the database connection
$conn->close();
?>

`

How to get URL parameter inside javascript?

im new to javascript and php.
Here is my problem I’m trying to post url with URL parameter inside javascript. How can I achieve it?

Here is my page URL : https://localhost/test/home.php?id=07

<script >
        function showStackedVerticalChart() {
    {
                **//i want to add above URL parameter to this URL (id=07)**
        $.post("partials/get-chart-data.php?chart_type=vertical-bar&id=07",
            function(data) {
                var chartdata = {
                    labels: ["Line 1","Line 2","Line 3","Line 4","Line 5","Line 6","Line 7","Line 8","Line 9","Line 10",
                    "Line 11","Line 12","Line 13","Line 14","Line 15","Line 16","Line 17","Line 18","Line 19","Line 20",
                    "Line 21","Line 22","Line 23","Line 24","Line 25","Line 26","Line 27","Line 28","Line 29","Line 30","Line 31","Line 32"],
                    datasets: data
                };

                var graphTarget = $("#stacked-vertical-chart");

                var graph = new Chart(graphTarget, {
                    type: 'bar',
                    data: chartdata,
                    options: {
                        
                        scales: {
                            xAxes: [{
                                barPercentage: 0.5,
                                stacked: true
                            }],
                            yAxes: [{
                                stacked: true
                            }]
                        }
                    }
                });
            });
    }
}
</script>

I tried adding this inside the script.

$id = $_GET['id'];
$.post("partials/get-chart-data.php?chart_type=vertical-bar&'" . $mo . "' "

Solidjs: Use a Map in createStore does not update on change

I’m fairly new to solidjs and maybe I’ve overlooked something but given the following example I try to understand the issue here:

const [state, setState] = createStore({ items: new Map() }); // e.g. Map<number, string>

In a component let’s say I want to use a derived state of the store like so:

export const Overview = () => {
    const count = () => state.items.size;

    return (<div>{count()</div>);
};

If I now add a new entry to the map I would have expected that the count property would be updated automatically since I use the dependency.

I’ve tried this example with an array instead of the map and this is working just fine and the component displays the correct and expected value(s).

Can somebody point me maybe to the correct section in the documentation or explain why a Map is not working but an array does?

C# PageMethods javascript callback function is not being called

I have java script function in an aspx page as shown below which calls below line

PageMethods.PopulateData(x, y, z, onSucceeded_PopulateData, onFailed_PopulateData)

The onSucceeded_PopulateData() call back java script function is not being fired if the page remained idle for more than 1 minute.

Can anybody provide solution for this?

datatable with selectInputs resets back to left after selection

I am using selectInputs in a column of a DT datatable in a Shiny app. Thanks to help here, I am including some JavaScript to selectize the selectInputs to keep the style and search capability. It is a wide table, so the selectInputs require scrolling horizontally to see them. When I make a selection in any of the selectInputs the first time, everything works fine. However, when I click any of the selectInputs a second time, the page scrolls back to the left and the selectInputs are out of view. How can I keep the style and search capability I have but prevent this from happening?

Example:

library(shiny)
library(DT)

# Function to selectize one or more input ids
selectize_ids <- function(ids) {
  myStrings <- as.character(sapply(ids, function(id) {
    paste0("  $('#", id, "').selectize();")
  }))
  c(
    "function(settings){",
    myStrings,
    "}"
  )
}

shinyApp(
  ui = fluidPage(
    div(style = "display: none;", selectInput(inputId = "dummy", label = NULL, choices = 1:2)),
    fluidRow(DT::dataTableOutput("mytable"))
  ),
  server = function(input, output, session) {
    df <- as.data.frame(matrix(data = paste0("text", 1:60), ncol = 20))
    colnames(df) <- paste0("column", 1:ncol(df))
    df$myselect <- sapply(1:nrow(df), function(i) {
      as.character(selectInput(
        inputId = paste0("myselect_", i),
        label = NULL,
        choices = c("option1", "option2", "option3")
      ))
    })
    select_ids <- paste0("myselect_", 1:nrow(df))
    output$mytable <- DT::renderDataTable({
      DT::datatable(
        data = df,
        escape = F,
        options = list(
          initComplete = JS(selectize_ids(select_ids))
        )
      )
    })
  }
)

Cant get button value when clicked the icon inside button in react js

So Im trying to get the value from a button. This my button:

<button
  className="toggle__btn"
  value={el._id}
  onClick={toggle}
>
     <i className="fa-solid fa-circle-info fs-4"></i>
</button>

This my function:

const toggle = (event) => {
    const id = event.target.value;
    console.log(id);
  };

The problem is I can’t get the value if I click the icon, but I can when I click outside the icon but still inside the button(there is blank space outside the icon). I want it to return the id even when the icon is clicked. How to do so? Why does this happen?

Values in array read in from d3.csv are undefined outside of function despite global variable declaration

Thank you in advance for your help!
I have declared four arrays globally in my code. Then, in the function to read the data from the csv, I assign the data values to array elements. However, the array elements are undefined outside of this function, and I can’t seem to find the issue…
I am using d3 version 7 () and Google Maps Javascript API.

My CSV file is formatted Project_Name, Artist, Lat, Long – with around 300 values.

// Request needed libraries.
const { Map, InfoWindow } = await google.maps.importLibrary("maps");
const { LatLng } = await google.maps.importLibrary("core");
const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker");

//Global Vars
let map;
let projectName = [];
let artist = [];
let lat = [];
let long = [];
let markers = [];


async function data() {
  d3.csv("/data/single.csv", function(d) {
    return {
      projectName: +d.Project_Name,
      artist: +d.Artist,
      lat: +d.Latitude,
      long: +d.Longitude,
    }
  }).then(function(d) {
    for (var i = 0; i < d.length; i++) {
      projectName[i] = d[i].Project_Name;
      artist[i] = d[i].Artist;
      lat[i] = parseFloat(d[i].Latitude);
      long[i] = parseFloat(d[i].Longitude);
    }
  });
}



function createMarkers(m){
  for (var z=0; z < lat.length; z++) {
    markers[z] = new google.maps.Marker({
      position: new google.maps.LatLng(lat[z], long[z]),
      map: m,
      title: projectName[z],
    });
  } 
}

async function initMap() {
  
  const map = new Map(document.getElementById("map"), {
    zoom: 11,
    center: { lat: 37.4239163, lng: -122.0947209 },
    mapId: "[MAP ID]",
    mapTypeControl: false,
  });
  const infoWindow = new google.maps.InfoWindow({
    content: "",
    disableAutoPan: true,
  });
  
  //READ CSV FILE
  data();
  
  //MARKERS
  createMarkers(map);
  
}

initMap();

I tried using await, that didn’t solve the problem. Also tried to use setTimeout, which resulted in the value of NaN instead of undefined.

How can I get a user via UserID in a slash command?

I have been programming a discord bot, following tutorials as needed since I am quite new, but I have come across a problem that, as simple as it sounds, I can’t seem to solve.
I am trying to draw a leaderboard, and for each placement on the leaderboard I want to get the user’s avatar to draw onto the leaderboard. To do this, I want to be able to get the user through just the UserId. However, I am doing all of this in a separate slash command. Here is a very simplified version of what I’m trying to do to give some context and/or maybe a better explanation:

const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js');
// ... some functions and what not go here
module.exports = {
   //... lines for setting up the command go here

   async execute(interaction){
       const data = fetchData();
       // ... a bunch of stuff, ordering my data, etc.
       data.forEach(async (userData, index) => {
          // And here begins my issue. The line below is just what I have attempted to do
          const target = interaction.guild.members.cache.get(userData.UserId); 
       });
   };
}

I have done a fair bit of research, and the only feasible solution I could find (which you can see is in the above example code) is to do
const target = interaction.guild.members.cache.get("User_ID");
However, even though I can log the return in the console, if I tried to do something like “target.user” it would say target is undefined. And, in case it helps, yes, I do have GuildMembers in my intents.

error RangeError: Maximum call stack size exceeded NextJS/React fix

I am trying to create a form where i can add a new product to my website database with NextJs and i encounter this error: error RangeError: Maximum call stack size exceeded

The following lines of code is for admin/create-product:

"use client"
import { useState } from "react"
import { useRouter } from "next/navigation";


import Form from "@components/Form";
const CreateProduct = () => {

    const [product, setProduct] = useState({
        title:'',
        image: [],
        desc: '',
        qty: 0,
        price: 0,
        category:''
    });
    const [submitting, setSubmitting] = useState(false)

    const router = useRouter()

    const createProduct = async (e) => {
        e.preventDefault()
        setSubmitting(true)

        try {
            const response = await fetch ('/api/products/new',{
                method: 'POST',
                body: JSON.stringify({
                    title: product.title,
                    image: product.image,
                    desc: product.desc,
                    qty: product.qty,
                    price: product.price,
                    category: product.category
                  }),
            })
            if(response.ok){
                router.push('/')
                console.log('New Product Added')
            }

            
        } catch (error) {
          console.log(error)  
        } finally{
            setSubmitting(false)
        }

    }

  return (
    <>
      <Form
          product = {product}
          setProduct = {setProduct}
          submitting = {submitting}
          setSubmitting = {setSubmitting}
          handleSubmit = {createProduct}
      />
    </>
  )
}

export default CreateProduct

And the following code is for Form:

import Link from "next/link"

const Form = ({ product, setProduct, submitting, setSubmitting, handleSubmit }) => {
  return (
    <Form onSubmit = {handleSubmit} className='mt-10 w-2/3 max-w-2xl flex flex-col gap-7 glassmorphism'>
         <label>
          <span className='font-semibold text-base text-gray-700'>
            Product Title
          </span>
          <input
            value={product}
            onChange={(e) => setProduct({ ...product, title: e.target.value })}
            type='text'
            placeholder='Title'
            required
            className='w-full flex rounded-lg mt-2 p-3 text-sm text-gray-500 outline-0'
          />
          
        </label>    
    </Form> 
  )
}

export default Form

I just need to fix the error, Also, this is the complete error it’s displaying “error: RangeError: Maximum call stack size exceeded at Form (./components/Form.js:17:92)”

Pinia state not updating when using spread operator({…object}) in $patch

Hello Stack Overflow Community,

I’m currently working on a Vue.js project utilizing the Pinia store. I’m running into an issue where my state data is not updating as expected when using the spread operator (…) in combination with the $patch method.

Here’s a snippet of the code I’m using:

const { password, createtime, ...rest } = res.data;
this.$patch(rest);

In this case, my Pinia store’s state is not being updated as expected. Specifically, the properties in the rest object should be applied to the store’s state using the $patch method, but I’m finding that the state remains unchanged after this operation.

I was under the impression that using the spread operator in this way would create a new object containing all properties of res.data except for password and createtime, and that these properties could then be applied to my store’s state using the $patch method.

I’m unsure why this is not working as expected, and I was hoping someone might be able to shed some light on this issue. Any insights would be greatly appreciated.

Thank you in advance for your time and help.

Best regards,

“I tried directly setting each individual property in the $patch method as follows:

this.$patch({
  id: res.data.id,
  status: res.data.status,
  username: res.data.username,
  phone: res.data.phone,
  memberLevelId: res.data.memberLevelId,
});

This method worked as expected and the state was correctly updated. From this, I concluded that the $patch method itself is functioning correctly and that the issue must lie with the spread operator.

My expectation was that using the spread operator in $patch would allow me to update multiple properties at once, reducing redundancy in my code. However, in practice, the state remained unchanged when I attempted this approach.

What I would like to understand is why the spread operator did not produce the desired result, and what I can do to achieve this effect.”