React update state array of objects inside array of objects

I have a piece of state, invoices, that is an array of objects as such below:

 const [invoices, setInvoices] = useState([
  {
    id: 123,
    tag_number: "",
    item_amounts: [
      { item: "processing", amount: 159 },
      { item: "shipping", amount: 10 },
    ],
    complete: false,
    dropoff_id: "",
    customer_id: "",
    picked_up: false,
  },
  {
    id: 124,
    tag_number: "",
    item_amounts: [
      { item: "processing", amount: 169 },
      { item: "shipping", amount: 20 },
    ],
    complete: false,
    dropoff_id: "",
    customer_id: "",
    picked_up: false,
  }
]);

I have gathered so far that to update the value associated with a key inside one of the objects in invoices, I would need to do something like the following:

setInvoices(
  invoices.map((invoice) => {
    if (invoice.id === id) {
      return { ...invoice, complete: true };
    } else {
      return invoice;
    }
  })
);

What I’m struggling to figure out is how to update an array of objects inside one of the objects in invoices?

In particular, I’m trying to update the the processing object inside of item_amounts for an invoice of a particular id

Nextjs | Global CSS cannot be imported from files other than your Custom

I try use this app

https://github.com/imranhsayed/woo-next/tree/master/src/styles

when I uncomments tyls in pages/_app.js then working, but how to correct import styles? Because in _app.js

is:

import "../src/styles/style.scss";
import "../src/styles/main.scss";

and this crash application:

./styles/main.scss
Global CSS cannot be imported from files other than your Custom <App>. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to pages/_app.js. Or convert the import to Component-Level CSS (CSS Modules).
Read more: https://nextjs.org/docs/messages/css-global
Location: pages_app.js

Hover on Face with React Three Fiber

I’m still a noob to the whole Three.js ecosystem, and so I’m having difficulties even when I find something very close to a solution. For example, I’ve finally been able to find a solution to how to highlight the face of a geometry on hover through seanwasere’s comment here on Three.js Discourse, on this CodeSandbox.

How do I translate this piece of code to React Three Fiber?

For reference, let me reproduce the code here:

import * as THREE from "/build/three.module.js";
import { OrbitControls } from "/jsm/controls/OrbitControls.js";
import Stats from "/jsm/libs/stats.module.js";

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  100
);
camera.position.z = 2;

const light = new THREE.DirectionalLight();
light.position.set(2, 2, 10);
scene.add(light);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);

const geometry = new THREE.BoxGeometry();
var materials = [
  new THREE.MeshPhongMaterial({
    color: 0x00ff00
  }),
  new THREE.MeshPhongMaterial({
    color: 0x00ff00
  }),
  new THREE.MeshPhongMaterial({
    color: 0x00ff00
  }),
  new THREE.MeshPhongMaterial({
    color: 0x00ff00
  }),
  new THREE.MeshPhongMaterial({
    color: 0x00ff00
  }),
  new THREE.MeshPhongMaterial({
    color: 0x00ff00
  })
];
const cube = new THREE.Mesh(geometry, materials);
scene.add(cube);

window.addEventListener(
  "resize",
  () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    render();
  },
  false
);

renderer.domElement.addEventListener("mousemove", onMouseMove, false);

const raycaster = new THREE.Raycaster();
let activeFaceIndex = 0;
function onMouseMove(event) {
  raycaster.setFromCamera(
    {
      x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
      y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1
    },
    camera
  );

  const intersects = raycaster.intersectObject(cube, false);

  if (intersects.length > 0) {
    if (
      intersects[0].face.materialIndex !== activeFaceIndex &&
      activeFaceIndex !== -1
    ) {
      materials[activeFaceIndex].color.setHex(0x00ff00);
    }
    activeFaceIndex = intersects[0].face.materialIndex;
    materials[activeFaceIndex].color.setHex(0xff0000);
  } else {
    if (activeFaceIndex !== -1) {
      materials[activeFaceIndex].color.setHex(0x00ff00);
    }
    activeFaceIndex = -1;
  }
}
const stats = Stats();
document.body.appendChild(stats.dom);

var animate = function () {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  controls.update();
  render();
  stats.update();
};

function render() {
  renderer.render(scene, camera);
}

animate();

Another useful reference on how to highlight triangles on a face is here by Mugen87, or in this JSFiddle.

