How to created nested arrays from a nest of arrays?

I’m looking to return an array of objects which contains a sub array of objects.

The data I am extracting from contains an array of ‘projects’ with a bunch of properties and within this array there is an array of ‘work items’. I want to loop/map through the ‘projects’ array and return a new array of objects and within that there will be a ‘subtasks’ property which needs to contain another array of objects which has been developed from the ‘work items’ array within the ‘projects’ array.

Below is where I have got to so far. This is not what I want as I need the main object to just be created when it loops through the projects and then the ‘subtasks’ array to be created when it loops through the ‘work items’. I tried putting the overarching object above the ‘return project.workItems.map….’ line but I was getting syntax errors.

See below this code for an example of the expected output.

  let newProjects1 = projects.map((project, index) => {

  return project.workItems.map((workItem) => {
    return {
      TaskID: index,
      ProjectNo: project.projectNumber,
      TaskName: project.projectTitle,
      StartDate: new Date("11/11/2024"),
      EndDate: new Date(project.projectEnd),
      subtasks: [
        {
          TaskID: index,
          TaskName: workItem.name,
          StartDate: new Date("11/11/2024"),
          Duration: 80,
          Progress: 150,
        },
      ],
    };
  })
;

});

The final output needs to look something like this

  [
{
  TaskID: 1,
  ProjectNo: "29895",
  TaskName: "Stoneybridge WTW",
  StartDate: new Date(projects[0].projectStart),
  EndDate: new Date(projects[0].projectEnd),
  subtasks: [
    {
      TaskID: 1.1,
      TaskName: "Sodium Carbonate",
      StartDate: new Date(projects[0].projectStart),
      Duration: 4,
      Progress: 150,
      comments: "unlucky",
      subtasks: [
        {
          TaskID: 1.11,
          TaskName: "Design",
          StartDate: new Date(projects[0].projectStart),
          Duration: 30,
          Progress: 150,
        },
        {
          TaskID: 1.12,
          TaskName: "Workshop",
          StartDate: new Date(projects[0].projectStart),
          Duration: 30,
          Progress: 150,
        },
        {
          TaskID: 1.13,
          TaskName: "Site",
          StartDate: new Date(projects[0].projectStart),
          Duration: 30,
          Progress: 150,
        },
      ],
    },]

This is the input data i.e. the ‘projects’ array, which contains the ‘workItems’ array. This is just one of the objects in the ‘projects’ array

 [{
"projectNumber": 26278,
"projectTitle": "Ifon WTW",
"chemicals": ["sodium hypochlorite", "sodium hydroxide", "pacl"],
"projectStatus": "site survey",
"siteType": "SR",
"location": "Glasgow",
"contractType": "construction",
"designLead": "Craig Garvie",
"projectManager": "Isaac Stanton",
"projectType": "Other",
"spm": "Mark Tench",
"client": "Yorkshire Water",
"comments": "project going swimmingly",
"projectStart": "12/20/2022",
"projectEnd": "07/28/2024",
"createdAt": "2022-11-22T07:43:42Z",
"updatedAt": "2023-04-09T10:13:14Z",
"equipment": [
  { "name": "kiosk", "count": 2 },
  { "name": "tanker fill point", "count": 1 },
  { "name": "dosing skid", "count": 1 },
  { "name": "POA catchpot", "count": 1 },
  { "name": "Low Point Catchpot", "count": 0 },
  { "name": "MCC", "count": 1 }
],
"workItems": [
  {
    "name": "work Item 1",
    "siteSurveyStart": "11/29/2022",
    "siteSurveyEnd": "01/25/2023",
    "designStart": "02/14/2023",
    "designEnd": "03/06/2023",
    "workShopStart": "04/24/2023",
    "workShopEnd": "05/05/2023",
    "rsePremisesStart": "06/24/2023",
    "rsePremisesEnd": "07/09/2023",
    "siteStart": "08/20/2023",
    "siteEnd": "09/13/2023"
  },
  {
    "name": "work Item 2",
    "siteSurveyStart": "11/02/2022",
    "siteSurveyEnd": "01/05/2023",
    "designStart": "02/02/2023",
    "designEnd": "03/24/2023",
    "workShopStart": "04/11/2023",
    "workShopEnd": "05/19/2023",
    "rsePremisesStart": "06/19/2023",
    "rsePremisesEnd": "07/17/2023",
    "siteStart": "08/20/2023",
    "siteEnd": "09/23/2023"
  }
],
"chemical": [{ "name": "sodium carbonate" }, { "name": "sulphuric acid" }],
"projectPersonnel": [
  { "name": "daniel carey" },
  { "name": "erin donnelly" },
  { "name": "craig garvie" },
  { "name": "ryan watson" },
  { "name": "lewis scott" },
  { "name": "jack overfield" },
  { "name": "fidel hernandez" }
]

}]

why node.js backend can’t set cookie to frontend react.js?

i have trouble when i try to send a cookie from node to react for login auth, when i test with insomnia it works with no problem.

this is the result test from insomnia there’s a cookie in connection
Insomnia

this my devtools from chrome, as you guys can see there’s nothing in here
DevTools

// custom config CORS
const configCors = {
    origin : 'http://localhost:3000',
    credentials : true,
    allowedHeaders: ['Content-Type', 'Authorization']
}

// the cookie i want to set
res.cookie("refresh", refresh, {
          httpOnly: true,
          secure: false,
          maxAge: 24 * 60 * 60 * 1000, // in milliseconds
        })

Why cookies don’t exist in devtools react.js, but only exist in insomnia when I test it

for information :
Frontend React.js,
Backend Node.js

how to be creative? what is the answer to create following task [closed]

1.**** Task Form****:
Create a reactive form for adding and editing tasks.
Fields: Task Name, Description, Due Date.

2 Task List Component:
Create a component to display a list of tasks.
Display tasks with their names and due dates.
Include buttons to edit and delete each task.

  1. Chart Component:
    Implement a component for displaying a chart using Apex Charts.
    The chart should visualize the number of tasks due in the next 7 days.

4 Task Service:
Use a service to manage tasks (add, edit, delete, get tasks).
Use dependency injection to inject the service into components.

5 Routing:
Implement routing for the application with two routes:
Route 1: Display the Task List component.
Route 2: Display the Chart component.

6.** Navigation:**
Include a navigation bar with links to switch between the Task List and Chart views.

I have to create 3 different page 1st include form 2nd include list 3rd include chart?
would be great if you reply with codes.

About How to run a certain blockchain project

Hi. I’m new to blockchain and I want to know how to run a certain blockchain project. This is it’s github repository.https://github.com/virajchandra51/MediVault. I have been trying for days for it to run. I would appreciate if someone gave me step by step guid on how to run this.

Currently, Im getting this error.This is the error Im getting. I have changed the address in contact.json but doesnt work. Also, Im getting the following warning when deploying the contract using node deploy.js.

node:51500) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
0xd09eD97239e278d591f80Eb45437895aa201F451

I have connected ganache to metamask using import accounts. I would appreciate if you gave me any sort of help here…

Error validating generated transaction: Error running script for input 0 referencing at 0: Script was NOT verified successfully

Good afternoon, please help me figure out the error, I can’t understand why the transaction doesn’t go through.
Here is my code:

const express = require('express');
const app = express();
const port = 3000;
const cors = require('cors');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const axios = require('axios');
var bitcoin = require("bitcoinjs-lib");
var secp = require('tiny-secp256k1');
var ecfacory = require('ecpair');
var ECPair = ecfacory.ECPairFactory(secp);
app.use(cors());


app.post('/submit', (req, res) => {
    const senderAddress = 'mxqxyFpBSxXHaL928G98tuL5pwX1gpmgTJ';
    const senderPrivateKey = "cQg2X7cVEBSHWW3mUdXm3VPAArRJc3K9PUNkmaEsHYFdKNN29CDt";
    const { recipientAddress , amountToSend } = req.body;
    const keyBuffer = Buffer.from(senderPrivateKey);
    const totalLength = 32;
    const result = Buffer.concat([keyBuffer], totalLength);
    var keys = ECPair.fromPrivateKey(result);
    const apiUrl = "https://api.blockcypher.com/v1/btc/test3/";
    const newtx = {
        inputs: [{addresses: [senderAddress]}],
        outputs: [{addresses: [recipientAddress], value: (parseInt(amountToSend  * 100000000))}]
    };
    axios.post(apiUrl+'txs/new', newtx)
      .then(function(response) {
        const tmptx = response.data;
        tmptx.pubkeys = [];
        tmptx.signatures = tmptx.tosign.map(function (tosign, n) {
          tmptx.pubkeys.push(keys.publicKey.toString('hex'));
          return bitcoin.script.signature.encode(
            keys.sign(Buffer.from(tosign, "hex")),
            0x01,
          ).toString("hex").slice(0, -2);
        });
        axios.post(apiUrl + 'txs/send', tmptx)
          .then(function (finaltx) {
            res.status(200).send('Транзакция отправлена!: ' + finaltx.data);
          })
          .catch(function (error) {
            res.status(500).send('Ошибка при отправке транзакции 1:' + (error.response ? error.response.data : error.message));
            console.error('Ошибка при отправке транзакции 1.1:', error.response ? error.response.data : error.message);
          });
      })
      .catch(function (error) {
          res.status(500).send('Ошибка при создании транзакции 2.1:' + (error.response ? error.response.data : error.message));
          console.error('Ошибка при создании транзакции 2.2:', error.response ? error.response.data : error.message);
       });
});
app.listen(port, () => {
console.log(`Сервер запущен на порте ${port}`);
});

Error validating generated transaction: Error running script for input 0 referencing efc9c6122a60b1aa78805686dd656a38708334f715d197e559a110c36655cdfc at 0: Script was NOT verified successfully.
[enter image description here](https://i.stack.imgur.com/mTNtE.jpg)

How to catch ERR_INTERNET_DISCONNECTED, ERR_NETWORK_CHANGED, etc?

TL;DR – I want to be able to programmatically reload the page so as to gracefully recover from an ERR_INTERNET_DISCONNECTED error, rather than leaving the user with a half-loaded, dead page which cannot be recovered and must be reloaded when the network reconnects.

I am listening for the ‘offline’ and ‘online’ events and I can catch those and handle them, however I want to be able to catch and handle ERR_INTERNET_DISCONNECTED and other such errors that occur when the connection is dropped while javascript is loading modules. Why? Because I want to be able to handle the following two conditions:

  1. The page has already fully loaded and the javascript is sitting idle, waiting for input. If the network disconnects and reconnects during this time, it doesn’t matter – the js will function just fine after the internet has reconnected.

  2. The page is in the middle of loading when the network disconnects. This is a non-recoverable error and requires that the page be re-loaded.

‘offline’ and ‘online’ events are dispatched in both cases, but it is only in case 2 that ERR_INTERNET_DISCONNECTED (etc) errors are thrown. So I want to be able to distinguish between the two cases and, when the network disconnection results in a non-recoverable error, display a modal to the user saying something along the lines of “The network has disconnected and the page is trashed, it will be reloaded when the network reconnects.” (or whatever). But to do that I need to be able to catch ERR_INTERNET_DISCONNECTED. I have tried using the general error listeners window.addEventListener('error', () => { ... }) and window.onerror = (a, b, c, d, e) => { ... } but it seems the ERR_INTERNET_DISCONNECTED cannot be caught by these. Is there any way to check programmatically to see if one of these errors has been thrown?

Of course, any code that is intended to catch and gracefully recover from ERR_INTERNET_DISCONNECTED could itself not be fully loaded when the error occurs, but I should at least try to gracefully recover from the error!

window.addEventListener('error', () => { ... }) and window.onerror = (a, b, c, d, e) => { ... }. No dice.

Error: Cannot find module ‘moment’ in the render deployin nodejs server file

solve this problem and run npm i moment i in the place of npm i or npm install
Error Encountered:

While deploying a Node.js server on Render, you’re encountering the error “Cannot find module ‘moment’.” This indicates that the moment module, used for date and time manipulation, is either not installed or not accessible within the deployment environment.

Resolving the Issue:

  1. Install moment:

    • Access the terminal within your project’s root directory.
    • Execute the following command to install moment locally:
      npm i moment
      

      This ensures the module is included in your project’s dependencies.

  2. Verify Installation:

    • Check if moment is now listed under “dependencies” in your package.json file.
    • Confirm its presence within the node_modules folder.
  3. Deployment Considerations:

    • Render’s build process might not automatically include node_modules.
    • To ensure moment is available during deployment, run npm i moment i.
      This flag typically includes devDependencies for deployment.

Additional Troubleshooting Steps:

  • Typos: Double-check for any typos in the require statement importing moment.
  • Cache Clearing: If the issue persists, clear the npm cache using npm cache clean --force and reinstall moment.
  • Development Server: Restart your development server to reload dependencies.
  • Module Location: If moment is installed in a non-standard location, provide the correct path in the require statement.
  • Version Compatibility: Ensure moment is compatible with your Node.js version.

Request for Further Information:

For more tailored assistance, please provide the following:

  • Relevant code snippet from index.js
  • Your project structure
  • Any additional error messages or logs

Remember:

  • Avoid global installations of moment to prevent version conflicts.
  • If you have any further questions or require additional guidance, feel free to ask!

How to update Data in every 10 sec in ajax?

I’m currently facing an issue with the setInterval function in my JavaScript code. I’m trying to use it to update a card’s content every few seconds, but instead of updating the existing card, it seems to be creating multiple copies.

function Hide(HideID) {
  HideID.style.display = "none";
}

$(document).ready(function() {
      fetchData();

      function fetchData() {
        const apiUrl = `https://api.cricapi.com/v1/cricScore?apikey=key`;
        $.ajax({
          url: apiUrl,
          type: "GET",
          success: function(data) {
            globalData = data
            UpdateData(data)
          },


          error: function(data) {
            console.log("error");
            console.log(data);
          }
        });

      }

      function UpdateData(data) {


        data.data.sort((a, b) => {
          const order = {
            live: 1,
            fixture: 2,
            result: 3
          };
          return order[a.ms] - order[b.ms];
        });

        console.log(data.data[0], 'yes?')

        var htmlContent = ''; // Create an empty string to store HTML content
        for (var i = 0; i < data.data.length; i++) {
          htmlContent += `<div class="ritekhed-fixture-table-slider-layer">
                <time class="ritekhed-slider-head" datetime="" style="height:64px;text-align:center;">${data.data[i].matchType.toUpperCase()}</time>
                <ul class="ritekhed-bgcolor">
                 <li class="ritekhed-fixture-addtext"> ${data.data[i].dateTimeGMT.split('T')[0]} </li>
                <li class="ritekhed-fixture-vs">
                <span style="float:left;"><img src="${data.data[i].t1img}" class="img-responsive" style="width:35px; height:35px" /><br /><strong>${data.data[i].t1.split(' ').slice(-1)[0]}</strong></span>
                <div id=""  class="counter_small" ><span >VS</span></div>
                <span><img src="${data.data[i].t2img}" class="img-responsive" style="width:35px; height:35px" /><br /><strong>${data.data[i].t2.split(' ').slice(-1)[0]}</strong></span>
                <br />
                <div style="margin-top:2%;text-align:center !important;"></div>
                </li>
                <li class="ritekhed-fixture-vs" style="height: 84px; ">                <span style="text-align: right; display: inline-block; width: 50%;">${data.data[i].t2s}</span>
<span style="text-align: left; display: inline-block; width: 50%;">${data.data[i].t1s}</span>
        <br><strong style="float: none; position: relative;top:8px">${data.data[i].status}</strong> </li>
                <li class="ritekhed-fixture-addtext" style="background-color:black;"><a href="" style="color:#51e829;">Telegram Link</a></li>
                </ul>
                </div>`;
        }
        // Append the generated HTML content to the slider
        $('#sl33').append(htmlContent);

And I’m using slick-slider so after every 10 sec, the slider is also not working properly

$('#sl33').slick({
  dots: false,
  infinite: true,
  prevArrow: "<span class='slick-arrow-left'><i class='fa fa-chevron-left'></i></span>",
  nextArrow: "<span class='slick-arrow-right'><i class='fa fa-chevron-right'></i></span>",
  speed: 2000,
  autoplay: false,
  fade: false,
  autoplaySpeed: 3000,
  slidesToShow: 5,
  slidesToScroll: 5,
  responsive: [{
      breakpoint: 1024,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 1,
        infinite: true,
      }
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 1
      }
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1
      }
    }
  ]
});

Set default values in react-hook-form conditionally

Background:
I have a very long complex form with deep nested objects creating using rhf (react-hook-form). I want to provide a checkbox at the top of the form which toggles the default values in the fields to assist the user.

Problem
By using rhf, I was able to fill up the defaultValues using reset method but now the issue is once I call the reset method with the defaultValues, I can’t unset the values using the reset if I provide an empty object.

Things I’ve tried
I’ve tried using the setValue method but it unset only 1 field at once and it’ll require recursion to set values for deep-nested object.

Code
Here’s a very minimal example of what I’m trying to do.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

const defaultValues = { name: `John Doe` };

const Form = () => {
  const [useDefaultValues, setUseDefaultValues] = useState(false);
  const { register, handleSubmit, reset } = useForm();

  useEffect(() => {
    if (useDefaultValues) {
      reset(defaultValues);
    } else {
      reset({}, { keepValues: false, keepDefaultValues: false });
    }
  }, [useDefaultValues]);

  return (
    <>
      <label>
        <input
          type="checkbox"
          value={useDefaultValues}
          onChange={() => setUseDefaultValues((prev) => !prev)}
        />
        Use Default values
      </label>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Name</label>
          <input type="text" name="name" {...register("name")} />
        </div>
        <input type="submit" />
      </form>
    </>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Form />, rootElement);

Codesandbox: https://codesandbox.io/p/sandbox/react-hook-form-reset-form-forked-sxmy8q?file=%2Fsrc%2Findex.js%3A1%2C1-42%2C1

Notice how unsetting the defaultValues doesn’t empty the form again

error shows [object Object] with multer and cloudinary upload

I’ve been trying to create an api route that accepts multiple images for carouselImages and single photo for other three atrributes(photo, leftPic, rightPic). However I’m getting [object Object] in the console. The images aren’t getting uploaded to cloudinary too.

what am I doing wrong in my code?

backend route file

import express from "express";
import { createGame } from "../controllers/game.js";
import { checkAdminOrModerator } from "../middlewares/auth.js";
import { v2 as cloudinary } from 'cloudinary';
import multer from 'multer';
import 'dotenv/config';
import { CloudinaryStorage } from 'multer-storage-cloudinary';

const gameRouter = express.Router();

cloudinary.config({
    cloud_name: process.env.CLOUD_NAME,
    api_key: process.env.CLOUDINARY_KEY,
    api_secret: process.env.CLOUDINARY_SECRET
});

const storage = new CloudinaryStorage({
    cloudinary,
    params: {
        folder: 'Demo',
        allowedFormats: ['jpeg', 'png', 'jpg', 'webp'],
    }
});

const upload = multer({
    storage,
});

gameRouter.post("/addGame", upload.fields([
    { name: 'photo', maxCount: 1 },
    { name: 'leftPic', maxCount: 1 },
    { name: 'rightPic', maxCount: 1 },
    { name: 'carouselImages', maxCount: 3 }
]), checkAdminOrModerator, createGame)

export default gameRouter

controller file

import Game from "../model/Game.js";

export async function createGame(req, res) {
    console.log('req.body', JSON.stringify(req.body, null, 2)) // this doesn't get logged on console
    console.log('req.files', JSON.stringify(req.files, null, 2)) //I guess I'm getting [object Object] from here but 'req.files' doesn't show up in the console either
    try {
        const {
            name,
        } = req.body;

        const photo = req.files['photo'] ? req.files['photo'][0].path : '';
        const leftPic = req.files['leftPic'] ? req.files['leftPic'][0].path : '';
        const rightPic = req.files['rightPic'] ? req.files['rightPic'][0].path : '';
        const carouselImages = req.files['carouselImages']
            ? req.files['carouselImages'].map((image) => image.path)
            : [];

        const newGame = new Game({
            name,
            photo,
            leftPic,
            rightPic,
            carouselImages
        });

        const savedGame = await newGame.save();

        return res.status(201).json(savedGame);
    } catch (error) {
        console.log('error', error)
        return res.status(500).json({ error: 'Internal server error' });
    }
}

frontend code. using vue2 and bootstrap vue

<template>
  <div class="wrapper">
    <b-form @submit.prevent="saveGame">
      <b-form-group label="Name">
        <b-form-input v-model="formData.name" />
      </b-form-group>
      <b-form-group label="Route Name">
        <b-form-input v-model="formData.routeName" />
      </b-form-group>
      <b-form-group label="Photo">
        <b-form-file @change="handlePhotoFileChange" />
      </b-form-group>
      <b-form-group label="Left Pic">
        <b-form-file v-model="leftPicFile" />
      </b-form-group>
      <b-form-group label="Right Pic">
        <b-form-file v-model="rightPicFile" />
      </b-form-group>

      <!-- Carousel Images -->
      <b-form-group label="Carousel Images">
        <b-form-file
          v-for="(carouselImage, index) in carouselImages"
          :key="index"
          @change="handleCarouselImageChange(index, $event)"
        />
        <b-button @click="addCarouselImage" variant="success"
          >Add Image</b-button
        >
      </b-form-group>
      <!-- Save and cancel buttons -->
      <b-button type="submit" variant="primary">Save</b-button>
    </b-form>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      formData: {
      },
      photoFile: null,
      leftPicFile: null,
      rightPicFile: null,
      carouselImages: [],
    };
  },
  methods: {
    addCarouselImage() {
      this.carouselImages.push(null);
    },

    removeCarouselImage(index) {
      this.carouselImages.splice(index, 1);
    },

    handlePhotoFileChange(event) {
      if (event.target.files && event.target.files.length > 0) {
        this.photoFile = event.target.files[0];
      }
    },

    handleCarouselImageChange(index, event) {
      this.$set(this.carouselImages, index, event.target.files[0]);
      console.log("carouselImages", this.carouselImages)
    },
    async saveGame() {
      const token = localStorage.getItem("token");
      if (!token) {
        console.error("Token not found");
        return;
      }

      const formData = new FormData();
      formData.append("name", this.formData.name);

      if (this.photoFile) {
         formData.append("photo", this.photoFile);
      }
      if (this.leftPicFile) {
         formData.append("leftPic", this.leftPicFile);
      }
      if (this.rightPicFile) {
         formData.append("rightPic", this.rightPicFile);
      }
      this.carouselImages.forEach((file) => {
         if (file) {
             formData.append('carouselImages', file);
         }
      });
      for (let [key, value] of formData.entries()) {
         console.log(key, value);
        }
      const url = `${process.env.VUE_APP_API_ENDPOINT}/game/addGame`;
      try {
        const response = await axios.post(url, formData, {
          headers: {
            Authorization: token,
          },
        });

        if (response.status === 200) {
          console.log("Game saved successfully");
        } else {
          console.error("Error saving game");
        }
      } catch (error) {
        if (error.response && error.response.status === 401) {
          console.error("Token expired or invalid");
          this.$router.push("/login");
        }
        console.error("Error saving game:", error);
      }
    },
  },
};
</script>

