With this .map() method, Why do I only get just 1 file?

const innerPost = () => {

    const [files, setFiles] = useState([]);
    const [filePkNum, setFilePkNum] = useState('');

return (

{files.map((file, index) => {
                    if (file.length == 0) {
                        return (
                            <div>
                                <h5>THERE IS NO FILE.</h5>
                            </div>
                        );
                    } else {
                        return (
                            <div>
                                <a
                                    href={`/api/store/download-noticeboard-file?fileId=${filePkNum+index}`}
                                >
                                    {file[index]}
                                </a>
                                <Button
                                    size='small'
                                    onClick={() => deleteFile(filePkNum+index)}
                                >
                                    Delete
                                </Button>
                            </div>
                        )
                    }
                })}



)

}

In this code, When I open the post with two files, Only one file is being rendered.

Plus, I need the exact href={URL} to download the file. filePkNum is not starting from 0.

Therefore I add Index like that.

Two things I want to learn from you are

  1. Why do the code only renders 1 file even there are two files are on the post ( I get posts from DB)

  2. About the href={} on a tag, am I doing it right?

Thank you for your time!

Can’t display object key in thead table with react.js

I want to display object’s key into thead and object value to tbody. but it’s showing nothing in thead. Could you help me to fix this issue?

const order = {t1: '123', t2: '234'};  

return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 1000 }}>
        <TableHead>
          <TableRow>
            { order && Object.keys(order).forEach((value) => <TableCell>{ value }</TableCell> )}
          </TableRow>
        </TableHead>
        <TableBody>
        </TableBody>
      </Table>
    </TableContainer>
  );

array of objects to array in vuejs?

thanks for your answers, my problem is the following, I have this array of objects:

var rowsData = [
   {"id": 1, "name": "darinel", "age": "2"},
   {"id": 2, "name": "yair", "age": "24"},
   {"id": 3, "name": "Daniel", "age": "24"},
   {"id": 4, "name": "Saul", "age": "24"}
];

I want to get from rowsData an array of arrays as follows (The values of rowsData):

[
    [1, "darinel", "2"],
    [2, "yair", "24"],
    [3, "Daniel", "24"],
    [4, "Saul", "24"]
]

I am trying as follows:

  columsActive () {
       this.rowsData.map ((row) => this.testRows.push (Object.values (row)))
     }

Where rowsData contains my array of objects and testRows is an empty array where I try to put the values with Object.values however this does not work at least in vueJs and it returns the same array of array of objects in testRows. Thank you very much in advance for any advice or link to any documentation, I would greatly appreciate it.

Make api fetch once, and then have the “input” event merely do the filtering

My code fires a new ajax request on every single keystroke and i don’t know how to make my api fetch once, and then have the input event do the filtering.

My code works fine , but if i would live it like that it would take years to load when i would have a large json content.

The states.json data is still the same (and usualy is in autocomplete), i should load it once instead of every keystroke. Extra request for each key is not a good idea. So can someone please help me?

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/main.css">
        <title>Test</title>
    </head>
    <body>
        <div class="container">
            <div class="search-wrapper">
                <input type="text" name="" autocomplete="off" id="search" placeholder="Search now">
                <ul class="match-list">
                    
                </ul>
            </div>
        </div>
    
        <script src="function.js"></script>
    </body>
    
    </html>

and here is my javascript

const search = document.querySelector("#search");
const matchList = document.querySelector(".match-list");

// search states.json and filter it
const searchStates = async searchText => {
    const res = await fetch('data/states.json');
    const states = await res.json();

    //Get matches to current text input
    let matches = states.filter(state => {
        const regex = new RegExp(`^${searchText}`, 'gi');
        return state.name.match(regex) || state.abbr.match(regex);
    });

    if (searchText.length === 0) {
        matches = [];
    };

    

    outputHtml(matches)
};

//show results in html
const outputHtml = matches => {
    if (matches.length > 0) {
        const html = matches.map(match =>`
        <li class="match-list-element">
        <h4 class="">${match.name} (${match.abbr})</h4>
        <span class="">${match.capital}</span>
        <small class="">Lat:${match.lat}/ Long: ${match.long}</small>
        </li>
        `
        ).join('');

        matchList.innerHTML = html;

    } else {
        matchList.innerHTML = null;
    }

}


search.addEventListener('input', () => searchStates(search.value));

How to turn on and off the scroll trigger in Material UI useScrollTrigger module?

I’m trying to create a survey page using Material UI in React. I’d like my survey to turn on when the user scrolls over a question and turns off when the user scrolls out of a question. A behavior similar to this page.

https://www.surveymonkey.com/r/Typical-Customer-Demographics-Template

After doing some research, I decided to use useScrollTrigger module in MUI. I was able to turn on the questions when I scroll down to them, but still can’t figure out a way to turn them back off when I scroll down, out of them.

