How do I fix with Next JS and Antd Design Styling not working?

Whenever I try to style Antd Design component ( Layout, Sider and so on ) but it doesn’t seems to be working. Therefore there won’t be any changes on them. But it works fine on other HTML elements like div, h1, p tags.

Here’s my code:

.sidbar{
    flex: 1;
    background-color: red;
    border-right: 0.5px solid rgb(218, 217, 217);
    min-height: 100vh;
    background-color: white;  
}
import styles from "../styles/Sidebar.module.scss";
import React from "react";
import { Layout, Menu } from "antd";
const { Header, Content, Footer, Sider } = Layout;
import {
  HomeOutlined,
  DashboardOutlined,
  TeamOutlined,
} from "@ant-design/icons";
import Link from "next/link";

const Sidebar = () => {
  return (
    <div>
      <Layout className={styles.sidebar}>
        <Header>header</Header>
        <Layout>
          <Sider>left sidebar</Sider>
          <Content>main content</Content>
          <Sider>right sidebar</Sider>
        </Layout>
        <Footer>footer</Footer>
      </Layout>
    </div>
  );
};

export default Sidebar;

Why is focus-visible applied on page load

If I understand correctly, focus-visible is only applied to an element if it is focused because of a keyboard interaction. However, in the following example, if I programmatically focus the element on page load, the focus ring shows up as well.

https://codesandbox.io/s/focus-on-page-load-jy595z?file=/src/index.js

Is this behavior expected? If so, what’s the best way to disable it while keeping the page accessible (stop showing the focus ring on page load but still able to highlight the focused element with keyboard navigation)

Changing video-background based on weather description using React

I am trying to have it so that the video background of my weather app will change based on the weather condition using React.
This is my App.js

import React, { useState } from "react";
import axios from 'axios';
import Background from './Background';