backend index.js

import express from "express";
import mongoose from "mongoose";
import 'dotenv/config';
import cors from 'cors';

import gameRouter from "./routes/game.js";

const app = express();

app.use(cors())
app.use(express.json());

app.use("/game", gameRouter);
app.use("/", (req, res) => {
  res.send("Hello World");
});

mongoose
  .connect(
    process.env.MONGODB_URI
  )
  .then(() => app.listen(3000))
  .then(() => console.log("Connected to database"))
  .catch((err) => console.log(err));

Not able to see the component in my React app on building it

I am building a cryptotracker app using the CoinGecko API. This is my App component.

import Navbar from "./components/Navbar";
import Home from "./components/Home";
import { Route, Routes } from "react-router-dom";
import Show from "./components/Show";

function App() {
  return (
    <>
      <Navbar />
      <Routes>
        <Route index element={<Home />} />
        <Route path="/show" element={<Show />} />
      </Routes>
    </>
  );
}

export default App;

This is my index.js file:

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

This is my Navbar component:

import React from "react";
import { Link } from "react-router-dom";

function Navbar() {
  return (
    <>
      <div className="nav_container">
        <div className="nav">
          <div className="navigation_menu">
            <Link to="/" className="nav_heading">
              Coiner
            </Link>
            <ul>
              <li>Home</li>
              <li>Pricing</li>
              <li>Features</li>
              <li>About</li>
              <li>Contact</li>
            </ul>
          </div>
          <div className="nav_button">
            <button>Login</button>
          </div>
        </div>
      </div>
    </>
  );
}

