RegExp working on RegExr but not in my JavaScript program

I’m trying to pull the username (danielj) from this URL:

https://danielj.tr.cwhq-apps.com/i_m113_intro_prog_py_09/ghost-busters

This regular expression seems to be what I need if I want to get the username in the first capturing group:

https://(w+).

I tried it on RegExr https://regexr.com/6osbp and it gives me exactly what I want (the first capturing group contains danielj).

When I run the same logic in a JavaScript program, I get null:

function getUsername(url) {
    const re = new RegExp("https://(w+).");
    const match = url.match(re);
    console.log(match);
}

const url = "https://danielj.tr.cwhq-apps.com/i_m113_intro_prog_py_09/ghost-busters";

getUsername(url); // null

My JavaScript is a bit rusty, but I thought this seemed straightforward enough. What am I missing?

I’ve read through these docs to refresh my JS memory, and it seems like everything matches up syntax-wise:

How to insert an array inside another array in NODEJS + MYSQL(knex) knex.schema.createTable?

I have these two tables created, one called “products”, and another called “cart”, I want to enter in the “cart” table the same products that I have in the “products” table in the form of an array of objects in which each object be a product, but I have the following error when trying to make a post (save) of the products:
code: ‘UNKNOWN_CODE_PLEASE_REPORT’,
errno: 4025,
sqlMessage: ‘CONSTRAINT cart.products failed for one_comfort.cart‘,
sqlState: ‘23000’,
index: 0,
sql: “insert into cart (idCart, products) values (18779, ‘[object Object]’)”
How can i solve this?

my “products” table is like this:

[
  {
    "id": 23448,
    "price": 60,
    "title": "ADIDAS TEE HULK",
    "date": "6/6/2022, 3:34:43 AM",
    "description": "ADIDAS TEE HULK UNISEX 100% COTTON.",
    "stock": "3",
    "code": "551A0",
    "image": "https://sevensport.vteximg.com.br/arquivos/ids/388207-1000-1000/GP3398_1.jpg?v=637599860976670000",
    "category": "t-shirts",
    "new": true,
    "logo": "https://www.chelsea.com.ar/arquivos/adidas-ch.jpg",
    "genre": "men"
  },
  {
    "id": 30463,
    "price": 50,
    "title": "PUMA EVIDE GRAPHIC TEE",
    "date": "6/6/2022, 3:37:02 AM",
    "description": "PUMA EVIDE GRAPHIC TEE WOMEN'S T-SHIRT",
    "stock": "3",
    "code": "111A0",
    "image": "https://sevensport.vteximg.com.br/arquivos/ids/407751-500-500/59974701_1.jpg?v=637644782507230000",
    "category": "t-shirts",
    "new": true,
    "logo": "https://www.chelsea.com.ar/arquivos/puma-ch.jpg",
    "genre": "men"
  }
]

and i want my “cart” table to be like this:

[
  {
    "id": 62621,
    "date": "6/28/2022, 3:43:04 AM",
    "products": [
      {
        "id": 57698,
        "title": "Camisa no cool!",
        "price": 230,
        "image": "https://sevensport.vteximg.com.br/arquivos/ids/414267-1000-1000/02128G8_1.jpg?v=637659506619730000",
        "description": "FULL DRICE!",
        "stock": 3,
        "date": "6/28/2022, 3:43:04 AM",
        "code": "GAFG",
        "category": "men"
      },
      {
        "id": 57692,
        "title": "Camisa cool!",
        "price": 230,
        "image": "https://sevensport.vteximg.com.br/arquivos/ids/414267-1000-1000/02128G8_1.jpg?v=637659506619730000",
        "description": "FULL DRICE!",
        "stock": 3,
        "date": "6/28/2022, 3:43:04 AM",
        "code": "GAFG",
        "category": "men"
      }
    ]
  }
]

[mySqlPersistence]

const { knexConfig } = require("../../services/MYSQL/config");
const knex = require("knex")(knexConfig);

