Safe and Secure way for Storing Sensitive Data in JS [closed]

I have made a login form for new users and I was wondering if anyone had thoughts on the best ways to store form data (the sensitive data being passwords) in javascript.

I do not want to use Local or Session storage and I think that IndexedDB is also not safe because it is easier to hack. I think that Caches are a possibility but let me know your thoughts.

Thanks.

How perform successive fetch() requests that build upon previous responses? [duplicate]

I apologize in advance about any obvious issues, I’m kind of fumbling my way through this at the moment and feel a bit in over my head.

I’m attempting to perform a fetch request in JavaScript using an asynchronous function that makes takes the result of a previous asynchronous function as an argument. The first function works fine, and delivers the Unique ID I need to progress into chaining multiple API calls together. When attempting to use it in another API call, I’ll be told that the Object I’m trying to pass as an argument is a promise.

Here’s the functioning code for the first fetch request.

    var gameName = 'Death in Taxes'; // Input by a user, stored as variable here for development.
    var tagLine = 'NA1';  // Input by a user, stored as variable here for development.

    fetchPuuid(gameName, tagLine); // Calls function

    async function fetchPuuid(gameName, tagLine){

       //Creates URL
       const apiURL = `https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/${gameName}/${tagLine}`;
       const queryParams = {
          api_key: 'RGAPI-c6450472-ed11-4c53-baa0-f6f8d739cdf5' // Changes every 24 hours
       };
       const queryString = new URLSearchParams(queryParams).toString();
       const fullUrl = `${apiURL}?${queryString}`;

       try{
          const response = await fetch(fullUrl);

          if(!response.ok){
             throw new Error('Could not fetch puuid');
          }
    
          const data = await response.json();
          puuid = data.puuid;
          return puuid;
       }
       catch(error){
          console.error(error);
       }
    }

When I attempt to use the function and store the response in an object const puuid = fetchPuuid(gameName, tagLine); then attempting to use that object returns a promise. Specifically it’s labeled as an [object Promise] when used as a variable in the fetchMatchByPuuid function.

So for example calling the below function with fetchMatchByPuuid(fetchPuuid(gameName, tagLine)); fails.

    async function fetchMatchByPuuid(puuid){
       const apiURL = `https://americas.api.riotgames.com/lol/match/v5/matches/by-puuid/${puuid}/ids`;
       const queryParams = {
          api_key: 'RGAPI-c6450472-ed11-4c53-baa0-f6f8d739cdf5'
       };
       const queryString = new URLSearchParams(queryParams).toString();
       const fullUrl = `${apiURL}?${queryString}`;
 
       try{
          const response = await fetch(fullUrl);
 
          if (!response.ok){
             throw new Error('Could not fetch Match IDs');
          }
 
          const data = await response.json();
          console.log(data);
       }
       catch(error){
       console.error(error);
       }
    }

After looking around I understand that this is simply the nature of the fetch() request as it’s asynchronous. Still I know there must be some way to use the information you get back, and I’ve been scouring the internet for several hours to no avail.

I’ve tried quite a few things, though all have felt as though I’m simply throwing stuff at the wall and seeing what sticks. Something that confused me was what seems to be an alternate way of writing the code using something called “Promise syntax”, which has arrows used in the code? At a glance, very confusing and I can’t tell if it’s simply outdated or not.

So I’ve tried to simply store the result of the first function into an object, which as mentioned does not work. Instead of working as an object it returns a promise; fair enough. Next I tried calling the function inside of the second function. So inside of fetchMatchByPuuid() I would call fetchPuuid() and assign the result to an object which I would then call further down in the function, which also gave a promise. Next I tried to use the await keyword when calling the function inside another function, which also returned a promise.

I read elsewhere on this site that it could be resolved using a .then callback, but I think that’s done in the other format (Promise syntax) and I don’t even know if it applies to my code.