function App() {
  

  const [location,setLocation] = useState('')
  const [data,setData] = useState({})
 
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=681134f49a40ffa25a43fd6bd3a2f480`

  const searchLocation = (event) => {
      if(event.key === 'Enter') {
        axios.get(apiUrl + "&units=metric")
          .then((response) => {
          setData(response.data)
          console.log(response.data)
        })
      }
  }

  return (
    <div className="app">

      <div className="search">
        <input 
        value={location}
        onChange={event => setLocation(event.target.value)}
        onKeyPress = {searchLocation}
        placeholder='Enter Location'
        type="text"/>
      </div>

      <div className="container">

        <div>
          <Background weatherDescription = {data.weather ? <p>{data.weather[0].main}</p> : null} />
        </div>   

        <div className="top">
          <div className="location">
            <p>{data.name}</p>
          </div>
          <div className="temp">
            {data.main ? <h1>{data.main.temp.toFixed()}°C</h1> : null}
          </div>
          <div className="description">
            {data.weather ? <p>{data.weather[0].main}</p> : null}
          </div>
        </div>

        {data.name != undefined && 
          <div className="bottom">
            <div className="feels">
              {data.main ? <p className="bold">{data.main.feels_like.toFixed()}°C</p> : null}
              <p>Feels Like</p>
            </div>
            <div className="humidity">
              {data.main ? <p className="bold">{data.main.humidity}%</p> : null} 
              <p>Humidity</p>
              <p></p>
            </div>
            <div className="wind">
              {data.wind ? <p className="bold">{data.wind.speed.toFixed()} KPH</p> : null} 
              <p>Wind Speed</p>
            </div>
          </div>
        }

      </div>

    </div>
  );
}

export default App;

An this is my video background component, Background.js

import React from "react";
import video1 from "./Videos/Clouds.mp4";
import video2 from "./Videos/Thunderstorm.mp4";

function Background(props) {


    const videos = [
        {
            name:"Clouds",
            background: video1

        },
        {
            name:"Thunderstorm",
            background: video2
        }
    ]


    return (
        <div>

            <video id="background" autoPlay loop muted>
                <source src = {props.weatherDescription === videos[0].name ? null : videos[0].background} type="video/mp4"/> 
            </video>

            
        </div>
    )
}



export default Background;

I have passed in the ‘weatherDescription’ props in App.js so that I can use it in Background.js. I have already tried If-else and I have tried ternary operator as well but it is not changing based on the description. Due to how the weatherAPI works a ternary operator has to be used to access the weather description.

I am very new to React and I am pretty sure that I am passing in the props correctly. Would you be able to see what I am doing wrong? I have tried console.logging stuff but I haven’t had much luck.

Prevent multiple fast clicks from triggering API

For my project a instagram-clone, I have a like and dislike button. If there are no likes or dislikes from the current logged in user, both will show black. If I like the post the like will show blue, and then when I click dislike, it switches from like to dislike, from blue to red. And clicking which ever is activated like/dislike it will unlike or undislike. The problem that arises, is that when you click super fast it somehow breaks through and adds multiple likes, when each user should only be able to add one like or one dislike.

enter image description here
enter image description here
enter image description here
enter image description here
enter image description here
enter image description here

How to load a 3D model with Collada using NASA Web World Wind?

I’ve been working with NASA’s World Wind library and I am currently trying to display a 3D model of a tree on top of the globe. I am following this example: https://github.com/NASAWorldWind/WebWorldWind/blob/develop/examples/Collada.js, but it isn’t working, aka nothing is displaying.

I’ve downloaded the tree model from this site:https://clara.io/view/240def5d-89b3-42f1-a59c-d4e589c068a0 and added the file inside my Collada folder as shown in the image below.
Files I’ve used

I’ve copied the directory path and am using it inside the init method. That being said it isn’t working and there isn’t a lot of information online about this library. When I try to use the callback function in load, it says that it can’t set properties to null. Does anyone know what’s wrong?

Here is the documentation for the library: https://worldwind.arc.nasa.gov/autodocs/WebWorldWind/

Code below:

var wwd = new WorldWind.WorldWindow("canvasOne");
wwd.addLayer(new WorldWind.BMNGOneImageLayer());
wwd.addLayer(new WorldWind.BMNGLandsatLayer());

var modelLayer = new WorldWind.RenderableLayer("Tree");
wwd.addLayer(modelLayer);

var position = new WorldWind.Position(45, -100, 1000e3);
var colladaLoader = new WorldWind.ColladaLoader(position);

colladaLoader.init({dirPath: './Test Folder/Collada/'});
colladaLoader.load('tree.dae', function(model) {
    model.scale = 5000;
    modelLayer.addRenderable(model);
    
});

TypeError: undefined is not an object (evaluating ‘MQTTConnection.prototype’)

The OnMQTTConnect as the others OnMQTT functions are prototypes. But the debugging throws a Typerror undefined despite that they are defined at the App.js. I have tried changing the position of the prototype declaration, but didn’t work neither changing the order of the imports. Someone knows why could it due to?.

MQTTConnection.js :

import init from 'react_native_mqtt';
import uuid from 'react-native-uuid';
import {AsyncStorage} from "react-native";


init({
    size: 10000,
    storageBackend: AsyncStorage,
    defaultExpires: 1000 * 3600 * 24,
    enableCache: true,
    sync: {},
});

const defaultConnectOptions = {
    reconnect: false,
    cleanSession: true,
    mqttVersion: 3,
    keepAliveInterval: 60,
    timeout: 60,
    userName: '',
    password: ''


}

export default class MQTTConnection {
    constructor() {
        this.mqtt = null;
        this.QOS = 0;
        this.RETAIN = true;
    }

    connect(host, port, options = null) {
        if (options) {
            this.QOS = options.qos;
            this.RETAIN = options.retain;
        }

        let currentTime = +new Date();
        let clientID = currentTime + uuid.v1();
        clientID = clientID.slice(0, 23);
        console.log('clientID: ', clientID)

        this.mqtt = new Paho.MQTT.Client(host, port, clientID);
        this.mqtt.onConnectionLost = (res) => {
            this.onMQTTLost;
        };
        this.mqtt.onMessageArrived = (message) => {
            this.onMQTTMessageArrived(message);
        };
        this.mqtt.onMessageDelivered = (message) => {
            this.onMQTTMessageDelivered(message);
        };

        const connectOptions = options ? options : defaultConnectOptions;

        this.mqtt.connect({
            onSuccess: this.onMQTTSuccess,
            onFailure: this.onMQTTFailure,
            ...connectOptions
        });
    }

    onMQTTSuccess = () => {
        this.onMQTTConnect()
    }

    onMQTTFailure = () => {
        this.onMQTTLost()
    }

    subscribeChannel(channel) {
        console.log('MQTTConnection subscribeChannel: ', channel)
        if (!this.mqtt || !this.mqtt.isConnected()) {
            return;
        }
        this.mqtt.subscribe(channel, this.QOS);
    }

    unsubscribeChannel(channel) {
        console.log('MQTTConnection unsubscribeChannel: ', channel)
        if (!this.mqtt || !this.mqtt.isConnected()) {
            return;
        }
        this.mqtt.unsubscribe(channel);
    }

    send(channel = null, payload) {
        console.log('MQTTConnection send: ')
        if (!this.mqtt || !this.mqtt.isConnected()) {
            return;
        }

        if (!channel || !payload) {
            return false;
        }
        console.log(`MQTTConnection send publish channel: ${channel}, payload: ${payload} qos: ${this.QOS} retained: ${this.RETAIN}`)
        this.mqtt.publish(channel, payload, this.QOS, this.RETAIN);
    }

    close() {
        this.mqtt && this.mqtt.disconnect();
        this.mqtt = null;
    }

}

MQTTConnection.prototype.onMQTTConnect = null
MQTTConnection.prototype.onMQTTLost = null
MQTTConnection.prototype.onMQTTMessageArrived = null
MQTTConnection.prototype.onMQTTMessageDelivered = null

App.js

import MQTTConnection from './src/MQTTConnection'
import React, {useEffect} from 'react'
import {View, StyleSheet, Text, Button} from 'react-native'
import { Buffer } from 'buffer';
global.Buffer = Buffer; 

export default function App() {

  useEffect(() => {
    this.mqttConnect = new MQTTConnection()
    this.mqttConnect.onMQTTConnect = this.onMQTTConnect
    this.mqttConnect.onMQTTLost = this.onMQTTLost
    this.mqttConnect.onMQTTMessageArrived = this.onMQTTMessageArrived
    this.mqttConnect.onMQTTMessageDelivered = this.onMQTTMessageDelivered

    this.mqttConnect.connect('4924d328ffbe4e649e261db3563eed0a.s2.eu.hivemq.cloud', 8884)

    onMQTTConnect = () => {
        console.log('App onMQTTConnect')
        this.mqttConnect.subscribeChannel('hanth2')
    }

    onMQTTLost = () => {
        console.log('App onMQTTLost')
    }

    onMQTTMessageArrived = (message) => {
        console.log('App onMQTTMessageArrived: ', message);
        console.log('App onMQTTMessageArrived payloadString: ', message.payloadString);
    }

    onMQTTMessageDelivered = (message) => {
        console.log('App onMQTTMessageDelivered: ', message);
    }

    return () => {
      this.mqttConnect.close()
    }

  }, [])

  return (
    <View style={styles.container}>
      <Text>react_native_mqtt</Text>
      <Button
        title="Press me"
        onPress={() => this.mqttConnect.send('hanth2', "message send to channel hanth2 again")}
      />
    </View>
  )

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  }
})


Login Page Code is not working for login page

So I am writing a PHP/Mysqli Login Code for the login page. The code seems like it doesn’t work because when I submit the login form, it just loads and reloads the page without any response. It is as though the code isn’t working. Maybe something is wrong somewhere. Please help me out, friends.

Below is my Login Code

<?php 

    include 'templates/db.inc.php';
    
    // If the user is not logged in redirect to the login page...
    if (isset($_SESSION['loggedin'])) {
        header('Location: clients/dashboard.php');
        exit();
    }

    if (isset($_POST['auth_email'], $_POST['auth_passkey'])) {
        
        // Prepare our SQL, preparing the SQL statement will prevent SQL injection.
        if ($stmt = $dbconn->prepare('SELECT clients_id, clients_password, $clients_email_activation_code FROM `kbt_clients_tbl` WHERE clients_email = ?')) {
            // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
            $stmt->bind_param('s', $_POST['auth_email']);
            $stmt->execute();
            // Store the result so we can check if the account exists in the database.
            $stmt->store_result();

            if ($stmt->num_rows === 1) {
                $stmt->bind_result($clients_id, $clients_password, $clients_email_activation_code);
                $stmt->fetch();
                
                if (password_verify($_POST['auth_passkey'], $clients_password)) {
                    
                    if ($clients_email_activation_code === 'Activated') {
                        // Verification success! User has logged-in!
                        // Create sessions, so we know the user is logged in, they basically act like cookies but remember the data on the server.
                        session_regenerate_id();
                        $_SESSION['loggedin'] = true;
                        $_SESSION['client_email'] = $_POST['auth_email'];
                        $_SESSION['client_id'] = $clients_id;
                        
                        header('Location: clients/dashboard.php');
                        exit();
                    }else{
                        //Email not verified - Account not Activated
                        header('Location: login.php?s=na');
                        exit();
                    }
                } else {
                    // Incorrect password
                    header('Location: login.php?s=ie');
                    exit();
                }
            } else {
                // Incorrect Email Address
                header('Location: login.php?s=ie');
                exit();
            }

            $dbconn->close();
        }
    }
?>

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
    <!-- Standard Meta -->
    <meta charset="utf-8">
    <meta name="description" content="<?php echo $siteOptions['site_description']; ?>">
    <meta name="author" content="<?php echo $siteOptions['site_name']; ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#313131" />
    <!-- Site Properties -->
    <title>Login into your Account Area - <?php echo $siteOptions['system_name']; ?></title>
    <!-- Stylesheet -->
    <link rel="stylesheet" href="css/vendors/uikit.min.css">
    <link rel="stylesheet" href="css/style.css">
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://www.google.com/recaptcha/api.js"></script>
    <script>
        function onSubmit(token) {
            document.getElementById("login-form").submit();
        }
    </script>
</head>

<body>
    <!-- preloader begin -->
    <div class="in-loader">
        <div></div>
        <div></div>
        <div></div>
    </div>
    <!-- preloader end -->
    <main>
        <!-- section content begin -->
        <div class="uk-section uk-padding-remove-vertical">
            <div class="uk-container uk-container-expand">
                <div class="uk-grid" data-uk-height-viewport="expand: true">
                    <div class="uk-width-3-5@m uk-background-cover uk-background-center-right uk-visible@m uk-box-shadow-xlarge" style="background-image: url(img/in-signin-image.jpg);">
                    </div>
                    <div class="uk-width-expand@m uk-flex uk-flex-middle">
                        <div class="uk-grid uk-flex-center">
                            <div class="uk-width-3-5@m">
                                <?php if (isset($_GET['s']) && $_GET['s'] === 'ie') : ?>
                                <div class="alert alert-danger alert-dismissible">
                                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                                    <strong>Oops...</strong> Invalid Email Address or Password. Try again.
                                </div>
                                <?php endif; ?>
                                <?php if (isset($_GET['s']) && $_GET['s'] === 'na') : ?>
                                <div class="alert alert-danger alert-dismissible">
                                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                                    <strong>Account not Activated!...</strong> Verify your email address to activate your account.
                                </div>
                                <?php endif; ?>
                                <div class="in-padding-horizontal@s">
                                    <!-- module logo begin -->
                                    <a class="uk-logo" href="index.php">
                                        <img class="uk-margin-small-right in-offset-top-10" src="img/in-lazy.gif" data-src="https://www.indonez.com/html-demo/Wave/img/in-logo-2.svg" alt="wave" width="134" height="23" data-uk-img>
                                    </a>
                                    <!-- module logo begin -->
                                    <p class="uk-text-lead uk-margin-top uk-margin-remove-bottom">Log into your account</p>
                                    <p class="uk-text-small uk-margin-remove-top uk-margin-medium-bottom">Don't have an account? <a href="register/">Register here</a></p>
                                    <!-- login form begin -->
                                    <form action="" method="POST" class="uk-grid uk-form" id="login-form">
                                        <div class="uk-margin-small uk-width-1-1 uk-inline">
                                            <span class="uk-form-icon uk-form-icon-flip fas fa-user fa-sm"></span>
                                            <input class="uk-input uk-border-rounded" id="auth_email" type="email" placeholder="Email Address" name="auth_email" required>
                                        </div>
                                        <div class="uk-margin-small uk-width-1-1 uk-inline">
                                            <span class="uk-form-icon uk-form-icon-flip fas fa-lock fa-sm"></span>
                                            <input class="uk-input uk-border-rounded" id="auth_passkey" type="password" placeholder="Password" name="auth_passkey" required>
                                        </div>
                                        <div class="uk-margin-small uk-width-auto uk-text-small">
                                            <label><input class="uk-checkbox uk-border-rounded" type="checkbox" name="remember_me" id="remember_me"> Remember me</label>
                                        </div>
                                        <div class="uk-margin-small uk-width-expand uk-text-small">
                                            <label class="uk-align-right"><a class="uk-link-reset" href="forgot-password.php">Forgot password?</a></label>
                                        </div>
                                        <div class="uk-margin-small uk-width-1-1">
                                            <button type="submit" class="uk-button uk-width-1-1 uk-button-primary uk-border-rounded uk-float-left g-recaptcha" name="login_btn" id="login_btn" data-sitekey="6LclA9IfAAAAAAgzYssqUoemSaE1Tge2ohV31ni1" data-callback='onSubmit' data-action='submit'>Login into Account</button>
                                        </div>
                                    </form>
                                    <!-- login form end -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- section content end -->
    </main>
    <!-- Javascript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="js/vendors/uikit.min.js"></script>
    <script src="js/vendors/indonez.min.js"></script>
</body>

</html>

    include 'templates/db.inc.php';
    
    // If the user is not logged in redirect to the login page...
    if (isset($_SESSION['loggedin'])) {
        header('Location: clients/dashboard.php');
        exit();
    }

    if (isset($_POST['auth_email'], $_POST['auth_passkey'])) {
        
        // Prepare our SQL, preparing the SQL statement will prevent SQL injection.
        if ($stmt = $dbconn->prepare('SELECT clients_id, clients_password, $clients_email_activation_code FROM `kbt_clients_tbl` WHERE clients_email = ?')) {
            // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
            $stmt->bind_param('s', $_POST['auth_email']);
            $stmt->execute();
            // Store the result so we can check if the account exists in the database.
            $stmt->store_result();

            if ($stmt->num_rows === 1) {
                $stmt->bind_result($clients_id, $clients_password, $clients_email_activation_code);
                $stmt->fetch();
                
                if (password_verify($_POST['auth_passkey'], $clients_password)) {
                    
                    if ($clients_email_activation_code === 'Activated') {
                        // Verification success! User has logged-in!
                        // Create sessions, so we know the user is logged in, they basically act like cookies but remember the data on the server.
                        session_regenerate_id();
                        $_SESSION['loggedin'] = true;
                        $_SESSION['client_email'] = $_POST['auth_email'];
                        $_SESSION['client_id'] = $clients_id;
                        
                        header('Location: clients/dashboard.php');
                        exit();
                    }else{
                        //Email not verified - Account not Activated
                        header('Location: login.php?s=na');
                        exit();
                    }
                } else {
                    // Incorrect password
                    header('Location: login.php?s=ie');
                    exit();
                }
            } else {
                // Incorrect Email Address
                header('Location: login.php?s=ie');
                exit();
            }

            $dbconn->close();
        }
    }
?>```

The **session_start()** declaration is in the "**DB.INC.PHP**" file that I included at the beginning of the page

What input type should I use for a code which combines text and numbers? although how would you declare in TypeScript to avoid errors?

I’m using VueJs (coming from React so I’m new), and I have this input wich contains a code => combinations of vowells and numbers. I’m having 2 problems, first of all I’m not sure wich be the correct type for the input, and, in second instance my var defined as number | string is throwing error.
I know it might be a kinda stupid problem but I’m new with Vue&TypeScript so it would be really helpfull if you can tell me the correct way to do it.
Here’s the code:

    <input 
      type="text"
      placeholder="enter a code using only vowels and numbers"
      required
      maxlength="15"
      minlength="7"
      v-model="codeValue"
      @blur="handleFocus"
      
       />
    <span v-if="focused">You should only enter vowels and numbers.</span>
    </form>
</template>

<script lang="ts" >
import {defineComponent} from 'vue'

export default defineComponent({
  name: 'InputValidations',
  data() {
    return {
      emailValue: '' as string, 
      selectedNumber:0 as number,
      codeValue: '' as string | number, 
      focused: false as boolean
    }

The error says: Argument of type ‘string | number’ is not assignable to parameter of type ‘string | null | undefined’.
Type ‘number’ is not assignable to type ‘string’.VueDX/TS(2345)

Remove last character of a string inside an array. JavaScript

I’m struggling to remove the last character of a string in a given position of the array. To make it easy and for my project purpose, I want to remove the last character of the first array element position [0]. I’ve tried with splice and others but it’s not working. Any help?
Here is a simple test code:

test = [‘80010′,’80030′,’80050’];

// Expected result

Console.log(test);
//[‘8001′,’80030′,’80050’]

Moment Js recur every nth month on first Sunday

I’m trying to generate recurrence for every 2 months on the first Sunday

I have tried this code so far but not getting the expected output

let c = moment('05-01-2022', 'MM-DD-YYYY').recur().every(1).daysOfWeek()
                                                  .every(0).weeksOfMonthByDay()

console.log(c.next(5))

// output Console:
[
  Moment<2022-05-02T18:30:00Z>,
  Moment<2022-06-06T18:30:00Z>,
  Moment<2022-07-04T18:30:00Z>,
  Moment<2022-08-01T18:30:00Z>,
  Moment<2022-09-05T18:30:00Z>
] 

Expected Output

[
  Moment<2022-05-02T18:30:00Z>,
  Moment<2022-07-04T18:30:00Z>,
  Moment<2022-09-05T18:30:00Z>,
  Moment<2022-11-07T18:30:00Z>,
  Moment<2023-01-02T18:30:00Z>,
] 

How to post image to my server from Flutter?

I have a small server based on node JS, which communicates with Post Gre SQL database, and server is working on port 5000.
I have route called uploadImage, which uploads an image to the /uploads folder, and uses Bearer token for the authorization.
I have not created this server in React, and don’t know how to use headers correct in http.multiPartRequest to post image.
Code for posting image is here:

const express = require('express');
const router = express.Router();
const pool = require("../database");
const config = require('../config/config');
const expressJwt = require('express-jwt');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const moment = require('moment');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, moment().unix() + '_' + file.originalname);
    }
});

