Mock antd useBreakpoint hook

I want to test the modal component, but there is an error with defining the cancel button,
it renders only if it’s not mobile.

isMobile is a variable that is a boolean value from hook – useBreakpoint (ant design library hook).

I don’t know how to mock that value, or how to click that button.

Note: if I remove the isMobile check, the button clicks well:)

import React from 'react'
import {Grid, Typography} from 'antd'
import {Button} from '@/components/Button'
import {Modal} from '@/components/Modal'
import translations from './translations'
import {ConfirmationModalProps} from './props'

const {Text} = Typography
const {useBreakpoint} = Grid

export const ConfirmationModal = ({visible, onClose, children}: ConfirmationModalProps) => {
    const screens = useBreakpoint()
    const isMobile = screens.xs

    return (
        <Modal
            title={translations().chargeConfirmation}
            visible={visible}
            onOk={onClose}
            onCancel={onClose}
            footer={[
                !isMobile && (
                    <Button role={'cancel-button'} type={'ghost'} key={'cancel'} onClick={onClose}>
                        { translations().cancel }
                    </Button>
                ),
                <Button type={'primary'} key={'charge'} onClick={onClose}>
                    { translations().confirm }
                </Button>
            ]}
        >
            <Text>{translations().confirmationText(children)}</Text>
        </Modal>
    )
}


describe('ConfirmationModal', () => {
    it('should should the children and close button', async () => {
        const onClose = jest.fn()

        jest.mock('antd/es/grid/hooks/useBreakpoint', () => ({
            xs: false
        }))

        render(<ConfirmationModal onClose={onClose} visible={true}>100</ConfirmationModal>)

        const child = screen.getByText('Are you sure you want to charge 100')

        expect(child).toBeTruthy()

        expect(screen.queryByTestId('cancel')).toBeDefined()

        await waitFor(() => screen.queryByTestId('cancel'))

        fireEvent.click(screen.queryByRole('cancel-button'))

        expect(onClose).toHaveBeenCalledTimes(1)
    })
})

Errors are:

  1. Error: Unable to fire a “click” event – please provide a DOM element.
  2. Unable to find an accessible element with the role “cancel-button”

Depending on queryByRole or getByRole selector.

What is wrong?

How do I get the POST data from a netlify serverless function and what’s the best way to make a database connection on serverles deployment?

Here is the code for my server which works fine. I am trying to achieve this with netlify’s serverless functions which I have pasted further below.

CODE ON STANDARD SERVER-HEROKU

const ratingController = {};
const Rating = require("../models/ratingModel");

ratingController.getAllRatings = async function (req, res) {
  const rating = await Rating.find();

  res.status(200).json({
    status: "success",
    data: rating,
  });
};

ratingController.createOneRating = async function (req, res) {
  console.log(req.body);
  req.body.userIp = req.headers["x-forwarded-for"];


  const rating = await Rating.create(req.body);

  // const rating = new Rating(req.body);
  // await rating.save();

  res.status(200).json({
    status: "success",
    data: {
      rating,
    },
  });
};

PART 1 – GET REQUEST

Here’s my code for the getAllRatings and it works fine

SERVERLESS FUNCTION – NETLIFY

const { MongoClient } = require("mongodb");
require("dotenv").config();

exports.handler = async function getData(event, context) {
  const client = await MongoClient.connect(process.env.DB, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  });
  const db = client.db();
  try {
    const slug = event.queryStringParameters.id;
    const data = await db.collection("collectionName").find({ slug }).toArray();
    client.close();

    return {
      statusCode: 200,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        status: "success",
        data: data,
      }),
    };
  } catch (error) {
    console.log(error);

    return {
      statusCode: 400,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        status: "fail",
        message: error.message,
      }),
    };
  }
};

My first question for the above is

Just because it works may not mean it’s the right way to do it.. I had a few concerns if calling the database each time there’s a call is correct and then placing the code the way I have, if it’s the way it should be. It’s all based on testing and random research. There’s no real method being followed so would appreciate some guidance on a more efficient method to do this.