Lastly I even tried to consolidate the functions into a larger string of fetch requests in a single function but that gave me a stack error and I quickly abandoned that idea.

I’m confident there’s a simple and understandable answer out there that I’m simply struggling to understand, or may even have staring me in the face but at the moment it simply isn’t cooperating.

How to have a single anchor link scroll to two different sections in a single page in react

I have a sidebar section and a content section. Sidebar section basically has anchor links that basically makes the respective Content scroll to top on Right hand side.

But I also want the sidebar link that i clicked scroll to top as well.

Summary: By click of single anchor link i want the anchor tag and the content both to scroll to top. Is it possible?

 const items = Array.from({ length: 15 }, (_, index) => `items from strapi ${index}`);
...
...


<div className="flex gap-4 items-start mt-16 mx-16">
                <div className="aside">
                    <ul>
                        {items.map((item, index) => (
                        <li className="h-16" key={index}>
                            <a
                                onClick={(e) => {
                                e.preventDefault();
                                const targetElement = document.getElementById(`${index}`);
                                if (targetElement) {
                                    targetElement.scrollIntoView({ behavior: 'smooth' });
                                }
                                }} 
                                href={`#${index}`}>{item}
                            </a>
                        </li>
                        ))}
                    </ul>
                </div>
                <div className='flex flex-col'>
                    {items.map((item, index) => (
                        <div id={`${index}`} className='flex pt-16'>
                          {`${index}`} {loaderData?.overview}
                        </div>
                    ))}
                </div>
            </div>

How to achieve this? In my given snippet only the content in RHS scrolls to top

Thumb nail slider using swiper

ERROR in ./src/App.js 27:16-24
export ‘FreeMode’ (imported as ‘FreeMode’) was not found in ‘swiper’ (possible exports: Swiper, default)

ERROR in ./src/App.js 27:26-36
export ‘Navigation’ (imported as ‘Navigation’) was not found in ‘swiper’ (possible exports: Swiper, default)

ERROR in ./src/App.js 27:38-44
export ‘Thumbs’ (imported as ‘Thumbs’) was not found in ‘swiper’ (possible exports: Swiper, default)

webpack compiled with 3 errors and 1 warning
Iam facing this issue in the App.js file

Iam expecting this kind of output. kindly check the output in the youtube link given below.
https://youtu.be/YDj9kcNIGa8?si=f1xNPzD3UyO91j6W

discord api help channel.messages.fetch in a conditional if

not an expert in js so trying to establish a var based on a condition but I cant call let or const in a conditional.

The goal is to get the userid if its either specified or replied to the message author

let user = ' '
let repliedTo = ' '
if (args[1])
    user = args[1].replace("<", "").replace(">", "").replace("@", "")
else if(msg.reference)
    repliedTo = await msg.channel.messages.fetch(msg.reference.messageId)
    user = repliedTo.author.id

I get a TypeError
TypeError: Cannot read properties of undefined (reading 'id')

I thought author.id was returned?

Mapping P5.js to Arduino potentiometers and push buttons

I have a school project that I need help with. I am trying to create an etch-a-sketch with p5.js and an Arduino. I have two potentiometers hooked up and one button. The potentiometers should control the lives on the X and Y axis and the button should clear the drawing.

I have installed node.js and the serial port successfully. I also wrote the Arduino IDE so that it is able to read the values of the potentiometers when they are rotated. These values show up both in the Arduino IDE and the P5.js sketch.

However, when I push the button, nothing happens. When I run the p5.js sketch, a small dot appears where that is supposed to represent the beginning of the line. However, after a few seconds it flies off of the page and disappears.

I don’t think I am understanding how to map the code to the controller properly. The p5.js Sketch code is below. I added a photo of the Arduino IDE code that I am using. I also added photos of how my Arduino is connected

P5.js Sketch Code:

let prevX, prevY;
//let isCleared = false;
let serialPortName = '/dev/tty.usbserial-1130';
let sensors = [200,200,0]

