Svelte — using ES6 classes, including setters and methods

I’m new to programming in Svelte. I would like to be able to use a method on an ES6 class instance in order to dynamically change values being used on my SPA. (Using svelte-spa-router is not an option, unfortunately.)

To get to the crux of the problem in a simplified from:

This is router.js:

import { writable } from 'svelte/store';

export class Router {
    constructor(pageMap) {
        this.pageMap = pageMap;
        this.current = {};
        this.currentName = '';
    }
    
    get name() {
        return this.currentName;
    }
    
    set name(pageName) {
        this.current = this.pageMap[pageName];
        this.currentName = this.current.name;
    }
    
    navigate(target) {
        this.name = target;
        console.log(this.currentName);
    }
}

and this is App.js:

<script>
    import { Router } from './router';
    const pageMap = {
        start: {
            title: 'start',
            name: 'world!',
        },
        end: {
            title: 'end',
            name: '-- it works!!!',
        },
    }
    const page = new Router(pageMap);
    page.name = 'start';
</script>

<h1>Hello {page.currentName}</h1>
<button on:click={() => page.navigate('end')}>
    change to "it works"
</button>
<button on:click={() => page.navigate('start')}>
    change back to "world!"
</button>

The desired behavior is that the page.currentName value changes with the button presses. The output to the console on button presses is correct: “–it works!!!”, or “world!”. However, the text remains “Hello world!”, so the value change is not traveling outside the class instance. If I had some way of saying “this = this” upon invoking the navigate method, that would probably solve the problem…

I suspect the correct answer involves writable stores, but I haven’t quite been able to figure it out.

onclick not working with firebase query to read data