knex.schema
  .createTableIfNotExists("products", (table) => {
    table.increments("id").primary();
    table.string("title");
    table.string("description");
    table.integer("price");
    table.integer("stock");
    table.string("image");
    table.string("code");
    table.string("category");
    table.boolean("new");
    table.timestamp("date").defaultTo(knex.fn.now());
    table.string("logo");
    table.string("genre");
  })
  .then(() => {
    return knex.schema.createTableIfNotExists("cart", (t) => {
      t.increments("idCart").primary();
      t.timestamp("dateCart").defaultTo(knex.fn.now());
      t.json("products");
      t.integer("product_id").unsigned();
      t.timestamp("date").defaultTo(knex.fn.now());
      t.foreign("product_id").references("id").inTable("products");
    });
  })
  .catch((err) => {
    console.log("Error creating table:", err);
  });

module.exports = knex;

[containerMySql]

const { knexConfig } = require("./config");
const knex = require("knex")(knexConfig);
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);

class Container {
  constructor(table) {
    this.table = table;
  }

  async findAll() {
    const element = await knex(this.table);
    return element;
  }

  async save(data) {
    return await knex(this.table).insert(data);
  }

  async find(id) {
    const element = await knex(this.table).where("id", id);
    return element;
  }

  async update(id, data) {
    const element = await knex(this.table).where("id", id).update(data);
    return element;
  }

  async getCarts() {
    const element = await knex(this.table);
    return element;
  }

  async deleteAll() {
    await knex(this.table).delete();
  }

  async deleteOne(id) {
    await knex(this.table).where("id", id).delete();
  }

  async getProducts(idCart) {
    const element = await knex(this.table).where("id", idCart);
    return element;
  }
}

class KnexProductsContainer extends Container {
  async find(id) {
    const element = await knex(this.table).where("id", id).select("*");
    return element;
  }

  async save(data) {
    try {
      await knex(this.table).insert(data);
    } catch (error) {
      console.log("FAIL " + error);
    }
  }

  async update(id, data) {
    const element = await knex(this.table).where("id", id).update(data);
    return element;
  }
}

class KnexCartContainer extends Container {
  async find(id) {
    const element = await knex(this.table).where("id", id).select("*");
    return element;
  }

  async getProducts(idCart) {
    const element = await knex(this.table).where("id", idCart).select("*");
    return element;
  }

  async save(data) {
 
    const newCart = {
      idCart: Number(nanoid()),
      products: [],
    };

    newCart.products.push({
      product_id: Number(nanoid()),
      title: data.title,
      price: data.price,
      logo: data.logo,
      stock: data.stock,
      description: data.description,
      category: data.category,
      genre: data.genre,
      image: data.image,
      code: data.code,
    });

    await knex(this.table).insert(newCart);
    return newCart;
  }

  async update(id, data) {
    const element = await knex(this.table).where("id", id).update(data);
    return element;
  }
}

module.exports = { Container, KnexProductsContainer, KnexCartContainer };

What do I do with this ‘session’ created by passport.js?

I am implementing user authentication and and once they are authenticated, they can CRUD their user data on the database. I can currently authenticate users and have users register a new account, but im not sure what my next step should be. What should my Node server pass back to my front end once my user is authenticated? I read everywhere that I am suppose to use tokens and sessions to check if user is auth for every request.

Auth.js

const router = express.Router()
const passport = require("passport")


router.post("/login", (req, res, next) => {
    passport.authenticate("local", function(err, user, info) {
        console.log(user)
        if(err){
            return res.status(400).json({errors: err})
        }
        if(!user){
            return res.status(400).json({errors: "Incorrect username or password"})
        }
        //figure out what this does 
        req.logIn(user, function(err){
            if(err){
                return res.status(400).json({errors: err});
            }
            return res.status(200).json({success: `Logged in ${user.id}`})
        })

    })(req, res, next)
})

module.exports = router 

Setup.js (for passportjs)

