Firebase Question – Uncaught TypeError: firebaseApp.firestore is not a function

import firebase from ‘firebase/compat/app’;
import ‘firebase/compat/auth’;

const firebaseConfig = {
apiKey: “AIzaSyAo_xPpbeKIbY_t90ZlXx-glsgQQnoWW6w”,
authDomain: “clone-6ba21.firebaseapp.com”,
projectId: “clone-6ba21”,
storageBucket: “clone-6ba21.appspot.com”,
messagingSenderId: “936299750326”,
appId: “1:936299750326:web:751ef8cc4679412c919717”,
measurementId: “G-N2154NWV83”,
};

const firebaseApp = firebase.initializeApp(firebaseConfig);

const db = firebaseApp.firestore();
const auth = firebase.auth();

export { db, auth };

Putting all the imports in index file

Hello i’m working on a node/express project and i’m wondering if is’t better to put all the imports of the dependencies in the index file of a controller and then pass them as parameters to the function or each function should have it’s required dependencies
screenshot of controller’s files

import passport from 'passport';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';
import util from 'util';
import httpStatusCodes from '../../utils/httpStatusCodes.js';
import * as login from './login.controller.js';
import logout from './logout.controller.js';
import * as reserPasswordController from './reset-password.controller.js';
import { ErrorHandler } from '../../utils/errorsHandler.js';
import responseHandler from '../../utils/responseHandler.js';
import signupUser from './signup.controller.js';
import addressService from '../../services/address.services.js';
import * as emailVerificationController from './email-verification.controller.js';
import generateCode from '../../utils/codeGenerator.js';
import sendMail from '../../utils/sendEmail.js';
import verifyEmailTemplate from '../../utils/verifyEmailTemplate.js';
import crudHandler from '../../services/crudHandler.js';

const randomBytesAsync = util.promisify(crypto.randomBytes);

const signin = (req, res, next) => {
  const secret = process.env.TOKEN_SECRET;
  login.login({
    req,
    res,
    next,
    passport,
    ErrorHandler,
    httpStatusCodes,
    responseHandler,
    jwt,
    secret,
  });
};

When trying to call a function in JavaScript I get the error: Cannot read properties of undefined (reading ‘target’)

I posted earlier but I’m stuck again. I’m a beginner so excuse my ignorance please and if I explain some things a bit weird. I tried to give as much information as possible though.

Goal: I’ve written a bunch of calculations that all needs to come together and calculate the cost of a solar power system

Expected result: The system cost field needs to get a value based on the existing calculations

Actual results: System Cost shows 0. Also, some of the other values that should feed into the Sytem Cost number is showing 0 as well in console.

Error messages: Cannot read properties of undefined (reading ‘target’)

What I’ve tried: I think it’s a scoping problem because when I moved some of the other calculations into functions with other calculations I get the right values on the console for those values. But when I do that the function that calculates system cost can’t read those values because now they are in other functions (I’ll give example shortly)

I think the variables that are needed are globally declared but that didn’t fix it. I’ve also tried to call the function but then I get this error: Cannot read properties of undefined (reading ‘target’). At the moment I have that with no parameters but I have tried with the parameters that is in the function declaration as well as using the variable I want to get out of the function but got similar errors.

Here’s a section of the html:

Approximate percentage of monthly bill you 
would like to save: 
<input 
       type="text" 
       min="1" 
       max="100" 
       value="0" 
       step="1" 
       onchange="CalcKwhSavings(event)" 
       style="width:400px;"
       id="inputSaveOnBill"
       />
<h2>Required Kwh Savings Per Month <span id="outputKwhSavings"></span></h2>

Here’s the variables and function I’m using to get the result:

let outputKwhSavings = document.getElementById('outputKwhSavings');
let inputSaveOnBill = document.getElementById('inputSaveOnBill');
var reqKwhSavingsPerMonth = 0;