export default Navbar;

This is my Home component:

import React, { useEffect, useState } from "react";
import axios from "axios";
import Coin from "./Coin";
import Query from "./Query";

function Home() {
  const [coins, setCoins] = useState();
  const [query, setQuery] = useState("");
  const [components, setComponents] = useState(true);
  const [queryCoins, setQueryCoins] = useState();
  const [heading, setHeading] = useState("Trending Coins");
  useEffect(() => {
    window.scrollTo(0, 0);
    const getCoins = async () => {
      const response = await axios.get(
        "https://api.coingecko.com/api/v3/search/trending"
      );
      const result = response.data.coins;
      setCoins(result);
    };
    getCoins();
  }, []);
  const handleQueryChange = (event) => {
    const new_value = event.target.value;
    if (new_value === "") {
      setComponents(true);
      setHeading("Trending Coins");
    }
    setQuery(event.target.value);
  };
  const handleQuery = async () => {
    const response = await axios.get(
      `https://api.coingecko.com/api/v3/search?query=${query}`
    );
    const result = response.data.coins;
    setQueryCoins(result);
    setComponents(false);
    setHeading("Search Results");
  };
  const handleKeyChange = (event) => {
    if (event.key === "Enter") {
      handleQuery();
    }
  };
  return (
    <>
      <div className="outer_home_container">
        <div className="input_container">
          <input
            type="text"
            className="search_input"
            placeholder="Search for coins..."
            value={query}
            onChange={handleQueryChange}
            onKeyDown={handleKeyChange}
            maxLength={20}
          />
          <button onClick={handleQuery} className="input_button">
            <i className="fa-solid fa-magnifying-glass"></i>
          </button>
        </div>
        <h1>{heading}</h1>
        <div className="container">
          {components ? (
            coins ? (
              coins.map((key) => {
                return <Coin coin={key} key={key.item.id} />;
              })
            ) : (
              <h2>Loading...</h2>
            )
          ) : queryCoins ? (
            queryCoins.map((key) => {
              return <Query coin={key} key={key.id} />;
            })
          ) : (
            <h2>Loading...</h2>
          )}
        </div>
      </div>
    </>
  );
}