Normally on a regular server the database connection is done just once.. and here I seem to be doing it every time and I am a bit confused if that’s ok or not..


PART 2 – POST REQUEST

Here’s my code for the POST request createOneRating

SERVERLESS FUNCTION – NETLIFY

const { MongoClient } = require("mongodb");
require("dotenv").config();

exports.handler = async function createRating(event, context) {
  const client = await MongoClient.connect(process.env.DB, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  });
  const db = client.db();
  try {
    console.log(event);
    const rating = await db.collection("ratings").insertOne(event.body);

    client.close();

    return {
      statusCode: 200,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        status: "success",
        data: rating,
      }),
    };
  } catch (error) {
    console.log(error);

    return {
      statusCode: 400,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        status: "fail",
        message: error.message,
      }),
    };
  }
};

This one does not work as it says

{
    "status": "fail",
    "message": "Cannot create property '_id' on string ''"
}

And I guess that’s because event.body is not where the data is.. but I am not sure how to get the POST data in a serverless deployment.

So my second question is

How do I retrieve the data sent by a POST request. As there’s no request parameter I am a bit confused.

Also I’d like to add the IP of the user so other than the POST data I’d also need some help on how to do this

  req.body.userIp = req.headers["x-forwarded-for"];

Map 2 arrays in Javascript

I’m trying to display the content of 2 arrays of contained in an object.
When I map RType.information.Type the content of the array “Type” is displayed.
But nothing happened if I want to display both (Type[] & Price[]).
I tried many things but nothing works..
If someone is able to help lemme know!

JS CODE

 RType.information.Type.map(function (type) {
    RType.information.Price.map(function (price) {
    return m(
        m('td.item-name', m('h4', `CLASS: ${type}`)),
        m('td.item-name', m('h4', `PRICE: ${price}`)),
        ),
      )},
   )},

OBJECT