How do I add file details like version, product name, company, etc when creating an exe file from node.js file using pkg?

I have a javascript file and I converted it into an executable using pkg (https://www.npmjs.com/package/pkg).

Here is the npm script:

//...
  "scripts": {
    // ...
    "build": "pkg index.js --target node16-win-x64 --output pn.exe"
  },
//...

And after generating the exe file, the default file details are applied like this:

enter image description here

How do I change those values (file description, file version, product name, etc.) using pkg?

If it is impossible to do with the pkg package, can you please recommend any other ways/tools to do that?

Azure App service Web Page cached at client side

We have a Asp.Net Core + Vue js (SPA) application hosted on Azure App service.
Since sometime, we observed that changes deployed to production are not reflected on client side.
After further investigation, we found that the html page rendered on client side doesn’t have latest script source url. We do add unique Id to our script src, but it looks like the entire page version is cached on browser, hence latest scripts are not rendered to client.

Any idea if anybody saw similar behaviour?

I tried to add following cache tags, however it doesn’t helps to prevent such behavior.
Most of complains we got are from Chrome / Edge browsers.

enter image description here

Here is the sample of script tag we have

enter image description here

Downloading images from external source and saving to $lib or static at build time

I have a Sveltekit project set up with adapter-static. I’m pulling in content for my pages from Directus. I’m hosting my images in S3, which is hooked up to my Directus instance so that I can use the Directus filesystem to read these image files from and save to my S3 storage. I am handling audio samples the same way.

At build time, I would like to import / download the remote images and audio samples to my project, the same way I am downloading the text information I need to populate my pages. I am using load functions in +page.server.ts to fetch the data I will need for each page at build time using the Directus API. I am however stumped as to how I can do this for images too. It would be ideal that I can write something in the load function that tells Sveltekit to “fetch all the images and audio samples from this remote folder, then store them in /$lib or in /static so that we can serve local images and audio in the static site”
Use case:I’m trying to create an intuitive way for content editors to work on content whilst at the same time trying to decouple the website code from relying on any external provider. If my S3 or Directus instance goes down, the most recent site build should display without problem. This is currently the case for everything except the image and audio assets referenced in my markup. So it would be ideal that my content editor can upload their images to S3 via the Directus instance (which will trigger a site build) and that my project can then download those images and store them locally at build (not on the client side at load time.)

Essentially it should not matter how or where I store my images; the function / package / way to do what I am asking would essentially be the same. Does anybody have advice on where to start / what to look into / npm packages to try to make this happen?

Why does a function work for only certain data?

I’ve been analizing, refactoring and correcting a piece of old JS code (it was written like 15 to 20yrs ago and it is inside a php file containing some older, but still functioning, logic). Now, I have already made some changes to the code to bring up to certain office-needed standards, but there is a function that only works for previously existing pieces of data and does not work if I try to add new data.
To be more clear, this function is supposed to save the changes made to a td when date, text and qty are added to said td. When I edit previously existing data, the code works, but only shows the changes at the next page reload, while when I try to add new data, it doesn’t work at all: it shows the changes on save, but when the page is reloaded, the data is not saved and, hence, not shown.
I need it to, obviously, always save the data and also show the updated td without having to reload the page.

This is the full function:

function savePoConf(id, matCode) {
                let pNum = jsfindObj('poNum');
                let pPos = jsfindObj('poPos');
                let cnfId = jsfindObj('poConfId');
                let cnfDate = jsfindObj('poConfDate');
                let cnfQty = jsfindObj('poConfQty');
                let cnfTxt = jsfindObj('poConfTxt');

                const params = new URLSearchParams({
                    sapConn: '<?php echo $c->sapConn ?>',
                    poNum: pNum.value,
                    poPos: pPos.value,
                    confId: cnfId.value,
                    confDate: cnfDate.value,
                    confQty: cnfQty.value,
                    confTxt: cnfTxt.value,
                    confUser: '<?php echo CurrentUser() ?>',
                    sid: Math.random(),
                });

                // AJAX call
                let url = 'https://intranet.intranet.it/api/SAP/intranetFunc.php?' + params.toString();
                console.log(url);
                let richiestaHTTP = new XMLHttpRequest();
                richiestaHTTP.open('GET', url);
                richiestaHTTP.send();
                richiestaHTTP.onload = function () {
                    if (richiestaHTTP.status === 200) {
                       
                        wellDoneHere();
                        console.log(richiestaHTTP);

                       
                        try {
                            let results = JSON.parse(richiestaHTTP.responseText);
                            if (results.text !== 'ok') {
                                alert(richiestaHTTP.result + ': ' + richiestaHTTP.responseText);
                            } else {
                                $("#poConf").modal('hide');

                                let addBtn = `<img src="/images/edit_add_16.png" onclick="showPoConf('${matCode}', '${pNum.value}', '${pPos.value}', '${cnfDate.value}', '${cnfQty.value}', '${cnfTxt.value}', '${cnfId.value}')" onmouseover="setAsPointer(this)">`;
                        
                                let editBtn = `<img src='/images/pgm_edit_16.png' onclick="showPoConf('${matCode}', '${pNum.value}', '${pPos.value}', '${cnfDate.value}', '${cnfQty.value}', '${cnfTxt.value}', '${cnfId.value}')" onmouseover='setAsPointer(this)'>`;
                         
                                let delBtn = `<img src='/images/delete_16.png' onclick="delPoConf('${pNum.value}', '${pPos.value}', '${cnfId.value}', '${id}')" onmouseover='setAsPointer(this)'>`;

                                let td = document.getElementById('ConfirmAuth_' + id + '_');
                                console.log(td);
                                if (td && td.nextSibling === null) {
                                    let confirmRow = document.createElement('tr');

                                    let confirmRef = document.createElement('td');
                                    confirmRef.setAttribute('id', 'ConfirmRef_' + id + '_');
                                    confirmRef.innerHTML = cnfTxt.value;

                                    let confirmQty = document.createElement('td');
                                    confirmQty.setAttribute('id', 'ConfirmQty_' + id + '_');
                                    confirmQty.innerHTML = cnfQty.value;

                                    let confirmDate = document.createElement('td');
                                    confirmDate.setAttribute('id', 'ConfirmDate_' + id + '_');
                                    confirmDate.innerHTML = cnfDate.value;

                                    let editButton = document.createElement('td');
                                    editButton.innerHTML = editBtn;

                                    let deleteButton = document.createElement('td');
                                    deleteButton.innerHTML = delBtn;

                                    confirmRow.appendChild(confirmDate);
                                    confirmRow.appendChild(confirmQty);
                                    confirmRow.appendChild(confirmRef);
                                    confirmRow.appendChild(editButton);
                                    confirmRow.appendChild(deleteButton);

                                    td.appendChild(confirmRow);
                                } else {
                                    let newTd = document.createElement('td');
                                    newTd.appendChild(td);

                                    let existingConfAuth = document.createElement('ConfirmAuth_' + id + '_');

                                    let existingConfDate = document.getElementById('ConfirmDate_' + id + '_');
                                    let existingConfQty = document.getElementById('ConfirmQty_' + id + '_');
                                    let existingConfRef = document.getElementById('ConfirmRef_' + id + '_');

                                    existingConfAuth.appendChild(existingConfDate);
                                    existingConfAuth.appendChild(existingConfQty);
                                    existingConfAuth.appendChild(existingConfRef);

                                    let confirmRow = document.createElement('tr');

                                    let confirmRef = document.createElement('td');
                                    confirmRef.setAttribute('id', 'ConfirmRef_' + id + '_');
                                    confirmRef.innerHTML = cnfTxt.value;

                                    let confirmQty = document.createElement('td');
                                    confirmQty.setAttribute('id', 'ConfirmQty_' + id + '_');
                                    confirmQty.innerHTML = cnfQty.value;

                                    let confirmDate = document.createElement('td');
                                    confirmDate.setAttribute('id', 'ConfirmDate_' + id + '_');
                                    confirmDate.innerHTML = cnfDate.value;

                                    let editButton = document.createElement('td');
                                    editButton.innerHTML = editBtn;

                                    let deleteButton = document.createElement('td');
                                    deleteButton.innerHTML = delBtn;

                                    confirmRow.appendChild(confirmDate);
                                    confirmRow.appendChild(confirmQty);
                                    confirmRow.appendChild(confirmRef);
                                    confirmRow.appendChild(editButton);
                                    confirmRow.appendChild(deleteButton);

                                    td.appendChild(confirmRow);
                                }


                            }
                        } catch (e) {
                            console.error(e);
                        }
                    }
                }
            }

Thank you to anyone who may help!

Obtaining row element on Button Click in a Specific Column Using DataTables

I am using datatable to display data. When i click on retry, opening one modal which take one input field and button.

enter image description here

Here is a code for the modal.

<!DOCTYPE html>
<html>
   <body>
      <div class="row">
         <div class="col-md-12">
            <div id="customModalPopup" class="modal" style="display: none">
               <div class="popup-modal-content">
                  <span class="close-cutom-modal" onclick="closeCustomModal()">&times;</span>
                  <h4>Retry this order.</h4>
                  <h4>Please entyer approval content for retry.</h4>
                  <br>
                  <label for="customTextbox">Enter Information*:</label>
                  <textarea name="customTextbox" id="customTextbox" cols="30" rows="10" required></textarea>
                  <div style="display: none;">
                     <span id="rowElement"></span>
                  </div>
                  <button class="custom-modal-btn" onclick="submitCustomModal()">Submit & Process</button>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>

After clicking on Submit & Process, i want that row element which button is clicked.

I am using one hidden element(span) for adding row element when button is clicked.

Please provide me better approach.

Highcharts gives error Cannot read properties of undefined (reading ‘time’)

I am getting the error

ERROR TypeError: Cannot read properties of undefined (reading 'time')
    at J.<anonymous> (highcharts.js:8:201256)
    at C (highcharts.js:8:2670)
    at J.init (highcharts.js:8:200998)
    at J.getArgs (highcharts.js:8:200703)
    at new J (highcharts.js:8:200634)
    at Object.chart (highcharts.js:8:199843)
    at HighchartsChartComponent.updateOrCreateChart (highcharts-angular.mjs:36:74)

When using highcharts I am getting the error as shown above but I have not used time anywhere. How to remove this error? This is done via angular. I am using MEAN STACK

public highcharts = Highcharts;
  public chartOptions!: Options
ngOnInit{
 this.chartOptions = {
          chart: {
            type: 'line',
          },
          title: {
            text: 'Top 5 User Login Activity Chart',
          },

          xAxis: {
            categories: new_data.email,
            title: {
              text: 'Users',
            },
          },
          yAxis: {
            title: {
              text: 'No of User Logins',
            },
          },
          series: [
            {
              type: 'line',
              name: 'No of time Loggedin',
              data: new_data.login,
            },
          ],

        };
}

Change the Select Option based on Autosuggestion Text Input Field

Need to change the select option based on text input field, when typing in the text input box autosuggestion should be occur and based on that selection need to show option.

How can we achieve this in pure JS

Have tried to change the country select option to input box and made changes in JS with respect to that. But not worked

// Default option select for country
var user_country_code = "C1";

        (() => {
            // Get the country name and state name from the imported script.
            const country_array = country_and_states.country;
            const states_array = country_and_states.states;

            const id_state_option = document.getElementById("state");
            const id_country_option = document.getElementById("country");

            const createCountryNamesDropdown = () => {
                let option = '';
                option += '<option value="">select country</option>';

                for (let country_code in country_array) {
                    // set selected option user country
                    let selected = (country_code == user_country_code) ? ' selected' : '';
                    option += '<option value="' + country_code + '"' + selected + '>' + country_array[country_code] + '</option>';
                }
                id_country_option.innerHTML = option;
            };

            const createStatesNamesDropdown = () => {
                let selected_country_code = id_country_option.value;
                // get state names
                let state_names = states_array[selected_country_code];

                // if invalid country code
                if (!state_names) {
                    id_state_option.innerHTML = '<option>select state</option>';
                    return;
                }
                let option = '';
                option += '<select id="state">';
                option += '<option>select state</option>';
                for (let i = 0; i < state_names.length; i++) {
                    option += '<option value="' + state_names[i].code + '">' + state_names[i].name + '</option>';
                }
                option += '</select>';
                id_state_option.innerHTML = option;
            };

            // country select change event
            id_country_option.addEventListener('change', createStatesNamesDropdown);

            createCountryNamesDropdown();
            createStatesNamesDropdown();
        })();


        // country names and code

        var country_and_states = {
            country: {
                "C1": "Country 1",
                "C2": "Country 2",
                "C3": "Country 3"
            },


            //states name and code

            states: {
                "C1": [{
                    "name": "State 1"
                }, {
                    "name": "State 2"
                }],
                "C2": [{
                    "name": "State 1"
                }],
                "C3": [{
                    "name": "State 1"
                }]
            }
        };
<div>
  <label for="country">Country</label>
  <select id="country">
    <option>select country</option>
   </select>
 </div>

<div>
    <label for="state">State</label>
    <select id="state">
        <option>_</option>
    </select>
</div>

200 OK response even if redirection should be performed Express.js

I am trying to redirect my web application when a page is requested but the session has not already been set. I use Express.js for the server side.

Here you are the code of the route on the server:

app.post("/api/auth/signin", async (req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  console.log(`Request JSON: ${JSON.stringify(req.body)}`);

  const userRequested = await db
    .collection("users")
    .findOne({ username: username });

  if (userRequested == null) {
    res.status(401).json({
      message: "Requested user does not exist",
    });
    res.json(username);
  } else if (username == null || password == null) {
    res.status(401).json({
      message: "Null username or password are not allowed",
    });
  } else {
    if (userRequested.password === password) {
      req.session.user = userRequested;
      res.status(200);
      res.json(userRequested);
      //redirect("/api/budget/whoami");
    } else {
      res.status(401).send({
        message: "Wrong credentials",
      });
    }
  }
});

Also, I use the following function:

app.use(function(req, res, next) {
  if (!req.session || !req.session.user){
  res.statusCode = 300;
  res.redirect('http://localhost:3000/index.html');
  }   else {
   next();
  }
});

The client performs the fetch in the following way:

async beforeMount() {
    console.log("Executing on page loading");

    await fetch("/api/budget/whoami", {
      method: "GET",
      redirect: "follow"
    })
      .then((res) => {

        if(res.status == 300){
          window.location.replace("index.html");
        }

          console.log("All good, getting the response");
          return res.json();
      })
      .then((user) => {
        console.log("Updating value");
        console.log(JSON.stringify(user));
        console.log(user.username);

        this.username = user.username;
        this.password = user.password;
        this.firstName = user.firstName;
        this.lastName = user.lastName;
      });
  }

Even if the login is not performed, I can see that the response status is 200 OK using Postman. Checking the response body, it is the HTML code of the login page where I want to redirect the user.

Can anyone explain to me what I am doing wrong?

I appreciate your patience.

React Native: Issue with FlatList Rendering – Items Not Displaying Correctly

I’m currently working on a React Native project and facing an issue with the FlatList component. The items in the list are not displaying correctly, and I’m having trouble figuring out what might be causing the problem.

Here’s a simplified version of my code:

import React from 'react';
import { View, FlatList, Text } from 'react-native';

export default function MyComponent() {
  const data = [
    { id: '1', text: 'Item 1' },
    { id: '2', text: 'Item 2' },
    { id: '3', text: 'Item 3' },
    // ...more items
  ];

  return (
    <View>
      <FlatList
        data={data}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View>
            <Text>{item.text}</Text>
          </View>
        )}
      />
    </View>
  );
}

Despite having valid data and a basic renderItem function, the items are not displaying as expected. I’ve checked the data structure and key extraction, but I’m not able to identify the issue.

Can someone please help me troubleshoot this problem with FlatList rendering? Any suggestions or insights would be greatly appreciated. Thank you!

How to compile ntrujs library for nodejs?

I am using ntrujs library, in npm, for encryption in a nodejs file. However, while compiling the library, it is showing me an error in the configure.ac file, which is getting built using C, so it’s giving me an error while compiling it for nodejs. Can someone please tell me how to fix it?

Here’s the link: https://github.com/IDWMaster/ntrujs

Error Message

I ran these commands given in the build_ntru:

rm -rf ./ntru-crypto
git clone –depth=1 https://github.com/IDWMaster/ntru-crypto.git
OLDDIR=$(pwd)
mkdir -p lib
cd ntru-crypto/reference-code/C/Encrypt/
./autogen.sh
./configure –prefix=$OLDDIR/lib
make -j32
make install
cd $OLDDIR

But there was an error in configure.ac file. How do I fix this?