function setup(){
  createCanvas(400,400);
  serial = new p5.SerialPort();
  serial.list();
  serial.on('open', onOpen);
  serial.on('BtnData', BtnData);
  prevX = width/2;
  prevY = height/2;
  
}

function draw(){
  if(isCleared == true);{
  background(250);
  isCleared = false;
  }
  stroke(0);
  strokeWeight(5);
  line(prevX, prevY, sensors[0], sensors[1]);
  //prevX = sensors[0];
  //prevY = sensors[1];
}

function onOpen(){
  print('serial monitor opened.'); 
}

function onData(){
  let data = serial.readLine();
  let sensors = data.split(",");
  prevX = sensors[0];
  prevY = sensors[1];
  prevX = map(prevX, 0, 1023, 0,511);
  prevY = map(prevY, 0, 1023, 0, 511);
  print(data);
}

function BtnData(){
  let currentString = serial.readLine();
  trim(currentString);
  
  if(!currentString)return;
  console.log(currentString);
  latestData = currentString;
  
  
//}

//}
//function mousePressed(){
 // isCleared = true;
}

Link to the p5.js Sketch
https://editor.p5js.org/KelseyV/sketches/asGl0G0MC

Photo of Arduino IDE Etch-A-Sketch Code

Arduino IDE Etch-A-Sketch code

Photos of Arduino Connections

top view of Arduino Uno
front view of bread board
back view of bread board

I would like to be able to control the p5.js sketch with the arduino so that the two potentiometers draw a line on the X and Y axis and the button clears the drawing when pressed.

rust GUI in webAssmbly

  1. I want to implement an image engine to run in a web environment through rust.
  2. Describe some image and animation parameters through a binary file, and then parse the binary file to achieve animation rendering.
  3. Compile the rust program into wasm so that it can run in the web environment.

4.According to the mainstream implementation solutions on the Internet, WebGL or Canvas is called in wasm to implement drawing. Is there any solution that can directly use the rust GUI to draw?

WebDev – How to move element from place to place smoothly with display grid?

I have two images on the page, one at the first row and one at the second row; To make it look like the images are scattered.
I added button in which upon pressing the images will go to one row only, showing that it is arranged.
I took inspiration from this website: https://www.phsofia.com/photoset/karina
I tried to copy the “change view” button

My code currently:

<style>
        #one{
           grid-row: 1;
           grid-column: 2/3;
           transition: 1s;
        }
        #two{
           grid-row: 2;
           grid-column: 3/5;
           transition: 1s;
        }
        #gallery{
            display: grid;
            transition: 1s;
        }
</style>

<body>
    <button id="btn-gallery-arrange">arrange!</button>
    <div id="gallery" class="display">
        <img id="one" class="one" src="https://picsum.photos/200/300" alt="">
        <br>
        <img id="two" class="two" src="https://picsum.photos/200/300" alt="">
        <script>
            var btn_arrange = document.getElementById("btn-gallery-arrange");
            var gallery = document.getElementById("gallery");
            var gallery_img = gallery.querySelectorAll("img");
            var img_Array = Array.from(gallery_img);

        
            btn_arrange.addEventListener("click",function(){
                img_Array.forEach(function(el){
                    el.style.gridRow = "1";
                    el.style.gridColumn = "span 1";
                });
            },false);
        </script>
        </body>

-Problem: Image element teleports to new place after clicking button.
-Tried: I tried adding “transition” property to the images and expected them to go to their new place smoothly

Form element doesn’t execute submit after button deletion

When button is clicked, click events bubble up to form and execute the proper callbacks. However, after the button is deleted, form submit event isn’t triggered. I can’t find exactly why this happens. Is the submit event called somehow after the DOM is updated? I’m not looking for a solution to this, but rather an explanation for the behavior.

HTML:

<form onsubmit="formSubmitCallback()" onclick="formClickCallback()">
  <div onclick="divCallback()">
    <button id="button" onclick="buttonCallback()">
      click me
    </button>
  </div>