This is how I created my scrollToColor function:

import { useScrollTrigger } from "@material-ui/core";

export default function ScrollToColor(props) {
  const {
    threshold,
    threshold2,
    textColorBefore,
    textColorAfter,
    fadeIn,
    fadeOut,
    children,
    ...other
  } = {
    threshold: 50,
    threshold2: 100,
    textColorBefore: "gray",
    textColorAfter: "black",
    fadeIn: "0.1s ease-in",
    fadeOut: "0.1s ease-out",
    ...props,
  };

  const trigger = useScrollTrigger({
    disableHysteresis: true,
    threshold: threshold,
    target: props.window ? window() : undefined,
  });

  const trigger2 = useScrollTrigger({
    disableHysteresis: true,
    threshold: threshold2,
    target: props.window ? window() : undefined,
  });

  return React.cloneElement(children, {
    style: {
      color: trigger ? textColorAfter : textColorBefore,
      transition: trigger ? fadeIn : fadeOut,
      color: trigger2 ? textColorBefore : textColorAfter,
      transition: trigger2 ? fadeOut : fadeIn,
    },
    ...other,
  });
}

I created 2 triggers so when it scrolls to the question, the text color turns black and when scroll out, it turns back to gray. This is a sample code on how I added this to the parent component.

import {
  AppBar,
  Toolbar,
  Typography,
  ThemeProvider,
  CssBaseline,
  createMuiTheme
} from "@material-ui/core";
import ScrollToColor from "./ScrollToColor";

const NavbarscrollToColor = props => {
  const theme = createMuiTheme();

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />

      <ScrollToColor>
        <AppBar position="static">
          <Toolbar>
            <Typography variant="h5" noWrap>
              {props.title}
            </Typography>
          </Toolbar>
        </AppBar>
      </ScrollToColor>
    </ThemeProvider>
  );
};

export default NavbarscrollToColor;

But this unfortunately doesn’t work. Any tips on how to make this work?

Also, is there any easier and cleaner way in React I could have archived this other than using the MUI useScrollTrigger module?

Thanks!

Safari Regex Invalid Group specifier name

const separator = ',';
const escape = '\';
const escapeForRegEx = '\\';
const matchUnescapedSeparatorAndTrim = new RegExp(`\s*(?<!${escapeForRegEx})${separator}\s*`, 'g');
const matchSeparator = new RegExp(separator, 'g');
const matchEscapedSeparator = new RegExp(`${escapeForRegEx}${separator}`, 'g');

Which is throwing an error only on Safari.

SyntaxError: Invalid regular expression: invalid group specifier name

So, I read that Safari doesn’t support lookbehind yet, but I am not sure where is it in my Regex.
How do I fix that?
Also, is there anything wrong with the regex itself or it’s just the way Safari reads it?

Thanks.

What are ‘print screen’ images stored as?

When you hit the ‘Print Screen’ button, what is it stored as? I know that it saves the screenshot to the clipboard, but is it stored as a jpg? Or a png? Or is it something else entirely?

I’m making an hta (yes, I know it’s deprecated, but circumstances require it be an hta) with html/css/js (limited to ES5), and have a function that if a certain error happens, it automatically submits a ticket to our help desk. I want the function to also take a screenshot of the application at the time of the ticket submission, save it as a jpeg, and associate it with the ticket. I’ve found a few similar circumstances on stackoverflow (here and here), and translated their solutions from vbscript to js as best I could, but the issue comes with pasting the image into an excel chart. I don’t get an error for the paste, but it exports a blank jpg. So I’m trying to see figure out what a print screen is stored as, and if I can use python (limited to 3.5), or if I’m translating from vbscript to js wrong.

Any help and advice is appreciated.

Function to only send the email IF there is a task or note update within 24 hours

I have this code (thank you, Tanaike). The problem I am having with it. Is it sending emails to the project owners even if there is no task update and no note update within 24 hours. So they’re getting blank emails. What I am trying to do, is so
IF there is NO task updates AND NO Updates – dont send the email

Public link to spreadsheet: https://docs.google.com/spreadsheets/d/1FcOKVkhdjK-vGuFPWSR2ZreBYFI6EK7EnQj3yKPvttk/edit?usp=sharing

BlankEmail