function CalcKwhSavings(event) {
   inputSaveOnBill = event.target.value;
    inputSaveOnBill.innerHTML = inputSaveOnBill ;
    
    reqKwhSavingsPerMonth = Math.round ((inputSaveOnBill * .01)* monthlyBillToKwhConversion);
  
    outputKwhSavings.innerHTML = reqKwhSavingsPerMonth;
    console.log("reqKwhSavingsPerMonth:" + reqKwhSavingsPerMonth);

}

Here’s some other variables that are dependent on the values in the above function (These function are showing 0 in the console which they shouldn’t be doing):

let numberOfPanels = Math.round (reqKwhSavingsPerMonth / kwhPerPanelPerMonth);
console.log("numberOfPanels:" + numberOfPanels);

let sizeOfPanelArray = Math.round (numberOfPanels * panelPeakPower / 1000);
console.log("sizeOfPanelArray:" + sizeOfPanelArray);

And here’s the function that needs the above variables (amongst others) to get to the the system cost result (I’m also not sure whether the below is written correctly to get the values from the radio buttons but I thought I’d start with trying to resolve the scoping problem):

function calcSystemCost(event) {
    let singlePhase = document.getElementById("singlePhase").value;
        let threePhase = document.getElementById("threePhase").value;
    let systemCost = 0;
    let phase = 0;

        if ([phase.singlePhase].checked == true) {
      if (sizeOfPanelArray > 6.5) {systemCost = Math.round ((singlePhaseBaseCost + eightKwSinglePhaseInverter) + (numberOfPanels * panelCost) + (numberOfBatteries * batteryCost))
}
else if (sizeOfPanelArray < 6.5) {
   systemCost = Math.round ((singlePhaseBaseCost + fiveKwSinglePhaseInverter) + (numberOfPanels * panelCost) + (numberOfBatteries * batteryCost))
}
console.log("System cost:" + systemCost); 

        }

        else if ([phase.threePhase].checked == true) {

        systemCost = Math.round ((threePhaseBaseCost + twelveKwThreePhaseInverter) + (numberOfPanels * panelCost) + (numberOfBatteries * batteryCost))
console.log("sytemCost:" + systemCost);
        }
  
  outputSystemCost.innerHTML = systemCost;
  

        }

And here’s the codepen with everything in

Any help would be very much appreciated. I’ve watched so many videos and read on so many places on how to handle scoping but I’m not getting anything to work.

Why does this module return undefined?

I’m writting a code in NodeJs using jimp and qrcode-reader. Those dependencies work well. The issue lies when I export the code into a module. And supposedly, it should return a value. This is an arrow function that returns the URL of the QR Code. However, If I use “console.log”, I can see it works. But when I use the module, it returns undefined. Perhaps I’m missing something real simple.

Here is the code of the module:

const Jimp = require('jimp')
const fs = require('fs')
const QrCode = require('qrcode-reader')

const scanQR = (source) => {
const buffer = fs.readFileSync(source)

   Jimp.read(buffer, (err, image) => {
       try {
           const qr = new QrCode()
           qr.callback = (error, value) => {
               try {
                   console.log(value.result)
                   return value.result
               } catch(error) {
                   console.error(error)
               }
           }
           qr.decode(image.bitmap)
       } catch (error) {
           console.error(error)
       }
   })
}

module.exports = scanQR

Here is the module imported:

const scanQR = require('./utils/scanQR')
const qr_code_screenshot = `${__dirname}/assets/images/qrcode-test.png`
const result = scanQR(qr_code_screenshot)
console.log(result)

Here is the result on console:
Console result

Thanks in advance.

How to keep track of a purchase total based on number of clicks

I am trying to keep track of a running total based on number of clicks on the buttons on the site. There are 8 buttons, all of which should add $123.45 to the total when clicked, as well as alert the total.

Some of my HTML