I got an async function to read/print data from a Firebase collection. It works when I call it in the script as a function. However, as soon as I set it to a button with a click listener, it doesn’t work.
I’ve tried changing it from async to a normal function however it won’t either as it says querySnapshot.forEach((snap) is not a function. I’ve also tried using the arrow notation, didn’t work either, instead of an error it just wouldn’t print anything on the console. I give it a crValue and I want it to return all the documents in the collection where the field cr is equals to crValue:

const crValue = document.getElementById('crValue').value;
        searchCrBtn.onclick = async () => {
        
            const patientQuery = query(collection(db, path), where('cr', '==', `${crValue}`));

            const querySnapshot = await getDocs(patientQuery);
            querySnapshot.forEach((snap) => {
               console.log(`Document ${snap.id} contains ${JSON.stringify(snap.data())}`)
            });

I’m assuming the error is in:

querySnapshot.forEach((snap) => {
               console.log(`Document ${snap.id} contains ${JSON.stringify(snap.data())}`)
            });

Because if I add console.log(patientQuery) and console.log(querySnapshot) before the piece of code above, the both work.

How do I avoid the error when creating a new class

IDE/Editor: Visual Studio Code Version 1.68.1
Extension: Live Server v5.7.5 (for debugging)

I am trying to use plain JavaScript and export a class. While debugging, whenever I create a new class, I get an Error code: STATUS_BREAKPOINT. I have also gotten a Access Violation error.

What am I doing to cause this error? Thank you.
Joe M.

The HTML file:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <title>Test page</title>
        <link rel="shortcut icon" href="#"></link>
        <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
    </head>
    <body>
        <!--script type="module" src="./js/postOffice.js"></script-->
        <div>
            <div>
                This is the test page.
            </div>
        </div>

        <!--script type="module"-->
        <script>
            let temp = import("./js/postOffice.mjs")
                        .then(obj => {
                            obj.postalFactory(window)
                            let letter = postalModule.newLetter('ready');
                            postalModule.postOffice.setName("main post office");
                            console.log(`loaded.`);
                        });
        </script>
    </body>
</html>

The js/postOffice.mjs file:

/**
 * Test
 */
'use strict';
import {default as PostOfficeImp} from './postalService.js';
import {postalMessageFactory, PostalMessage, MESSAGE_TYPE} from './postalMessage.js';
import {Letter, newLetter} from './letter.js'
//import {default as PostOfficeImp} from './postalService.js';

//let postOffice = null;

/**
 * This is the post office module factory function.
 * @param {Window} window_
 * @param {*} other_
 */
export function postalFactory(window_, ...other_) {
    if (!(window_ instanceof Window)) {
        throw new Error(`Error: No window object was passed to the post office factory!`);
    }

    // create postalModule object to contain everything.
    if (!('postalModule' in window_)) {
        window_.postalModule = {};
    }
    window_.postalModule.postalMessageFactory = postalMessageFactory;
    window_.postalModule.Letter = Letter;
    window_.postalModule.newLetter = newLetter;

    if (other_.length > 0 && other_ !== 'undefined' && null !== other_) {
        window_.other = other_;
    }
};

The js/letter.js file:

/**
 * Stack overflow version
 */
 'use strict';

class Letter {
    constructor(messageType_) {
        this.#pojo = {
            messageType: messageType_,
        };
    }

    #pojo;

    /**
     * Get a copy of the data object.
     * @returns Copy of the data
     */
    getPojo() {
        return {
            // Use spread to create a copy of the object
            ...this.#pojo,
        };
    }

    /**
     * This converts the data to a string using the JSON.stringify function.
     * @returns String of the data.
     */
    stringify() {
        return JSON.stringify({
            // Use spread to create a copy of the object
            // Then convert it to a string.
            ...this.#pojo,
        });
    }
};

export function newLetter(messageType_) {
    return new Letter(messageType_);
}

export {Letter};

How to set Custom Headers in xrpl.js

I need to set custom headers for my requests in xrpl.js in order to connect to a Blockchain Service with an API Key. I see that ConnectionOptions has an authorization field, which then is used as

options.headers = { Authorization: `Basic ${base64}` }

in createWebSocket, but my service requires

options.headers = { x-api-key: <My API Key> }

Is there any way to do that?

How to disabled only a input field with checkbox in ReactJS?

I would like to disable the “Date of Completion” field with the checkbox, but the problem is that I create these fields dynamically, so when I try to disable only the field relating to it it disables all other “Date of Completion” fields I would like to disable only the previous field and not all others.

Image

const [checked, setChecked] = useState(false)    
    const [inputList, setInputList] = useState([
        { 
            startDate: "Start Date",            
            completionDate: "Completion Date:",
            inline: true 
        }
    ])
    const handleInputChange = (e, index, val) => {
        const { name, value } = e.target
        setChecked(e.target.checked)    

        const list = [...inputList]

        list[index][name] = val !== undefined ? val : value 
            setInputList(list)
    }
    const handleRemoveClick = (index) => {
        const list = [...inputList]
        list.splice(index, 1)
        setInputList(list)
    }
    const handleAddClick = () => {
        setInputList([
            ...inputList,
            { 
                startDate: "Start Date",            
                completionDate: "Completion Date:",
                inline: true 
            }
        ])
    }
    let embed = {
        embed: {
            fields: inputList
        }
    }    
//Form
{inputList.map((x, i) => {                
    return (
        <>           
            <FormControl>
                <Box>
                    <FormLabel htmlFor='startDate'>Start Date:</FormLabel>                      
                    <Input 
                        name="startDate"
                        onChange={(e) => handleInputChange(e, i)}              
                        type='text' 
                        placeholder='Start Date' 
                    />                                                
                </Box>
                <Box>
                    <FormLabel htmlFor='completionDate'>Completion Date:</FormLabel>                        
                    <Input 
                        name="completionDate"
                        isDisabled={checked ? true : false}
                        onChange={(e) => handleInputChange(e, i)} 
                        type='text' 
                        placeholder='Completion Date' 
                    />                                                
                </Box>                
                <Box pt={{ base: '0', md: '2.7rem'}}>                       
                    <Checkbox  
                        type="checkbox" 
                        name="inline" 
                        checked={x.inline}                                     
                        onChange={(e) => handleInputChange(e, i, e.target.checked)}
                        colorScheme='purple'>
                            <label>Studying</label>
                    </Checkbox>  
                </Box>                                 
            </FormControl>           
            {inputList.length - 1 === i && (
                <Button onClick={handleAddClick}> + New Section </Button> 
                )}
            {inputList.length !== 1 && (
                <Button  onClick={() => handleRemoveClick(i)}>- Remove Section</Button> 
            )}                      
          
        </>
    )
})} 

File size validation JS with Multer

is there a way to implement file size validation in this case?
I am using middleware of Multer. Since the middleware Multer uploads the file, I think I should write a if statement there. Not exactly sure how to implement it.

const express = require('express');
const server = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const {fs} = require('fs');
const { application } = require('express');

const storage = new GridFsStorage({
  url: mongoURI,
  cache: true, // cache
  file: (req, file) => {
    return file.originalname + date.yyyymmdd();
  }
});

const upload = multer({ storage });

server.get("/upload", (req,res) =>{
  res.render('upload');
});

const maxSize = 10 * 1024 * 1024;
 
server.post('/upload', upload.single('file'), (req, res) => {
  res.redirect("/");
});

// how can I validate the size of the file keeping the same format?

Thank you.

Receive javascript error: Cannot set properties of null (setting ‘value’)

I want to inject a date into a datepicker field. I do not understand the error. I am passing a calculated variable ${start_date} and in the logs I can see where that value is generated correctly, but on the execute line I get the failure. I assume this is a syntax error on my part (very new to JS).

Code:

${start_date}= Get Current Date local 6 days %m/%d/%Y

Execute JavaScript document.getElementById(‘${STARTDATEPICKER}’).value=’${start_date}’

Log file information:

JavascriptException: Message: javascript error: Cannot set properties of null (setting ‘value’)

17:29:15.744 TRACE Arguments: [ ‘document.getElementById(‘//[@id=”startDatePicker”]/button’).value=’07/11/2022” ]
17:29:15.744 INFO Executing JavaScript:
document.getElementById(‘//
[@id=”startDatePicker”]/button’).value=’07/11/2022′
Without any arguments.
17:29:15.744 DEBUG POST http://localhost:53404/session/ba6c550f09a90a200a847eceddeaf77d/execute/sync {“script”: “document.getElementById(‘//*[@id=”startDatePicker”]/button’).value=’07/11/2022′”, “args”: []}

function return returns multiple values

the function below logs undefined undefined then the value or undefined undefined then undefined. So it logs 3x. How do I make it only log the 3rd log. or just set x equal to the 3rd log.

import { randomfunction } from randomfunction

const x = randomfunction()

console.log(x)

// logs undefiend undefined then var

Sorting Array of Object by multiple keys

I’m newbie in programming, so i need some help.
I have array of objects. I need to sort it and turn it into an array of objects, which will contain the key city, then an array of objects from the leaders, and an array of coffee shops.

  let arr = [
    {city: 'New York', boss: 'John', name: 'Caffe 1'},
    {city: 'New York', boss: 'John', name: 'Caffe 2'},
    {city: 'New York', boss: 'Ben', name: 'Caffe 3'},
    {city: 'New York', boss: 'Ben', name: 'Caffe 4'},
    {city: 'Washington', boss: 'Lisa', name: 'Caffe 5'},
    {city: 'Washington', boss: 'Lisa', name: 'Caffe 6'},
    {city: 'Washington', boss: 'Kate', name: 'Caffe 7'},
    {city: 'Washington', boss: 'Kate', name: 'Caffe 8'},
    {city: 'Los Angeles', boss: 'Joe', name: 'Caffe 9'}

  ]

I need to get something like this.

    let result =  [
      {city: 'New York', 
      boss:[
        {
          name: 'John', 
          caffes:[
            {name: 'Caffe 1'},
            {name: 'Caffe 2'}
                  ]
                },
        {name: 'Ben', 
          caffes: [
            {name: 'Caffe 3'},
            {name: 'Caffe 4'}
                  ]
                }     
            ]
      },
      {city: 'Washington', 
      boss:[
        {
          name: 'Lisa', 
          caffes:[
            {name: 'Caffe 5'},
            {name: 'Caffe 6'}
                  ]
                },
        {name: 'Kate', 
          caffes: [
            {name: 'Caffe 7'},
            {name: 'Caffe 8'}
                  ]
                }     
            ]
      },
      {city: 'Los Angeles', 
      boss:[
        {
          name: 'Joe', 
          caffes:[
            {name: 'Caffe 9'},
                  ]
                },
            ]
      },
      ]

I trying many ways, but any of them can’t help me.
How can i do this?

NODE_ENV image promotion strategy

So I have a standard node app. I build it with Yarn, and push to different ECR repositories based on the environment I want to deploy to (stage, dev, prod). I also build with NODE_ENV set to developement/production depending on the image’s destination.

This works fine, but the whole concept of image promotion means you should reuse images for each environment instead of having separate repositories, as far as I understand it.

The problem I am not understanding is how this is possible if I am building with two different NODE_ENV’s. As far as I understand, when you build with NODE_ENV = development, various development modules get included.

What is the correct approach here?

Elegant way to combine a removeCartItem and addCartItem function?

I feel like there much be a way to nest these functions together so that the code is more elegantly written but I’m not sure how. Everything works fine as is but it’s two large functions nearly doing the same thing.

const addCartItem = (cartItems, productToModify) => {
  const existingCartItem = cartItems.find((cartItem) => cartItem.id === productToModify.id);

  if (existingCartItem) {
    return cartItems.map((cartItem) =>
      cartItem.id === productToModify.id ? { ...cartItem, quantity: cartItem.quantity + 1 } : cartItem
    );
  }
  return [...cartItems, { ...productToModify, quantity: 1 }];
};

const removeCartItem = (cartItems, productToModify) => {
  const existingCartItem = cartItems.find((cartItem) => cartItem.id === productToModify.id);

  if (existingCartItem) {
    return cartItems.map((cartItem) =>
      cartItem.id === productToModify.id && cartItem.quantity > 0
        ? { ...cartItem, quantity: cartItem.quantity - 1 }
        : cartItem
    );
  }
  return [...cartItems, { ...productToModify, quantity: 1 }];
};

const addItemToCart = (productToModify) => {
    setCartItems(addCartItem(cartItems, productToModify));
  };

  const removeItemFromCart = (productToModify) => {
    setCartItems(removeCartItem(cartItems, productToModify));

Not applying jQuery class to new elements

When the new element button is clicked, it creates an element and adds the .numeric class, but the .numeric class is not applied to the new elements.

$(".numeric").keyup(function() {
  var num = $(this).val().match(/[0-9,]*/g)[0];
  var decimalNum = $(this).val().match(/[.][0-9]*/) || "";
  if (num) {
    var wholeNum = num.match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
    var resultNum = wholeNum + decimalNum;
    $(this).val(resultNum);
  } else {
    $(this).val(num);
  }
});

$(document).ready(function() {
  $("input[type=tel]").focus(function() {
    $(this).attr('placeholder', 'hello world');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>I wonder what HTML is in use here?</div>