const bcrypt = require("bcrypt")
const User = require('../models/user')
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;

passport.serializeUser((user, done) => {
    done(null, user.id)
})

passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
        done(err, user);
    })
})

passport.use(
    new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
        //Match user
        User.findOne({ email: email })
            .then(user => {
                //match password
                bcrypt.compare(password, user.password, (err, isMatch) => {
                    if (err) throw err;
                    if (isMatch) {
                        console.log("successfully auth")
                        return done(null, user);
                    } else {
                        console.log("incorrect password ")
                        return done(null, false, { message: "Incorrect Password" })
                    }
                })

            })
            .catch(err => {
                console.log("no account found")
                return done(null, false, { message: err })
            })
    })
)
module.exports = passport

index.js

require('dotenv').config()
const express = require('express');
const session = require('express-session');
const mongoose = require("mongoose")
const MongoStore = require("connect-mongo")
const cors = require("cors");
const axios = require('axios');
const User = require('./models/user')
const bcrypt = require('bcrypt')

const passport = require("./passport/setup")
const auth = require("./routes/auth")


const app = express();
app.use(cors());
let port = process.env.PORT;
if (port == null || port == "") {
  port = 5000;
}

mongoose.connect(process.env.ATLAS_URI).then(console.log("MongoDB Connection Success")).catch(err => console.log("MongoDB Connection Failed" + err))
// For backend and express init
app.use(express.json());
app.use(express.urlencoded({ extended: false }))

app.use(session({
  secret: 'random secret',
  resave: false,
  saveUninitialized: true,
  store: MongoStore.create({ mongoUrl: process.env.ATLAS_URI }),
}));


app.use(passport.initialize())
app.use(passport.session())

app.use("/auth", auth)

app.post('/register', (req, res) => {
  const email = req.body.email
  const plainTextPassword = req.body.password;

  //check if user already exists 
  User.find({ name: email }, (err, existingUser) => {
    if (existingUser.length === 0) {
      bcrypt.hash(plainTextPassword, 8, async (err, hash) => {
        try {
          const user = new User({
            email: email,
            password: hash
          });
          let result = await user.save();
          if (result) { 
            console.log("account registered successfully")
            res.send(result)
          }

        } catch (e) {
          res.send("Something Went Wrong");
          console.log("something went wrong ---" + e)
        }
      })
    } else {
      console.log("user account already exists! Login instead. ")
    }
  })

})

Im not trying to debug an error, just need to know what the approach is. Basically, I want the user to login once, and then be able to navigate around the web app and crud to their database. Thank you!!

My sessions are stored in a different collection in mongodb but idk what to do with this

Bootstrap 3 Dropdown hide.bs.dropdown eventTarget Property Returns Undefined

I need to get the target of a click event inside a BootStrap 3 dropdown menu. After a lot of googling I found this answer, which seems to be exactly what I need. But e.eventTarget always returns undefined. Below is my code