<article class="dog-card">
  <img src="images/murphy-card.jpg" alt="a brown and white dog with a questioning look on his face" onclick="dogInfo('Murphy', 'Mix', '$123.45')">
  <h3>Murphy</h3>
  <p><strong>Cost to Adopt:</strong> $123.45</p>
  <p>Corrum volorit iandae nimaxim cum restia volor reicid ut et etur sunt arum rendae pla endis re ea erum, qui doluptae</p>
  <p class="adopt" onclick="addFee()">Adopt</p>
</article>

And my JS so far

function addFee() {
  let x = 123.45;
  let total = ('Your total is $' + x);

  alert(total);
}

I know this JS isn’t what I need, but I just wanted to put something in so I could verify the button was working.

Any advice is much appreciated, thanks!

split text string by array of properties

I have a block of text which is supposed to have different types of formatting. The text and the formatting tags are stored in a string and an array respectively. I want to create a data structure that will hold the 2 together. Here is actual working data:

Formatted text:

this text is bold while this is italic and this is bold too.

Text string:

this text is bold while this is italic and this is bold too.

Format tags array:

{
  "bold":[
    [13,16],
    [51,54]
  ],
  "italic":[
    [32,37]
  ]
}

Note that the format tags array contains the start and end of different types of formatted text.

Now the question is: How could I merge these 2 types of information to create one good object holding the two. A generic format that can be converted into HTML and Markdown would be appreciated. I was thinking about:

[
  {text:"this text is ", tags: []}.
  {text: "bold", tags: ["bold"]},
  {text: "while this is ", tags: []},
  {text: "italic", tags: ["italic"]},
  {text: " and this is ", tags: []},
  {text: "bold", tags: ["bold"]},
]

Also note that it is possible for one text slice to have multiple tags.

Webpack doesn’t reload the page entirely like manual refresh when I make a changes in my js file

I’m building a web app and I have an input element with autofocus
Whenever I change something in my app.js webpack automatically refresh the page and apply my changes but that doesn’t bring autofocus to my input element

When I reload the page manually I see my input element get into focus like the behavior I expected but when I keep editing and saving my app.js, I see the element lose it’s focus

Can I make it work in a way that behave like a manual refresh ?

this is my element in the page which has autofocus

<input class="" type="text" value="" autofocus>

this is my webpack config content

'use strict';

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development', // 'production'
    entry: {
        main: path.resolve(__dirname, 'src/app.js')
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].[contenthash].js',
        // assetModuleFilename: '[name][ext]',
        clean: true
    },
    devtool: 'inline-source-map',
    devServer: {
        static: path.resolve(__dirname, 'src'),
        port: 8080, // default 8080
        open: true,
        hot: true
    },
    // loaders
    module: {
        rules: [
            // css
            {
                test: /.css$/, use: ['style-loader', 'css-loader']},
            // images
            {
                test: /.(svg|ico|png|webp|jpg|gif|jpeg)$/, type: 'asset/resource'}
            // js for babel
            // ,{
            //     test: /.js$/,
            //     exclude: /node_modules/,
            //     use: {
            //         loader: 'babel-loader',
            //         options: {
            //             presets: ['@babel/preset-env']
            //         }
            //     }
            // }
        ]
    },
    // plugins
    plugins: [new HtmlWebpackPlugin({
        title: 'DDS Audit',
        filename: 'index.html',
        template: path.resolve(__dirname, 'src/views/temp.html')
    })]
}

How to set value in object constructor?

I have problem with my script.

Why my constructor of this object do not know that value of wynik1 is changing and always return “this.A” instead of changing it?

var wynik1 = (liczba1 / liczba2) * profil;

function potatos(name, moc, square, A, B, C, D, price) {
  this.name = name;
  this.moc = moc;
  this.square = square;
  this.A = A;
  this.B = B;
  this.C = C;
  this.D = D;
  this.price = function() {
    if (wynik1 < 18000) {
      return this.A;
    }
    if (wynik1 < 10000) {
      return this.B;
    }
    if (wynik1 < 5000) {
      return this.C;
    }
    if (wynik1 < 3000) {
      return this.D;
    }
  };
}