</form>

JS:

function buttonCallback() {
  console.log("button")
  document.getElementById("button").remove()
}

function divCallback() {
  console.log("div")
}

function formClickCallback() {
console.log("form click")
}

function formSubmitCallback() {
  console.log("form submit")
}

Result:

"button"
"div"
"form click"

How to get my timer to start at the stored value in history

document.querySelector('.js-start').addEventListener('click',() =>clickStart());

let n = JSON.parse(localStorage.getItem('history')) || 0;
document.querySelector('.js-timer'). innerHTML = n
let nUnround = 0;
let id;
function clickStart(){
    if(document.querySelector('.js-start').innerHTML == 'Start'){
        document.querySelector('.js-start').innerHTML = 'Stop';
        id = setInterval(()=> {

            nUnround += .01
            n = nUnround.toFixed(2);
            localStorage.setItem('history', JSON.stringify(n));
            document.querySelector('.js-timer').innerHTML = `${n}`
        },10)
    }
    else if(document.querySelector('.js-start').innerHTML == 'Stop'){
        document.querySelector('.js-start').innerHTML = 'Start';
         clearInterval(id);
        
    }
}

document.querySelector('.js-reset').addEventListener('click', () => {
    n = 0;
    nUnround = 0;
    localStorage.removeItem('history')
    document.querySelector('.js-timer').innerHTML = `0.00`
});

im trying to get my timer to start at the data i retrieve at the start stored as history but it just resets my score back to zero once i press start

i tried setting n = parseFloat(localStorage.getItem(‘history’) and then setting nUnround to that but it did not work,

aggrid use column filters as search in treedata

I want to use filters in my columns in a grid with 2 levels of treedata. If the filter is for a column in the child level, then i would like the following to happen –

  1. Any child cell that meets the filter background color changes.
  2. Any siblings are not filtered.
  3. Any parents that do not have children that meet the filtered are no longer in the grid.

I am using Javascript. Any advice on how to accomplish this? I have included a picture based on another grid control I have been using. I would like to switch to aggrid.

In the picture below you can see I have searched on 2 columns in the child rows. They are highlighted with the parent. All sibling rows are in the grid. I had to hand code the search. Is this possible to do with the filters in aggrid. thanks.

What I want to accomplish:

How to structure multidimensional mixted object in mongoose?

Have a single object with a dynamic structure, like as a DOM:

[
    { name: '1.0' }
    {
        name: '2.0',
        childs: [
            {
                name: '2.1',
                childs: [
                   ...
                ]
            }
        ]
    },
]

I would like to create a model that only allows child objects that have the same structure. I have tried to create separate parent child type structures:

mongoose.model('obj', mongoose.Schema({
    title: { type: String },
    parent: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'obj'
    }
}));

Have two problems with this option:

  • The structure would depend on many other types of objects, about 5 or 6 and each one nested.
  • When creating a mass insertion with model.insertMany([ ... ]) by depending on each other, I would need to invent static ids to reference them unless I insert them one by one and then search for them according to each id, this is very tedious since I must create migrations with hundreds of static items.

It would be much easier to take a multidimensional object with multiple children and save it in a single Mongodb document, even selecting the document would be much easier, but I don’t know how I could maintain the structure within the model since being of mixed content type it could be allow parameters that do not match, for example, child could be text and fail instead of being an array, you would have to validate each variable in javascript code one by one recursively.

I try define a recursive model, but I don’t know how to do recursion in mongoose:

mongoose.model('obj', mongoose.Schema({
    title: { type: String },
    childs: [{
        type: mongoose.Schema, // How to put the same schema?
        // What do i put here?
    }]
}));

Can I define this nested structure in mongoose?

React useState not automatically re-rendering to reflect an updated object in my database