$(document).on("hide.bs.dropdown", ".name-dropdown", function(e) { 
  console.log(e.clickEvent.target);
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="col-sm-4 text-left customer-name">
  <div class="dropdown name-dropdown">
    <input class="customer-namefield form-control dropdown-toggle text-box single-line" data-toggle="dropdown" id="Customer_Name" name="Customer.Name" placeholder="Name" type="text" value="test" aria-expanded="true">
    <div class="name-menu dropdown-menu" style="">
      <table>
        <tbody>
          <tr class="name-menu-row">
            <td>test123</td>
            <td></td>
            <td></td>
          </tr>
          <tr class="name-menu-row">
            <td>test12</td>
            <td></td>
            <td></td>
          </tr>
          <tr class="name-menu-row">
            <td>test</td>
            <td></td>
            <td></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

I will be populating the dropdown via ajax. When the user clicks on one of the <tr> it will autocomplete several input fields at once with the data in that table row.

Also if you can suggest a better way to reach my end goal, I would be open to other ideas.

issue with select using jquery chained plugin

I am using the jquery chained plugin and its somewhat working, means half working, i am able to get the json data from the remote page call but its not populating the select and also on the first select, the jquery ajax does not get fired when i select sometimg very first time, it runs the ajax call, if i select something else or again same value from the select call.

so saying, it works on the second call to the first select, first call does not work.

here is my fiddle for it

https://jsfiddle.net/ye7o459n/

the problem seems to how i am calling it but i am totally not sure

here is the code JS Code

<select class="classnocss select2_el" id="IDParent" style="" name="CampaignID" data-validation="required" data-validation-error-msg=" selection is required." data-placeholder="Select Campaign" data-allow-clear="true">
                
                    <option value="" selected> - Select -</option>
                
                    <option value="2123" >Drowning (2123)</option>
                
                    <option value="2067" >andel - Sentido (2067)</option>

          </select>
          
           <select name="CampaignPlatformID" id="IDChild" data-url="../ajaxCall.cfm" data-id="253"
      data-validation="required" style="width:75%" 
      data-validation-error-msg="Platform selection is required.">
    </select> 

jquery code

$(document).on('change', $("#IDChild"), function(el) {
    $(this).remoteChained({
      parents : "#IDParent",
      url : "../ajaxCall.cfm?action=dealpost&dealID="+ $('#IDChild').attr('data-id')
    });

How can I check the radio button with a single click? and how to select one by default?

I am trying to make a simple react app that displays radio input for each ‘hero’ from a list of heroes and if the user checks, the hero’s name will be displayed as the favorite hero. But the problem is on my local machine to check a hero I need to double click that radio input. How can I check a hero with a single click?
Code of the app.js file is given below:

import React, { useState } from "react";
import "./App.css";
function App() {
    const [heros, setHeros] = useState([
        "Superman",
        "Batman",
        "Antman",
        "Robocop",
    ]);
    const [selected, setSelected] = useState(null);

    const handleChange = (e) => {
        e.preventDefault();
        setSelected(e.target.value);
        console.log(e.target.checked);
    };


    return (
        <div>
            <h1>Select Your Favorite Hero</h1>
            <form onChange={handleChange}>
                {heros.map((hero, index) => (
                    <div key={index}>
                        <input
                            type="radio"
                            name="hero"
                            id={hero}
                            value={hero}
                            onChange={handleChange}
                            // onClick={handleClick}
                        />
                        <label htmlFor="{hero}">{hero}</label>
                        <br />
                    </div>
                ))}
            </form>
            <div>
                <p>Your super hero is: {selected}</p>
            </div>
        </div>
    );
}
export default App;

JS pull property from object in array and set to root level in array

I’m building off a prior question: React displaying data in a table with dynamic columns

In that question I was working on building a table to reflect the amount of hours worked for a client per day in a month (selected by the user, but the codesandbox I made is simplified). For another part of the app, I’m expanding that table so that an admin selects a user, month, and year and then the table populates the days of the month as the header, with each row being a different client. After a few steps, I have the output close to what I’m looking for, but 1 step shy and I’m stuck…

Heres the simplified data set and current logic:

const data = [
    {
    start: "2022-04-3",
    hours: 1,
    client: {
        id: "123",
      fullName: "Tom Tom"
    }
  },
  {
    start: "2022-04-10",
    hours: 2,
    client: {
        id: "123",
      fullName: "Tom Tom"
    }
  },
  {
    start: "2022-04-10",
    hours: 3,
    client: {
        id: "123",
      fullName: "Tom Tom"
    }
  },
  {
    start: "2022-04-10",
    hours: 1,
    client: {
        id: "123",
      fullName: "Tom Tom"
    }
  },
  {
    start: "2022-04-13",
    hours: 1,
    client: {
        id: "456",
      fullName: "Jack Jack"
    }
  },
  {
    start: "2022-04-13",
    hours: 2,
    client: {
        id: "123",
      fullName: "Tom Tom"
    }
  },
  {
    start: "2022-04-15",
    hours: 1,
    client: {
        id: "789",
      fullName: "Pete Pete"
    }
  },
  {
    start: "2022-04-15",
    hours: 1,
    client: {
        id: "789",
      fullName: "Pete Pete"
    }
  }
]

let collData = data.reduce((accumulator, currentValue) => { 
    let existing = accumulator.find((n) => n.client.id === currentValue.client.id && n.start === currentValue.start);
            if (existing) {
              existing.hours += currentValue.hours;
            } else {
              accumulator.push(currentValue);
            }
            return accumulator;
          }, []);
        console.log("step 1 ", collData);
        
        
let res = {};



collData.forEach((item) => {
    const splitDate = item.start.split("-");
    const day = splitDate[splitDate.length - 1];

    const newStat = { start: parseInt(day), hours: item.hours};
      
   if(res[item.client.id])
   {
       let stats = res[item.client.id].stats;
        stats = [...stats, newStat];
        res[item.client.id].stats = stats;
   }
   else{
      res[item.client.id] = {
        client: item.client,
        stats: [newStat]
      }
   }
    
  });


  let filtArr = [];
  
  const daysInMonth = 30;
 
    let dayInfo = [];
    for (let i = 1; i <= daysInMonth; i++) {
      dayInfo.push(i)
 
      // create an array and fill hours with 0
 var dayArr = dayInfo.map((day) => ({
        day: day,
        hours: 0
      }));
      } 
      
const displayDates = (id) => {
  const client = res[id];

    let temp = [];
      dayArr.map((i, idx) => {
        const getHours = client.stats.find((item) => item.start === i.day);
        let newStats = {};
        if (getHours) {
          newStats = {
          
            client: {fullName: client.client.fullName, id: client.client.id},
            stats: [{
                day: i.day,
                hours: getHours.hours,
            }]
            
            
          };
      
        }
        else{
          newStats = {
            
            client: {fullName: client.client.fullName, id: client.client.id},
            stats: [{
                day: i.day,
            hours: 0,
            
            }]
            
          };
        }
        temp[idx] = newStats;
      });
 return temp;
      
}

 Object.keys(res).forEach(id=>{
    filtArr = [...filtArr, res[id]];
        console.log(displayDates(id))
  })

In order to map out the table rows/data, I’m trying to get the final data to be structured as: (currently client is being populated with each day of the month/hours)

current output = 
[{
  client: {
    fullName: "Pete Pete",
    id: "789"
 },
  stats: [{
    day: 1,
    hours: 0
   }]
 }, {
  client: {
    fullName: "Pete Pete",
    id: "789"
 },
  stats: [{
    day: 2,
    hours: 0
  }]
 }, {
  client: {
    fullName: "Pete Pete",
    id: "789"
 },
  stats: [{
    day: 3,
    hours: 0
  }]
 },//and so on for all days of the month
]

ideal output=
[
  {
    client: {name: "name name", id: "123"},
    stats: [
             {day: 1, hours: 0},
             {day: 2, hours: 1},
             {day: 3, hours: 0},
             {day: 4, hours: 2},
             //and so on for all the days in the month
            ]
  }
]

I’ve tried using map and forEach to get this structure, but I must not be understanding something about accessing the object properties in the array (I keep getting undefined errors). I figured there was probably somewhere in the logic along the way I could have structure it like this, but I’m not skilled enough to figure that out.
I have a JSFiddle with a live example: https://jsfiddle.net/joznox/xzd5y142/3/

Any help would be greatly appreciated.

Promise.all fetch continue executing after throwing error?

I am trying to fetch JSON data from the WordPress Developer Reference site. I need to search a keyword without knowing if it’s a function, class, hook, or method, which is part of the url I need to fetch. So I’m using Promise.all to cycle through all possible urls. It works if the response.status <= 299, throwing the error immediately, and if the response is ok, then it continues to .then. Fine, but occasionally it will return an ok status if the JSON exists and only returns an empty array. So I need to check if the JSON data is an empty array, which I can’t seem to do in the first part. I can only check in the second part as far as I know. And if it throws the error it doesn’t continue trying the other urls. Any suggestions?

var keyword = 'AtomParser';
const refs = ['function', 'hook', 'class', 'method'];

// Store the promises
let promises = [];

// Cycle through each type until we find one we're looking for
for (let t = 0; t < refs.length; t++) {
  const url =
    'https://developer.wordpress.org/wp-json/wp/v2/wp-parser-' +
    refs[t] +
    '?search=' +
    keyword;
  // console.log(url);
  promises.push(fetch(url));
}
Promise.all(promises)
  .then(function(response) {
    console.log(response[0]);

    // Get the status
    console.log('Status code: ' + response[0].status);
    if (response[0].status <= 299) {
      // The API call was successful!
      return response[0].json();
    } else {
      throw new Error('Broken link status code: ' + response[0].status);
    }
  })
  .then(function(data) {
    // This is the HTML from our response as a text string
    console.log(data);

    // Make sure we have data
    if (data.length == 0) {
      throw new Error('Empty Array');
    }

    // ref
    const reference = data[0];

    // Only continue if not null or empty
    if (reference !== null && reference !== undefined && data.length > 0) {
      // Success
      // Return what I want from the reference
    }
  })
  .catch(function handleError(error) {
    console.log('Error' + error);
  });

Is there some way to get the JSON data in the first part so I can check if it’s in an array while I’m checking the response status?

JS intitialise “” array based on input?

I’m not entirely sure on the term for this. Which is why after 20 mins of googling I thought it was a good question to ask.

What this called, and how you do?:

eg. The following is the wanted result

 const [arrArr, setArrArr] = useState( [ ["", "", "", "", ""],["", "", "", "", ""],["", "", "", "", ""]]); 

To get this an arr should be based on currentWord.length and element length of arrArr should be of lives

useEffect(()=> {

    setArrArr(......)
},[])

How to make edit function that replaces existing text for To-Do App?

I created an editItem function which creates the HTML element when the user clicks on the edit button, I am not sure how to go about when the user inputs, when the update replaces the existing task.

I am aware that the replace can be used to replace the new-task-created class in the renderList

Just a note I created a new object updateEl which contains the class of the modal and I also created updateTask function which returns the new values been inserted.

My thinking pattern is this: If I need to create new values for the user input, time, and date, that new information can just replace the old information when they click save ( UpdateTask function)

HTML

<div class="form">
   <input class ="user-input" type="text">
   <input class="date" type="date">
   <input class="time" type="time">
   <button onclick="addTask()" class="add" id="add">+</button>
</div>

  <div class="list"></div>
<div class="modal"></div>

JS

//local storage key
const STORAGE_KEY = "tasks-storage-key";

// variables object
const el = {
  form: document.querySelector(".form"),
  input: document.querySelector(".user-input"),
  list: document.querySelector(".list"),
  date: document.querySelector(".date"),
  time: document.querySelector(".time"),
};

const updateEl = {
  formUpdate: document.querySelector(".form-update"),
  inputUpdate: document.querySelector(".user-input"),
  modal: document.querySelector(".modal"),
  dateUpdate: document.querySelector(".date-update"),
  timeUpdate: document.querySelector(".time-update"),
};

//Create ID

const createId = () =>
  `${Math.floor(Math.random() * 10000)}${new Date().getTime()}`;

//variable of empty array that gets new task
let taskList = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? "[]");

renderList();

function makeNewTask() {
  const data = {
    id: createId(),
    taskNew: el.input.value,
    taskDate: el.date.value,
    taskTime: el.time.value,
  };

  return data;
}

function updateTask() {
  const dataUpdate = {
    id: createId(),
    inputUpdate: updateEl.inputUpdate.value,
    dateUpdate: updateEl.dateUpdate.value,
    timeUpdate: updateEl.timeUpdate.value,
  };

  return data;
}


function renderList() {
  // This resets the list innerHTML to the new list
  el.list.innerHTML = taskList.map(function (data) {
    return `<div class="task">
            <div class="task-content">
                <div class="task" data-id="${data.id}">
                <div class="new-task-created">${data.taskNew}</div>
                <label class="due-date">${data.taskDate}</label>
                <label class="due-time">${data.taskTime}</label>
            </div>
    
            <div class="action-buttons">
                <button onclick="editItem(event)" class="edit" data-id="${data.id}">Edit</button>
                <button onclick="deleteItem(event)" class="delete" data-id="${data.id}">Delete</button>
                <button onclick="completeItem(event)" class="complete" data-id="${data.id}">Complete</button>
            </div>
        </div>`;
  });

  
}

//event listner that listens for add button.
function addTask() {
  taskList.push(makeNewTask());
  // store the list on localstorage because data changed
  storeList();
  // render list again because you've added a new entry
  renderList();
  
}

//function that removes task from array with delete button.
function deleteItem(event) {
  taskList.splice(taskList.indexOf(event.target.dataset.id), 1);
  // store the list on localstorage because data changed
  storeList();
  // render list again because entry was removed
  renderList();
}

//function that stores task list.
function storeList() {
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(taskList));
}

//function that that edits tasks with date and time.
function editItem() {

  let updateInput = document.createElement("div")
  updateInput.innerHTML = `<div class="form-update">
        <input class ="input-update" type="text">
        <input class="date-update" type="date">
        <input class="time-update" type="time">
        <button onclick="UpdateTask()" class="update" id="update">Save</button>
        <button onclick="close()" class="close" id="close">Save</button>
    </div>`;

    updateEl.modal.appendChild(updateInput);
}


function UpdateTask(){

}


//function that that completes task.
function completeItem(event) {
  const element = event.target.closest(".task-content");
  let taskItem = element.querySelector(".new-task-created");
  let dateItem = element.querySelector(".due-date");
  let timeItem = element.querySelector(".due-time");
  // style..
  taskItem.style.textDecoration = "line-through";
  dateItem.style.textDecoration = "line-through";
  timeItem.style.textDecoration = "line-through";
}

use aurthentification prompt issue

im trying to athentificate user with prompts but alert always say authentification approved id like to know what to do to fix it

<script>
    var code_utilisateur = prompt("fournissez votre code utilisateur").toLowerCase();
    var mot_de_passe = prompt("entrez votre mot de passe").toLowerCase();
    var tableau = ["admin,qwerty", "bob,starwars123", "marie,1q2w3e"];
    alert(code_utilisateur);
    if (code_utilisateur && mot_de_passe == tableau[0] || tableau[1] || tableau[2]) {
        alert("Authentification réussie");
        alert("Bonjour " + code_utilisateur);
    }
    else {
        alert("Echec d'authentification");
    }
</script>

JavaScript – Ordering an array of objects with a chunk size / repeating pattern

I have some JSON (returned from a DB query, sample below) that I’m trying to figure out how I can order in a very specific manner:

+────────────────+─────────────────+─────────────────+
| Desired order  | Not acceptable  | Not acceptable  |
+────────────────+─────────────────+─────────────────+
| AA08-1         | AA08-1          | AA08-1          |
| AA09-1         | AA09-1          | AA08-2          |
| AA10-1         | AA10-1          | AA08-3          |
| AA08-2         | AA11-1          | AA09-1          |
| AA09-2         | AA08-2          | AA09-2          |
| AA10-2         | AA09-2          | AA09-3          |
| AA08-3         | AA10-2          | AA10-1          |
| AA09-3         | AA11-2          | AA10-2          |
| AA10-3         | AA08-3          | AA10-3          |
| AA11-1         | AA09-3          | AA11-1          |
| etc.           | etc.            | etc.            |
+────────────────+─────────────────+─────────────────+

It needs to repeat after a set “chunk size” (in this case 3), and loop through the data.

The data is pre-sorted in the order in which the References should appear, (taking into effect the date and various other criteria), but not in the order that the steps appear.

I’ve been able to easily sort it either by the “Step” or by the “Reference” using a loop (and combine those values into a single string. But I have not been able to figure out how to order as shown in the first column. I need to take the first 3 references, and combine with the step “1”, then take those same 3 references, combine with the step “2”, and then take those same 3 references, combine with the step “3”, and then start with the next “group” of references and repeat the process. (The position of AA11-1 being crucial in grasping that.)

Here’s an example of the JSON data: [This is a simplified data set.]

[
    {
        Reference: 'AA08',
        Date: 2022-06-22,
        Step: 1,
    },
    {
        Reference: 'AA09',
        Date: 2022-06-23,
        Step: 1,
    },
    {
        Reference: 'AA10',
        Date: 2022-06-24,
        Step: 1,
    },
    {
        Reference: 'AA11',
        Date: 2022-06-24,
        Step: 1,
    },
    {
        Reference: 'AA08',
        Date: 2022-06-22,
        Step: 2,
    },
    {
        Reference: 'AA09',
        Date: 2022-06-23,
        Step: 2,
    },
    {
        Reference: 'AA10',
        Date: 2022-06-24,
        Step: 2,
    },
    {
        Reference: 'AA11',
        Date: 2022-06-24,
        Step: 2,
    },
    {
        Reference: 'AA08',
        Date: 2022-06-22,
        Step: 3,
    },
    {
        Reference: 'AA09',
        Date: 2022-06-23,
        Step: 3,
    },
    {
        Reference: 'AA10',
        Date: 2022-06-24,
        Step: 3,
    },
    {
        Reference: 'AA11',
        Date: 2022-06-24,
        Step: 3,
    }
]

I’ve tried a lot of things, and I’m not really any further ahead. Here’s an example of something I was playing with, but it does not achieve the desired results. (Splits it into separate arrays, but not in a helpful way.)

const chunkSize = 3;
const processedData = [];
for (let i = 0; i < jsonData.length; i += chunkSize) {
    const chunk = jsonData.slice(i, i + chunkSize);
    const processedChunk = chunk.map((item) => ({
      ...item,
      Reference: item.Reference + '-' + item.Step
    }))
    processedData.push(processedChunk)

  }
  console.log(processedData)

Any pointers would be appreciated!

(I’ve looked at a pile of SO posts, so please don’t just down-vote this – I haven’t found anything that seems to address this need.)

Storing the name of the current user and matched user in state using useEffect returning incorrect output

I have a function in my context that takes in two data points, the current username and the username of a randomly selected user who is online

const pairProgrammingMatching = (username, matchedUser) => {
    setPairUsers({username: matchedUser })
}

I call this function in another component using useEffect()

    useEffect((() => {
        console.log('curr username is', username)
        pairProgrammingMatching(username, checkOnlineUsers(pickRandom()).username)
        console.log('inside pairUsers state', pairUsers)
    }), [])

checkOnlineUsers simply returns a list of all users who are currently online and active

let checkOnlineUsers = () => {
    const results = onlineUsers.filter(obj => {
        return obj.profile.is_online === true && obj.profile.currently_active === false && obj.username !== user.username
    })
    return results
}

Here’s a sample of what this function returns

[{ email: "***@gmail.com"
   first_name: ""
   last_name: ""
   profile: {city: 'Washington DC', country: 'USA', is_online: true, currently_active: false}
   username: "testingUser" }]

pickRandom simply picks a number between 0 and n, with n being the number of users returned in checkOnlineUsers:

const pickRandom = () => {
    return Math.round(Math.random()*onlineUsers.length)
}

The problem here is that if I print out pairUsers inside my useEffect I expect to see this:

{ 'userA': 'testingUser' }

with userA being the name of the current user. However this is what I get:

{username: undefined}