var upload = multer({ storage: storage });

router.route('/uploadImage').post(expressJwt({ secret: config.serverSecretKey }),upload.array("files"), async function (req, res) {
    let retVal = { msg: '', logoUrl: ''};

    try
    {
        if (req.user == null || req.user === undefined) {res.sendStatus(401); return;}
        if (req.user.accountid == null || req.user.accountid === undefined || !req.user.app) {res.sendStatus(401); return;}

        let files = req.files;
        if(files && files.length > 0 ){
            retVal.imageUrl = 'http://localhost:5000/uploads/' + files[0].filename;
        }else {
            retVal.msg = 'Error';
        }

        res.status(200).json(retVal);

    }catch(err){
        console.log({err});
        res.status(401);
    }
});


Is there any benefit in using Map (Object) over objects in React functional components?

I couldn’t find anything about this online but I recently saw some React examples using the Map object to make a simple mapper. This had me wondering if there is some kind of benefit to using the Map object rather than a plain javascript object {} in React functional components.

Are there any noteworthy difference between these two examples?

function myFunctionalComponent() {
    const mapper = {
        foo: 'bar',
        fizz: 'buzz'
    };
}

function myFunctionalComponent() {
    const mapper = new Map([
        ['foo', 'bar',],
        ['fizz', 'buzz']
    ]);
}