const animus = new potatos('nameone', 370, 1.7, 7533, 5670, 4800, 4200);
const anomus = new potatos(' olar', 470, 1.7, 7800, 6900, 5260, 4630);
const atopuso = new potatos('komisuslar', 780, 1.7, 7900, 6080, 5450, 4815);

var prices = (function moc() {
  if (liczba4 == "A") {
    return animus.price(4200, 4000, 3800, 3600);
  }
  if (liczba4 == "B") {
    return anomus.price(4000, 4200, 4600, 5000);
  }
  if (liczba4 == "C") {
    return atopuso.price(4200, 4500, 4800, 5300);
  }
})();

Apply user input changes using jQuery

I’ve been set a task at uni as an introduction to jQuery and cannot for the LIFE of me, figure out how to execute what I need to do…

So the task is:
“Using jQuery allow users to enter a colour then on click of the “Apply” button apply the user entered colour to the box.”

The HTML and CSS code I’m given is below alongwith the JS that I’ve attempted to put together. At the moment, the change triggers when you put the text into the box, and then click back into the box, but I can’t figure out how to make this action occur when using the Apply button.

HTML:

<!-- DO NOT MODIFY --->
<div class="form-container">
  <input type="text" class="colourInput" placeholder="Type colour here">
  <button>Apply</button>
</div>
<div class="box">
</div>

CSS:

/* DO NOT MODIFY */

.form-container {
  margin: 0 auto;
  width: 235px;
  margin-bottom: 20px;
  margin-top: 20px;
}
.box {
  height: 200px;
  width: 200px;
  margin: 0 auto;
  background-color: #000;
}

My current JS:

// Using jQuery allow users to enter a colour then on click of the "Apply" button apply the user entered colour to the box.

$('.colourInput').on('click', function(){
$('.box').css("background-color", $(this).val());
});

Really cannot get my head around this, so any help would be amazing! The task was set in Codepen, which is why the “document ready” element was not used.

Link to task CodePen
Thanks

How conditional comparing string with boolean really works in JS?

I am curious about how the conditional comparing works in js regarding the boolean and string. For example:

console.log("true" > false)
//OUTPUT: false

console.log("true" >= false)
//OUTPUT: false

Assuming if it’s false in the first lines of code, what happens in the second line of code? Why does it not returning true? I would be appreciated if any of you guys give me the general rule for these comparisons. I can understand equality, but not with those conditional comparison when comparing string and boolean.

document.querySelector(‘input[name=nameOfradio]:checked’).value; but radio not checked

I’m trying to get the value from a radio with :
document.querySelector(‘input[name=nameOfradio]:checked’).value;

But I want to get a value even if none of the radios are checked.

For exemple in this snippet, if neither of the radios are checked i’d like to change the text for “you didn’t select a number and you didn’t select a letter”

function myFunction(){
  
  let var1 = document.querySelector("input[name=radioa]:checked").value;
    let var2 = document.querySelector("input[name=radiob]:checked").value;

    document.getElementById("change").innerHTML = var1+" and "+var2;
}
<div>
  <p>Wich number will you choose ?</p>
  <input id="one" name="radioa" type="radio" value="Number 1"/>
  <label for="one">The N° 1</label>
  <input id="two" name="radioa" type="radio" value="Number 2"/>
  <label for="two">The N° 2</label>
</div>
<div>
<p>Wich letter will you choose ?</p>
  <input id="a" name="radiob" type="radio" value="Letter a"/>
  <label for="a">The letter a</label>
  <input id="b" name="radiob" type="radio" value="Letter b"/>
  <label for="b">The lettter b</label>
</div>
<div>
<button id="z" onclick="myFunction();">button</button>
</div>
<div>You have chosen :</div>
<div id="change"></div>