function ProjectUpdate24hour() {
  // Retrieve our 3 needed sheets.
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const [sheetITPM, sheetITPM_Tasks, sheetNotes] = ["ITPM", "ITPM_Tasks", "Notes"].map(e => ss.getSheetByName(e));

  // Retrieve Project IDs, names and emails.
  const values = sheetITPM.getRange("A2:J" + sheetITPM.getLastRow()).getValues().map(r => ({ id: r[0], name: r[1], email: r[9] }));

  // Retrieve All Tasks.
  const tasks = sheetITPM_Tasks.getRange("A2:H" + sheetITPM_Tasks.getLastRow()).getValues().reduce((o, r) => (o[r[2]] = o[r[2]] ? [...o[r[2]], { description: r[3], status: r[4], owner: r[5], dueDate: r[6], t_lastupdate: r[7] }] : [{ description: r[3], status: r[4], owner: r[5], dueDate: r[6], t_lastupdate: r[7] }], o), {});

  // Retrieve All Notes.
  const notes = sheetNotes.getRange("A2:F" + sheetNotes.getLastRow()).getValues().reduce((o, r) => (o[r[1]] = o[r[1]] ? [...o[r[1]], { note: r[2], author: r[3], date: r[4], n_lastupdate: r[5] }] 
  : [{ note: r[2], author: r[3], date: r[4], n_lastupdate: r[5] }], o), {});

  Object.entries(notes).forEach(([, v]) => v.sort((a, b) => a.n_lastupdate.getTime() < b.n_lastupdate.getTime() ? 1 : -1)); //Sort Notes by latest update 

  //This determines if the tasks lastest update column is within 25 hours of the current time
  const now = new Date().getTime();
  const before24h = now - (25 * 60 * 60 * 1000);
  Object.entries(tasks).forEach(([k, v]) => {
    tasks[k] = v.filter(({t_lastupdate}) => {
      const temp = t_lastupdate.getTime();
      return now > temp && temp > before24h;
    });
  });

  //This determiens if the notes lastest update column is within 25 hours of the current time
  Object.entries(notes).forEach(([k, v]) => {
    notes[k] = v.filter(({n_lastupdate}) => {
      const temp = n_lastupdate.getTime();
      return now > temp && temp > before24h;
    });
  });


  // Send our emails to project owners with our email format 
  values.forEach(({ id, name, email }) => {
    const message = [
      `Here is the 24 hour project update for Project: n${name}`,
      "",
      `Assigned Tasks:`,
      ...tasks[id].map(({ description, status, owner, dueDate }, i) => [`Task ${i + 1}:`, `Task Description: ${description}`,`Task Owner: ${owner}`,`Task Status: ${status}`,
      `Task Due Date: ${dueDate}`, ""].join("n")),
      
      `Project Notes:`,
      ...notes[id].map(({ note,author }, i) => [`Note ${i + 1}: ${note}`,`Author: ${author}`, ""].join("n")),
    ].join("n");
    MailApp.sendEmail({ to: email, subject: "Project Update", body: message });
  });
}

Array multidimensional javascript

this is my first post and i hope the comunity can help me.
I want to create an array in javascript, i tried but i can’t.
this is the array in php, how i do this in javascript?

$structure = array(
            0 => array(
                'columns' => array(
                    array('tipo' => 'banner', 'data' => array('name' => '61b9f0845b7da.jpg'))
                )
            ),
            1 => array(
                'columns' => array(
                    array('tipo' => 'product', 'data' => array('id_product' => 1233198)), 
                    array('tipo' => 'product', 'data' => array('id_product' => 2021097, 'color' => '333'))
                )
            )`enter code here`
        );

Using JavaScript to add an attribute to all

My question is regarding a WordPress site. Using JavaScript or jQuery (I don’t know the difference..), on the entire front-end of the website, I would like to add the attribute accept="image/*" to all of the <input type="file">. Could someone please help me achieve this?

Safari doesn’t find const within function (Can’t find variable)

JavaScript in Safari fails and execution is stopped if const is used within function. All other browsers (Chrome, Firefox, …) work correctly, even on macOS.

My code (simplified):

    const a = 1;
    function f() {
      console.log(a);
    }
    f();

In JavaScript console I can see:
[Error] ReferenceError: Can't find variable: a

I resolved it by changing const to var and it started to work immediately. (I didn’t try let).

    var a = 1;
    function f() {
      console.log(a);
    }
    f();

I tried to investigate and understand why this is a problem. However, none of the resources gave me an answer why const should not work within function:

Is it something to do with Safari (security?) settings?

Unfortunately, I can’t troubleshoot this further as I’m working on Windows and don’t have macOS available all the time.

Jest: Cannot read properties of undefined (reading ‘0’)

I’m newbie with jest and I have made a test to check several calls to datababase from an url.

I run the test with this command:

npx jest --watchAll file.test.js

And everything works fine. But, If I modify a comma, for example, the test is running again and I’ve got errors. I haven’t any “OK” from the api and I’ve got this error too:

TypeError: Cannot read properties of undefined (reading '0')

When I try to check what I have received with what I have expected, like we can see in this line:

expect(1).toBe(result.data[0].id);

If I stop the test and run again with: npx jest –watchAl file.test.js everything works fine.

What happend? Why Have I got these errors when the test is running for twice?

The code of my test is:

import config from "../config";
import {getData} from "../com/functions";

describe("Test several connections with Postgress making a request via POST", () => {
    describe("Test read data from database", () => {
        test("Test 1: Read data from tbl001_users", async () => {
            let data = {
                "query": 1,
                "origin": "Mapping-Service"
            };
    
            let result = await getData(`${config.backend.protocol}://${config.backend.domain}:${config.backend.port}/api/youmalou`, data);
            console.log(result);
            expect(1).toBe(result.data[0].id);
            expect("OVT").toBe(result.data[0].code);
            expect(2).toBe(result.data[1].id);
            expect("TTHOT").toBe(result.data[1].code);
        });
        test("Test 2: Read data from tbl001_users", async () => {
            let data = {
                "query": 1,
                "origin": "Mapping-Service"
            };
    
            let result = await getData(`${config.backend.protocol}://${config.backend.domain}:${config.backend.port}/api/youmalou`, data);
            expect(1).toBe(result.data[0].id);
            expect("OVT").toBe(result.data[0].code);
            expect(2).toBe(result.data[1].id);
            expect("TTHOT").toBe(result.data[1].code);
        });
        test("Test 3: Read data from tbl001_users", async () => {
            let data = {
                "query": 1,
                "origin": "Mapping-Service"
            };
    
            let result = await getData(`${config.backend.protocol}://${config.backend.domain}:${config.backend.port}/api/youmalou`, data);
            expect(1).toBe(result.data[0].id);
            expect("OVT").toBe(result.data[0].code);
            expect(2).toBe(result.data[1].id);
            expect("TTHOT").toBe(result.data[1].code);
        });
        test("Test 4: Read data from tbl002_suppliers", async () => {
            let data = {
                "query": 2,
                "params": ["OVT"],
                "origin": "Mapping-Service"
            };
    
            let result = await getData(`${config.backend.protocol}://${config.backend.domain}:${config.backend.port}/api/youmalou`, data);
            expect("OK").toBe(result.result);
            expect(1).toBe(result.data.length);
        });
        test("Test 5: Read data from tbl002_suppliers", async () => {
            let data = {
                "query": 2,
                "params": ["OVT"],
                "origin": "Mapping-Service"
            };
    
            let result = await getData(`${config.backend.protocol}://${config.backend.domain}:${config.backend.port}/api/youmalou`, data);
            expect("OK").toBe(result.result);
            expect(1).toBe(result.data.length);
        });
        test("Test 6: Read data from tbl002_suppliers", async () => {
            let data = {
                "query": 2,
                "params": ["OVT"],
                "origin": "Mapping-Service"
            };
    
            let result = await getData(`${config.backend.protocol}://${config.backend.domain}:${config.backend.port}/api/youmalou`, data);
            expect("OK").toBe(result.result);
            expect(1).toBe(result.data.length);
        });
    });
});

The file where I dispatch the requests has this code:

import express from "express";
import {getData} from "../com/functions";
import config from "../config";
import cors from "cors";
import {YoumalouDDBB} from "../database/Youmalou/youmalou_ddbb";


const router = express.Router();

const ddbb = new YoumalouDDBB();
async function start(){
    await ddbb.connect();
}

start();

let url = null;
let urls = null;

if ((config.node_env === "test") || (config.node_env === "development") ||  (config.node_env === "production")){
    url = `${config.frontend.protocol}://${config.frontend.domain}:${config.frontend.port}`;
    urls = `${config.frontend.protocols}://${config.frontend.domain}:${config.frontend.port}`;
}

const corsOptions = {
    origin: [url, urls],
    optionSuccessStatus: 200,
    methods: ["POST", "OPTIONS"],
};

if ((config.node_env === "test") || (config.node_env === "development") || (config.node_env === "production")){
    router.all("*", cors(corsOptions));
}

router.post("/api/youmalou", async(req, res)=> {
    let result = null;
    

    if (typeof(req.body.query) === "number"){
        console.log(req.body);
        result = await ddbb.getDataFromDDBB(req.body.query, req.body.params);
    }

    res.json(result.data);
});

module.exports.Router = router;

The :max doesn’t work properly in html input control when typing in a value

I have a form with inputs based on a model in vue.js. The model contains an array of objects in searchResultOrderLines.

<tr v-for="(item, index) in searchResultOrderLines" v-bind:value="item" v-on:click="editSearchRow(index)">
    <td>
        <input class="form-control" type="number" v-model="item.QuantityPicked" min="0" :max="item.QuantityNeeded" />
    </td>

The input renders as a numeric control with arrows to increment and decrement. It will not allow the user to spin below 0, nor above the value defined in the item.QuantityNeeded, which is as required. However, the user is able to enter a numeric value which is > item.QuantityNeeded, by simply typing into the text box. Is there any way of limiting or preventing this?