Change an audio file frequency into ultra-sonic sound frequency

I’m trying to change my audio file frequency in Javascript and after a lot of struggle I came to one solution, files are given below but I face one limitation here that it can only convert frequency upto “22kHz”.

But I want to convert it to “45kHz”???

“Web Audio API” & “Pizzicato.js” is used in this project. You can use any audio file.

JS file:

import "./styles.css";
import PizzicatoRecorder from "pizzicato-recorder";
import Pizzicato from "pizzicato";
import audio from "../viper.mp3";

PizzicatoRecorder(Pizzicato);

document.addEventListener("click", () => {
  console.log("start");
  Pizzicato.Recorder.start({ mute: false });
  var sound = new Pizzicato.Sound(audio, () => {
    sound.addEffect(delay);
    sound.play();
  });
  var delay = new Pizzicato.Effects.HighPassFilter({
    frequency: 22000,
    peak: 10,
  });

  sound.on("end", function () {
    console.log("end");
    Pizzicato.Recorder.stop("wav", handleAudio);
  });
});


function handleAudio(file, fileType) {
  console.log("Stop");
  let url = URL.createObjectURL(file);
  let hf = document.createElement("a");
  hf.href = url;
  hf.download = "AtLastSuccess." + fileType;
  hf.innerHTML = hf.download;
  hf.click();
}