I’m working on my first React project where I’m implementing a shopping cart feature. When a user clicks on a button to increase the quantity of an item in their cart, I update the quantity in the MongoDB database through my backend route (addCart). After updating the quantity in the database, I want to re-render the component to reflect the changes in the total price, but the state isn’t updating accordingly.

  • I have a cartItems state that holds multiple objects representing items in the user’s cart.
  • When the user clicks the button to increase the quantity (handleAddCounter function), I call quantityUpdater to update the quantity in the database.
  • After updating the quantity in the database, I update the cartItems state and call calculateTotalPrice to update the total price.
  • However, the total price doesn’t reflect the updated quantity until I refresh the page.
    I suspect that the issue lies in how I’m updating the state after the database change. Could someone please guide me on how to correctly update the state and trigger a re-render after updating the database?
//My states and their initial values
const [cartItems, setCartItems] = useState([]); //This currently holds multiple objects
const [totalPrice, setTotalPrice] = useState(0);
//Button that adds to the quantity
<button className='inline-flex items-center justify-center font-medium text-xl text-slate-600 mx-2 h-8 w-8 hover:border hover:bg-gray-300 hover:border-gray-300 hover:rounded-full' onClick={() => {handleAddCounter(item.productId, item.productImage, item.productTitle, item.productPrice, item.productSize, item.quantity)}}>+</button>
//Trying to run fetch data and calculate price on each re-render
useEffect(() => {
        fetchCartData();
        //Running calculate total price to get the new value from the state
        calculateTotalPrice();
    }, [cartItems]);