export default Home;

The main problem is that when I run my app through npm run start, it successfully renders all the components, that is Navbar and Home. but after I build my app through npm run build and run the website through live server, it only renders the Navbar component, and to render the Home component I have to click the Coiner logo, and then and only then it successfully renders the Home component and my Navbar component together.

Sorry for making any mistakes in the format, I am new to the Stackoverflow Q&As.

I tried editing my package.json file before building the application.

Here is the code:

{
  "name": "app",
  "homepage": "./",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.6.3",
    "lodash": "^4.17.21",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.21.1",
    "react-scripts": "5.0.1",
    "recharts": "^2.10.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I changed homepage to “./” but it did not work.

And here is the website’s link.

Any help would be appreciated.

I’m building my first website using an API, not sure why I’m pulling an error

I am using OMDb API to build a movie search platform for some practise in VS Code. I was watching a video and my syntax is almost identical, I am successfully pulling the data in a promise. Now when I go to use .map() to change the innerHTML, I’m pulling an error.

async function main() {
  const movie = await fetch("https://www.omdbapi.com/?i=tt3896198&apikey=ba040381");
  const movieData = await movie.json();
  const movieListEl = document.querySelector(".movie__list");

  console.log(movieData) // to prove data is being pulled

  movieListEl.innerHTML = movieData
    .map(
      (movie) =>
        `<div class="movie__card">
          <div class="movie__card--container">
            <h3>${movie.title}</h3>
            <p><b>Year:</b>0000</p>
            <p><b>Rating:</b>xxxxx</p>
            <p><b>Runtime:</b>xxxxx</p>
            <p><b>Genre:</b>xxxxx</p>
          </div>
        </div>`
    )
    .join("");
}

main();

This is not perfect by any means, but in the video this syntax seemed to work perfectly before cleaning up the code and making it easier to read by creating a separate function to change the HTML

(https://i.stack.imgur.com/mWZOU.png)

I’m very lost and had reached out for some help in this discord channel I’m in with unfortunately no luck. I am very new to JavaScript—and using APIs for that matter. Any feedback is very much appreciated.

Keep Javascript Speech Recognition in Webview run in Background Android

I’m building a WebApp in Java to show this page: https://davidwalsh.name/demo/speech-recognition.php,it’s using Javascript Speech Recognition. However, I want to make my WebApp and its Javascript run in background so it can work even the phone’s screen is turned off. Thanks for any helps!

And here’s my webapp code(I removed some unnecessary part like Permission Request to make it shorter):

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.PermissionRequest;

public class MainActivity extends AppCompatActivity {
    private WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebChromeClient(new WebChromeClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("https://davidwalsh.name/demo/speech-recognition.php");
    }
}

Electron App Shows spawn ENOTDIR at ChildProcess.spawn error After Packaging, but Works Locally

Problem Description:

I’m encountering an issue with my Electron app. After packaging the app and running I am getting the following error,However, when running it locally with npm run electron:serve, everything works fine.
Error

    Uncaught Exception:
    Error: spawn ENOTDIR
    at ChildProcess.spawn (node:internal/child_process:412:11)
    at spawn (node:child_process:707:9)
    at Object.<anonymous> (/Users/avinashkumaranshu/Project/Desktop/advance-notes-working/dist/mac-arm64/advance-notes.app/Contents/Resources/app.asar/electron/main.js:17:23)
    at Module._compile (node:internal/modules/cjs/loader:1116:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Module._load (node:internal/modules/cjs/loader:829:12)
    at Function.c._load (node:electron/js2c/asar_bundle:5:13331)
    at Object.<anonymous> (node:electron/js2c/browser_init:193:3197)
    at Object../lib/browser/init.ts (node:electron/js2c/browser_init:193:3401)

Code Details:

  • main.js: Path: /electron/main.js

    
     const { app, BrowserWindow, ipcMain } = require("electron");
     const path = require("path");
     const isDev = require("electron-is-dev");
     const { spawn } = require("child_process");
     const log = require("electron-log");
    
     log.transports.file.level = "debug"; // Set log level (e.g., debug, info, warn, error)
    
     const serverPath = path.join(__dirname, "../back-end/dist");
    
     ipcMain.on("log-message", (event, message) => {
       log.info(`[Renderer Log] ${message}`);
     });
    
     // Start NestJS server in a separate child process
     const serverProcess = spawn("node", ["main.js"], {
       cwd: serverPath,
       stdio: "inherit", // Redirect server logs to the main process console
     });
    
     // Wait for the server to start before creating the main window
     serverProcess.on("exit", (code, signal) => {
       if (code === 0) {
         // Create the main window only if the server process exits successfully
         createWindow();
       } else {
         // Handle errors or gracefully exit the app
         console.error(
           `Server process exited with code ${code} and signal ${signal}`
         );
         app.quit();
       }
     });
    
     function createWindow() {
       // Create the browser window.
       const win = new BrowserWindow({
         width: 800,
         height: 600,
         webPreferences: {
           nodeIntegration: false,
           enableRemoteModule: true,
         },
       });
    
       win.loadURL(
         isDev
           ? "http://localhost:3000"
           : `file://${path.join(__dirname, "../front-end/build/index.html")}`
       );
     }
    
     app.on("ready", createWindow);
    
     // Quit when all windows are closed.
     app.on("window-all-closed", function () {
       // On OS X it is common for applications and their menu bar
       // to stay active until the user quits explicitly with Cmd + Q
       if (process.platform !== "darwin") {
         app.quit();
       }
     });
    
     app.on("activate", function () {
       // On OS X it's common to re-create a window in the app when the
       // dock icon is clicked and there are no other windows open.
       if (BrowserWindow.getAllWindows().length === 0) createWindow();
     });
    
    
  • package.json: Path: /package.json

     {
       "name": "advance-notes",
       "version": "1.0.0",
       "description": "Main package.json",
       "main": "electron/main.js",
       "homepage": "./",
       "scripts": {
         "start": "cd front-end && react-scripts start",
         "build": "react-scripts build",
         "test": "react-scripts test",
         "eject": "react-scripts eject",
         "electron:serve": "concurrently -k " cd front-end && cross-env BROWSER=none yarn start" " yarn electron:start"",
         "electron:build": "cd front-end && yarn build && cd ../ && electron-builder -c.extraMetadata.main=electron/main.js",
         "electron:start": "wait-on tcp:3000 && electron ."
       },
       "build": {
         "extends": null,
         "appId": "com.example.advance-notes",
         "files": [
           "dist/**/*",
           "front-end/build/**/*",
           "front-end/node_modules/**/*",
           "back-end/dist/**/*",
           "back-end/node_modules/**/*",
           "node_modules/**/*",
           "electron",
           "package.json"
         ],
         "directories": {
           "buildResources": "assets"
         }
       },
       "devDependencies": {
         "@types/draft-js": "^0.11.16",
         "concurrently": "^5.3.0",
         "cross-env": "^7.0.3",
         "electron": "^16.0.0",
         "electron-builder": "^24.9.1",
         "prettier": "^2.2.1",
         "wait-on": "^5.2.1"
       },
       "dependencies": {
         "class-validator": "^0.14.0",
         "electron-is-dev": "^2.0.0",
         "electron-log": "^5.0.3"
       }
     }
    
  • React code path: /front-end

  • Nest code path: /back-end

    Additional Information:

    • Dependencies:

      • electron: 16.0.0

      • electron-builder: 24.9.1

    • Scripts:

      • Run the app locally (npm run electron:serve).

      • Build and package the app (npm run electron:build).

    • Environment:

      • Operating System: macOS

      • Node.js: 14.21.3

Why cannot I show the sum of elements in an array using forEach() in JavaScript?

I encountered a seemingly vague issue in my code.
I tried everything searching for answers online but of no avail.
I am in search on how to depict to the browser via my HTML element the sum of the array elements.

Here is my JavaScript Code below:

//create a counter function using closure method



//it counts the products that gets in the store
let time = Date();
const products = {
        productName: [],
        description: [],
        quantity: [],
        unitOfMeasure: []
    }
    //assigning values input into an array
let countLog = products.quantity;
let counterEl = document.getElementById('counter-el');
let countLogEl = document.getElementById("count-log-el");
let countSumEl = document.getElementById('count-sum-el');
let displaySumEl = document.getElementById('display-sum');

function counterIncrement(productName, description, count, unit) {
    productName = document.querySelector('.text-input-product').value;
    description = document.querySelector('.text-input-description').value;
    unit = document.querySelector('.text-input-unit-measure').value;
    products.productName.push(productName);
    products.description.push(description);
    count = "";
    count = document.getElementById('number-input').value;
    count = count.replace(/([^a-z0-9áéíóúñü_-s.,]|[tnfrv])/gim, "");
    document.getElementById('counter-el').textContent = `Your count is: ${count} ${unit} of ${productName}`;
    products.quantity.push(count);
    count += countLog;
    products.unitOfMeasure.push(unit);
}




function save(count) {
    count = document.getElementById('number-input').value;
    count = document.getElementById('number-input').value = "";
    counterEl.textContent = "Count is set to 0";
    countLogEl.textContent = "Count Log: ";
    for (let i = 0; i < countLog.length; i++) {
        countLogEl.textContent += countLog[i] + " - ";

    }

}

function sumArray(sum) {

    sum = "";
    countLog.forEach(myCount);

    function myCount(item) {
        sum += item;
    }
    displaySumEl.textContent = `Total: `;
    displaySumEl.textContent += `${sum}`;

}

I tried to find the solution online, but I was a kind frustrated.
I am expecting I can display the sum of the array items in my array of counted product quantity, but I was wondering why it only depicts the numbers appended side by side without adding it all up.