document.getElementById("app").innerHTML = `
<h1>Frequency Modulation & Download!</h1>
<div>
  Download from
  <a href="https://www.google.com" target="_blank" rel="noopener noreferrer">here</a>.
</div>
`;

html file:

<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app"></div>


    <script src="src/index.js">
    </script>
</body>

</html>

package.json file:

{
  "name": "vanilla",
  "version": "1.0.0",
  "description": "JavaScript example starter project",
  "main": "index.html",
  "scripts": {
    "start": "parcel index.html --open",
    "build": "parcel build index.html"
  },
  "dependencies": {
    "parcel-bundler": "^1.6.1",
    "pizzicato": "0.6.4",
    "pizzicato-recorder": "1.0.3"
  },
  "devDependencies": {
    "@babel/core": "7.2.0"
  },
  "resolutions": {
    "@babel/preset-env": "7.13.8"
  },
  "keywords": [
    "javascript",
    "starter"
  ]
}

useEffect triggering before useState

I have a form that is supposed to register every input (through useState) and constantly check if that is valid (through useEffect), but that console.log always seems to return a outdated check so I think it is first checking if it’s valid and then registering the change.

//SAVING INPUTS
const [values, setValues] = useState({})

function handleChange(e) {
    setValues({ ...values, [e.target.id]: e.target.value })
}

//VALIDATING FORM
const [validation, setValidation] = useState({ emailValid: false })

useEffect(() => {
    handleEmail()
    console.log(validation)
}, [values])

function handleEmail() {
    const { email } = values
    const emailIsValid = /[w]+@[w]+.(com|br|net)/.test(email)

    setValidation({ ...validation, emailValid: emailIsValid })
}

This is the form’s input field:

<div className="inputbox">
    <label htmlFor="email">E-mail</label>
    <input type="text" id="email" required onChange={e => handleChange(e)} />
</div>