//Updating the quantity
const handleAddCounter = (prodId, img, title, price, size, quantity) => {
const updatedQuantity = quantity + 1;
quantityUpdater(prodId, img, title, price, size, quantity, updatedQuantity);}
//Sending that to the back end
const quantityUpdater = async (prodId, img, title, price, size, quantity, updatedQuantity) => {
try {
const token = localStorage.getItem('token');
console.log('Getting token from singleProduct: ', token);
const showUserName = username;console.log('Seeing if username has a value: ', showUserName);
const showProductId = prodId;console.log('Seeing if product id has a value: ', showProductId);
        if (!token) {
            throw new Error('Authentication token not found');
        }

        const response = await fetch('http://localhost:3001/auth/user/addCart', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`,

            },
            body: JSON.stringify({
                productId: prodId,
                img: img,
                title: title,
                price: price,
                size: size,
                quantity: updatedQuantity,
                username,
            }),
        });

        if (!response.ok) {
            throw new Error(`Network response error: ${response.statusText}`);
        }

        // Update cartItems state with the new data (forcing state to re-render because it doesn't recognize an updated object)
        // React only recognizes a state change when the state is se t with a new object
        const updatedCartItems = cartItems.map(item => {
            if (item.productId === prodId && item.productSize === size) {
                // Update quantity for matching product ID and size
                return {
                    ...item,
                    quantity: updatedQuantity
                };
            }
            // Return unchanged item for other items
            return item;
        });

        setCartItems(updatedCartItems);
        calculateTotalPrice();
        console.log('Calculate Total price fired!');
    } catch (error) {
        console.error('Error adding to cart: ', error.message);
    }
};

 //Calculating the total price 
const calculateTotalPrice = () => { 
console.log('Calculate total price received and running'); 
// Check if cart is defined and is an array 
if (cartItems && Array.isArray(cartItems)) { 
let addedValue = 0; 
console.log('This is to check the calculated price to see if cartItems is actually printing something worth while: ', cartItems); 
for (let i = 0; i < cartItems.length; i++) { 
// Check if cart[i] is not undefined before accessing its properties 
if (cartItems[i] && cartItems[i].productPrice) { addedValue += cartItems[i].productPrice; } }
setTotalPrice(addedValue);

        console.log('Is total Price updating the price?: ', totalPrice);
    } else {
        setTotalPrice(0);
    }
}

//Back end to create new item or update an existing object 
router.post('/addCart', authenticate, async (req, res) => { 
const { productId, img, title, price, size, quantity, username } = req.body; 
//Extracting product information from 
console.log('Product ID in route:', productId); 
console.log('IMG in route:', img); 
console.log('title in route:', title); 
console.log('Price in route:', price); 
console.log('Size in route:', size); 
console.log('Quantity in route:', quantity); 
console.log('username in route:', username); 
// Extract productId from req.body 
const isProductIdANum = req.body.productId; console.log('Type of productId:', typeof isProductIdANum);
//Price being manipulated below
let newPrice;

// Check if they exist, I don't want to go further if they don't
if (!productId || !img || !title || !price || !size || !quantity || !username) {
    return res.status(400).json({ error: 'Missing required fields' });
}

try {
    //Querying the username field in the user collection
    const user = await User.findOne({ username });

    if (!user) {
        return res.status(404).json({ error: 'User not found' });
    }

    //Check for existing cart item
    //The productId being produced from req.body is a string so we converted it back to int
    const existingCartItem = user.cart.find(item => item.productId === parseInt(productId));
    const existingSize = user.cart.find(item => item.productSize === parseInt(size));

    if (existingCartItem && existingSize) {
        //Changing the quantity value instead of adding another object
        console.log('Existing item found!: ', existingCartItem);
        //Storing the original price 
        const originalPrice = existingCartItem.productPrice / existingCartItem.quantity;
        console.log('Original Price: ', originalPrice);

        //updating the quantity
        existingCartItem.quantity = quantity;
        console.log('Quantity: ', quantity);

        //Price Based on Quantity
        newPrice = originalPrice * quantity;
        console.log('New Price: ', newPrice)

        existingCartItem.productPrice = newPrice;
    } else {
        // Adding the product to the cart
        productPrice = price * quantity;
        user.cart.push({ productId, productImage: img, productTitle: title, productPrice: productPrice, productSize: size, quantity: quantity });
    }
    await user.save();

    res.status(201).json({ message: 'Product added successfully to cart' });
} catch (error) {
    console.error('Error adding to cart: ', error.message);
    res.status(500).json({ error: 'Could not add to cart' });
}

});

JavaScript “element is not defined” in Array.prototype.find()

I am building an application in ReactJS that uses tags to organize photos. My data structure is set up in three parts: (1) photos, (2) tags and (3) “imageTags” which are relationships between a photo and a tag. For photos that have id’s 9, 12, and 35 and have tags 4, 5, and 6 respectively, the imageTag object would look like this:

const imageTags = {
  {id: 1, imageId: 9, tagId: 4},
  {id: 2, imageId: 12, tagId: 5},
  {id: 3, imageId: 35, tagId: 6}
} 

The “Tag” component is passed only the imageTag id, from which it should be able to determine the image it is assigned to, and the tag that should be on that image, like this:

// props: imagetagId={7}
const imageId = imageTags.find(element => element.id === props.imageTagId)

This works fine for initial render. However, when a user tries to remove a tag from a photo,* the state of the app changes and suddenly I get the error:

Uncaught TypeError: element is undefined

What I don’t understand is, how can “element” be undefined? My understanding is that it is walking through the imageTags object and checking each “element”, hence why I named the variable that way. I know this is NOT an issue of “imageTags.find(…) is undefined”, it is not that the find method is returning no results. To me the error reads as if element itself is undefined… but how is that possible?

Here is the function that alters imageTags when a user tries to remove a tag:

// remove a specific imageTag from imageTags
const handleRemoveTag = (imageTagId) => {
  for (const [key, value] of Object.entries(imageTags)) {
    if (value.id == imageTagId) {
      delete imageTags[key];
    };
  };
};

*another important detail I have found: this error does NOT occur when removing the LAST tag in the list. Tags can be safely removed one at a time starting from the final one to the first one, but removing a tag from the middle or beginning causes this error. I’m not sure why that would be, but it seems relevant for troubleshooting.