var RType = {
   information : {
      Type : ["value1", "value2"],
      Price : ["112", "200"],
   },

Request and Cheerio (data scraping packages for JavaScript) prints data but will not add to array

I am trying to store tracking data from the ISS using request and Cheerio for JS, I have got to the point that I can print the data but when trying to store the data in an array it returns undefined.

data.push(tr.text().split(“|”)); //will not put anything in the array data

console.log(tr.text().split(“|”)); //does exactly what i want it to

var data = [];

function sendReq(){

request('https://spotthestation.nasa.gov/sightings/view.cfm?country=Canada&region=Newfoundland&city=Saint_Johns#.YmhIZdPMK5c', 
    function (error, response, html) {

        if (!error && response.statusCode == 200) { 
            var $ = cheerio.load(html); 
            $('table').each(function(){
                
                var tr = $(this).next(); 

                data.push(tr.text().split("|")); //wont put into array data

                //console.log(tr.text().split("|")); //works perfectly fine
                
            }); 
        }

    });
}

sendReq();

console.log(data);

Adding custom context menu to each table row

I had it working when I use document.getElementById(‘row’), but since its an Id it is only applying to the first row. I tried the following code which reads like it should work, but it is not (context menu is not showing up)

  const rowContextMenu = document.querySelector(".row-context-menu");

  Array.from(document.querySelectorAll('row')).forEach(function (el) {
    el.addEventListener("contextmenu", e => {
      e.preventDefault();
      let x = e.offsetX, y = e.offsetY;
      rowContextMenu.style.left = `${x}px`;
      rowContextMenu.style.top = `${y}px`;
      rowContextMenu.style.visibility = "visible";
    });
  });

JsonWebTokenError: jwt malformed when pulling from mySQL

For context, I’m trying to send a one time link to the user’s email as a reset password link that will take them to the reset password page if the jwt token is successfully verified. I followed a tutorial and created a dummy version where user info was stored locally and it worked perfectly. But when I try to implement into my main project which pulls user data from mySQL I keep getting a malformed error, I am checking all the values and everything matches including checking the token on the jwt website to see if it return the correct info which it does so I’m very confused as to what I’ve done wrong. The only thing that changes between the test and main project is where the data is pulled from. Here is my code for this part of the project:

// Create and send link
router.post('/forgot-password', (req, res, next) => {
    var email = req.body.email
    db.query('SELECT * FROM users_test WHERE email = ?', [ email ], (error, results) => {

      if (results.length < 1) {
          res.send('no user')
          return
      }

      const user = results[0]
      const secret = process.env.JWT_SECRET + user.password

      const payload = {
          email: email,
          id: user.id
      }

      const token = jwt.sign(payload, secret)
      const link = `http://localhost:5000/auth/reset-password/${user.id}/${token}`
      console.log(link)
      res.send('sent')
  })
})

// verify token and display password reset page
router.get('/reset-password/:id/:token')= (req, res, next) => { 
    const { id, token } = req.params

    db.query('SELECT * FROM users_test WHERE id = ?', [ id ], (error, results) => {
        if (error) {
            console.log(error)
        }
        const user = results[0]

        const secret = process.env.JWT_SECRET + user.password
        res.json({secret})
        try {
            var payload = jwt.verify(token, secret)
            res.render('reset-password.hbs')
        }
        catch (e) {
            console.log(e)
        }
    })
}

The line the error is point at: var payload = jwt.verify(token, secret)

The error I’m getting:

throw err; // Rethrow non-MySQL errors
      ^
JsonWebTokenError: jwt malformed
    at Object.module.exports [as verify] (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesjsonwebtokenverify.js:63:17)
    at Query.<anonymous> (C:UserswinbaDesktopSecureSoftwareSecure-Software-02controllersauth.js:497:29)
    at Query.<anonymous> (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesmysqllibConnection.js:526:10)
    at Query._callback (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesmysqllibConnection.js:488:16)
    at Query.Sequence.end (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesmysqllibprotocolsequencesSequence.js:83:24)
    at Query._handleFinalResultPacket (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesmysqllibprotocolsequencesQuery.js:149:8)
    at Query.EofPacket (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesmysqllibprotocolsequencesQuery.js:133:8)
    at Protocol._parsePacket (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesmysqllibprotocolProtocol.js:291:23)
    at Parser._parsePacket (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesmysqllibprotocolParser.js:433:10)
    at Parser.write (C:UserswinbaDesktopSecureSoftwareSecure-Software-02node_modulesmysqllibprotocolParser.js:43:10)

Any help or ideas as to where the error is coming from would be appreciated, thank you.

Waiting for an API response before pushing its results to an array [duplicate]

I am building an app using JS and am having troubles understanding this part of my code. I am calling a function called getWaypoint (at the moment just for the start and end location, but eventually for all waypoints), and then creating and returning an object. In my other function, I want to push this object to an array. It seems at the moment I am pushing to the array before the API call is actually completed, resulting in the array being a bunch of ‘undefined’ entries. I talked to some friends, and we think one of the functions has to be async, but we can’t figure out which one or how to implement it properly. Any help is appreciated 🙂

function getWaypoint(cityName, curTime) {
fetch(BASE_URL_GEOCODE + cityName)
    .then((response) => response.json())
    .then((data) => {
        const city = data[0]

        return {
            location: {
                name: city.display_name,
                lat: city.lat,
                lon: city.lon,
            },
            time: findNewTime(curTime),
        }
    })
}

function getWaypoints(startLocation, endLocation, leaveTime) {
    //!will need to call for each waypoint once that functionality is made
    let waypoints = []
    waypoints.push(getWaypoint(startLocation, leaveTime))
    waypoints.push(getWaypoint(endLocation, leaveTime))
    return waypoints
}

CSS Overflow property breaks interactions with elements on page

I don’t know why but, when I add overflow property to my div container, then each element inside this is not interactable, I can’t select text grab images, etc… It behaves like I would use pointer-events: none; but I didn’t, I need a scrollable div, and I can not do this due to that bug. Can someone explain that? Is there my mistake or just a normal bug with chromium-browser. I tried some scrollbar libraries, but it doesn’t work as well.

HackerRank Seperate the Numbers Challenge

Hello everyone;
I have been grappling with 3 cases that are not passing. The difference is so subtle with a digit change. I tried JavaScript notations for very large numbers or scientific notations but of of no avail.
The challenge is linked here.

The different test cases are here.

console.log(separateNumbers(“90071992547409929007199254740993”)) //Gives NO although it should give “yes”

console.log(separateNumbers(“90071992547401929007199254740193”)) //Gives YES when 9 replaced with 1//

My code goes like:

function separateNumbers(s) {
var beautiful = true;
for (let len = 1; len < s.length; len++) { 
    var first = s.substr(0, len);
    var num = s.substr(0, len);
    if (s.length <= len) {
        continue;
    }
    var sNew = ''.concat(first.toString());
    while (sNew.length < s.length) {
        num++;
        sNew = sNew.concat(num.toString());
    }
    if (sNew === s) {
        console.log('YES ' + first);
        beautiful = false;
        continue;
    }
}
if (beautiful) {
    console.log('NO')
}

}

Your helps are very much appreciated. Thanks many

TypeError: Cannot read properties of undefined (reading ‘0’) in NodeJS

I have the TypeError: Cannot read properties of undefined (reading '0') with game_id: result.data[0].game_id, warning in my terminal,

What is weird is that the console.log("result ", result); shows me what I need, but below I can’t access result.data[0].game_id

Code

return promise1.then((result) => {
      console.log("result ", result); <-- ALL GOOD HERE
      if (!result && !result.data && !result.data[0]) return;
      Stream.findOne({}).then((stream) => {
        if (!stream) {
          let streamInfos = new Stream({
            game_id: result.data[0].game_id, <-- ISSUE HERE

Output of the console.log("result ", result);

{"data":
[{
 "id":"45300981596",
 "user_id":"90849777",
 "user_login":"versifixion",
 "user_name":"VersifiXion",
 "game_id":"21779",
 "game_name":"League of Legends",
 "type":"live",
 "title":"VERSI | Stream test calculez pas | !reseaux",
 "viewer_count":1,
 "started_at":"2022-04-26T21:15:38Z",
 "language":"fr",
 "thumbnail_url":"https://static-cdn.jtvnw.net/previews-ttv/live_user_versifixion-{width}x{height}.jpg",
 "tag_ids":["6f655045-9989-4ef7-8f85-1edcec42d648"],
 "is_mature":false
}],
 "pagination":{}}

How can use await/async in vue mounted

I am trying to use mapGetters value in my other computed property. It showing null because the preferences method not executed completed. I want to wait until the store set the getter and setter. I am tried async/await but it’s not working

mounted() {
  this.preferences();
  this.selectedColumnsHeader;
},

methods: {
  async preferences() {
    await this.$store.dispatch('fetchPreferences');
  }
}

JavaScript counter app reset button is not working

const value = document.getElementById("value");
const btnDecrease = document.getElementById("decrease");
const btnReset = document.getElementById("reset");
const btnIncrease = document.getElementById("increase");

let count = 0;

btnDecrease.addEventListener("click", function(e) {
  count--;
  value.innerHTML = count;
});

btnIncrease.addEventListener("click", function(e) {
  count++;
  value.innerHTML = count;
});

btnReset.addEventListener("click", function(e) {
  count = 0;
  value.innerHTML = count;
});
<h1>Counter</h1>
<p id="value">0</p>
<button id="decrease">decrease</button>
<button id="reset">reset</button>
<button id="increase">increase</button>

<!-- javascript -->
<script src="app.js"></script>

Hello everyone I need help understanding why my reset button is not working. The console reads Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’).

The buttons for the increase and decrease work fine, can someone explain to me what I’m doing wrong. Thank you

Electron store data locally without localstorage

Hi, i have a electron app builded using JavaScript.

I need to store some data and still after close the app.

I have find many ways, like json, localstorage.

I can’t edit json using JavaScript only, i need a server, but my app is locally and i have many computers, and i can’t host a localserver for each version of app

I found localstorage but when i change the destination of the app. It delete all data and it’s danger, any problem in the electorn, all data deleted.

So I need to store data in electron locally and read/write data using javascript.

I think with server-side. I can read/write but i need a localhost, and my electorn app just a client-side program like browser.

All my solutions have a problem. I need database read/write client side and not localstorage.

I search on internet along but i can’t found anything.

Sorry for my bad english 🙂

this script, it’s a code that I’m updating from V12 of discord.js to v13

I want to understand the reason for the error, so if it happens again, you can correct it,
the following error appears whenever I use the !whitelist command
(my english is very basic, sorry if there are too many spelling mistakes)

E:DesktopBotcommandswhitelist.js:30
                        const whitelist = new Whitelist({
                                          ^

TypeError: Whitelist is not a constructor

this is the script where cmd reports the error

const Whitelist = require('../classes/whitelist.class')
const config = require('../config/whitelist.config')
const moment = require('moment-timezone')

const usersCooldown = {}
const whitelists = {}


module.exports = {

    
    run: async(client, message, args) => {

    const userItsNotOnCooldown = (userId) => {
        if(Array.isArray(usersCooldown[userId])) {
            if(usersCooldown[userId].length >= config.maximumTries) {
                const firstTryDate = usersCooldown[userId][0].date
                if(Math.floor((Math.abs(new Date() - firstTryDate) / 1000) / 60) <= config.cooldown) {
                    return false
                }
                delete usersCooldown[userId]
            }
        }
        return true
    }
    const userId = message.author.id

    if(typeof whitelists[userId] === 'undefined') {
        if(userItsNotOnCooldown(userId)) {
            const whitelist = new Whitelist({
                message,
                client
            })
            
            whitelist.on('finished', (whitelist) => {
                delete whitelists[userId]
                const data = {
                    whitelist,
                    date: new Date
                }
    
                // console.log(data) // @todo: log data into mongodb.
                
                if(!data.passed) {
    
                    if(typeof usersCooldown[userId] === 'undefined') {
                        usersCooldown[userId] = [data]
                        return
                    }
    
                    usersCooldown[userId].push(data)
                }
            })
            
            whitelists[userId] = whitelist
        } else {
            message.reply(`você atingiu o número máximo de tentativas, tente depois das: **${moment(usersCooldown[userId][0].date).add(config.cooldown, 'minutes').tz('America/Sao_Paulo').format(`DD/MM/YYYY [-] HH:mm`)}**`)
        }
    } else {
        message.reply("você só pode fazer uma whitelist por vez!")
    }
 }
}

I will leave the main if necessary

const Discord = require("discord.js");
const client = new Discord.Client({intents: 32767});
const leaveEvent = require('./events/leave.event');
const config = require('./config/whitelist.config');


client.on("ready", () => {
    console.log(`BOT FUNCIONANDO NORMALMENTE NOME DO BOT : ${client.user.tag}!`)
})

client.on('messageCreate', message => {
    if (message.author.bot) return;
    if (message.channel.type == 'dm') return;
    if (!message.content.toLowerCase().startsWith(config.prefix.toLowerCase())) return;
    if (message.content.startsWith(`<@!${client.user.id}>`) || message.content.startsWith(`<@${client.user.id}>`)) return;

   const args = message.content
       .trim().slice(config.prefix.length)
       .split(/ +/g);
   const command = args.shift().toLowerCase();

   try {
       const commandFile = require(`./commands/${command}.js`)
       commandFile.run(client, message, args);
   } catch (err) {
   console.error('Erro:' + err);
 }
});

client.on("guildMemberRemove", (member) => {
    leaveEvent(member)
});
client.login(config.discordClientId);