Just started learning javascript and pretty confused, how can i clean my code?

I’ve just started learning JavaScript, and i’m finding it very confusing so far. If anyone could help with any advice, many thanks in advance!


function Shoes (shoeName, productCode, quantity, itemValue) {
   this.shoeName = shoeName; 
   this.productCode = productCode; 
   this.quantity = quantity; 
   this.itemValue = itemValue; 
  

should ‘change’ and ‘shoeDescription’ be within the Shoe class, or separate functions? (as they are coming up in console.table)


     this.change = function (name, code, qty, value) {
      this.shoeName = name;
      this.productCode = code;
      this.quantity = qty;
      this.itemValue = value;
    
      console.log(`
      Item:
      ${shoeName} ${productCode} ${quantity} ${itemValue}

      has been edited to:
      ${name} ${code} ${qty} ${value}
      `)
   }
      

   
   this.shoeDescription = function () {
     
    return `
      Shoe: ${this.shoeName} 
      Product Code: ${this.productCode} 
      Qty: ${this.quantity}
      Value: ${this.itemValue}`
   }


}




function shoeSearch(shoes01, shoes02){
    let found = false;
    shoes01.forEach(x => {
        if(x.shoeName == shoes02){
            console.log(`${shoes02} found.`);
            found = true;
        }
    });
 
    if(!found){
        console.log(`${shoes02} not found.`)
    }
 }



function lowestItem(shoes01){
   let low = shoes01[0].itemValue;
   let shoeName = "";
   shoes01.forEach(shoes02 => {
       if (shoes02.itemValue < low){
           low = shoes02.itemValue;
           shoeName = shoes02.shoeName;
       }
   })

   console.log(`${shoeName} is our cheapest item, with value of £${low}`)
}




function highestItem(shoes01){
   let high = shoes01[0].itemValue;
   let shoeName = "";
   shoes01.forEach(shoes02 => {
       if (shoes02.itemValue > high){
           high = shoes02.itemValue;
           shoeName = shoes02.shoeName;
       }
   })

   console.log(`${shoeName} is our most expensive item has the value of £${high} `)
}



let sabat01 = new Shoes("nike", "nk0119", 2, 150);
let sabat02 = new Shoes("adidas", "ad5169", 43, 170);
let sabat03 = new Shoes("sketchers", "sk624", 10, 67);
let sabat04 = new Shoes("puma", "pu738", 20, 93);
let sabat05 = new Shoes("asics", "as823", 13, 50);

let shoeStock = [sabat01, sabat02, sabat03, sabat04, sabat05];



shoeStock.sort(
    (p1, p2) => 
    (p1.shoeName > p2.shoeName) ? 1 : (p1.shoeName < p2.shoeName) ? -1 : 0);


When i run these console.log, i don’t get why highest item doesn’t show
Also, how do i remove the ‘change’ and ‘shoe description’ from console.table

// find "adidas"
console.log(shoeSearch(shoeStock, "adidas"));
// try and find an item that doesnt exist
console.log(shoeSearch(shoeStock, "kicks"));
// find lowest item
console.log(lowestItem(shoeStock));
// find highest item
console.log(highestItem(shoeStock));
// get any item description
console.log(sabat03.shoeDescription());
// edit an item
console.log(sabat01.change("nike", "nk020", 88, 175));
// display product name in in ascending order
console.table (shoeStock)

Missing ordered list and unodered list points when converting html to pdf using jsPDF

I try to convert from html to pdf using jsPDF.

I could not get the pdf as the original html.
ordered list and unordered list bullet points are missing in the pdf file.

ordered-list-in-html

ordered-list-in-html

ordered-list-in-pdf

ordered-list-in-pdf

unordered-list-in-html

unordered-list-in-html

unordered-list-in-pdf
unordered-list-in-pdf

function BlazorDownloadFile(filename, text) {
  let parser = new DOMParser();
  let doc = parser.parseFromString(text, "text/html");

  console.log(doc.body);
  const element = doc.body;

  var opt = {
    margin: 1,
    filename: filename,
    html2canvas: { scale: 2 },
    jsPDF: { unit: "cm", format: "a4", orientation: "portrait" },
  };
  // Choose the element that our invoice is rendered in.
  html2pdf().set(opt).from(element).save();
}

Please help me to fix this issue.

JavaScript: Interrupt a setTimeout() inside a promise, upon a click event

Here is a very simplified reproduction of the issue I am facing:

window.onload=function(){
    touchme = document.getElementById('click');
    function mains(){
        touchme.innerHTML = "clicked " + Math.random().toString();
    }
    function process() {
        touchme.dataset.clicked = "false";
        mains();
        touchme.addEventListener("click", () => {
            touchme.dataset.clicked = "true";
        }, {once : true});

        let clickPromise = new Promise((resolve, reject) => {
            var timer = setTimeout(() => {
                if(touchme.dataset.clicked == "true"){
                    resolve();
                }
                else{
                    reject();
                }
            }, 1500);
        });
        
        clickPromise.then(() => { 
            process();
        });

        clickPromise.catch(() => {
            alert("game over");
        });
    }

    process();
}

This bit of HTML has been used <body><button id="click">Click</button></body>

What I basically want is:

  • if I click the button, mains() will run immediately
  • if I don’t, setTimeout() will wait 1.5secs for me. Within this time if I click, setTimeout() resets and mains() gets executed
  • if I still don’t click, alert("game over") is executed. The “self callback loop” breaks

However, the mains() function isn’t being run immediately whenever I am clicking, instead it is waiting for the timeout, causing a delay of 1.5s after every click.

Naturally, the solution is to use clearTimeout(), however, I can’t seem to wrap my head around where to use it. Adding it inside the function argument of event listener causes the timeout to run independently of the click event and just makes it reject the promise 1.5s later, notwithstanding my button clicks. I also tried calling the function itself inside the event listener function, which doesn’t work. Adding it inside an if(touchme.dataset.clicked == "true") outside the setTimeout() and inside the promise wouldn’t work, as my initial value is false, so it just checks the initial state.

How to check image height and width before upload in Reactjs

I am working on reactjs and right now i am trying to validate image height and width before upload,how can i do this ? i want user cant upload more than 200*200 (pixel)/dynamic,How can i do this ? Here is my current code

const createOfficer = async () => {
   setShowSpinner(true)
    const formData = createFormDataObject(newOfficerData)
    const res = await putAPIFormDataWrapper(editDepartmentUrl, formData)
    if (!res.isError) {
      setShowSpinner(false)
      props.notify(res.data.data.message, 'success')
    } else {
      setShowSpinner(false)
      props.notify(res.error.message, 'error')
    }
  }

How do I skip weekends on the X-axis?

Actual behaviour
Now a series of all days of the week is being built on the X-axis.
like now:
2022-5-30
2022-5-31
2022-6-1
2022-6-2
2022-6-3
2022-6-4
2022-6-5
2022-6-6

Live demo with steps to reproduce

https://jsfiddle.net/5z1b9xnp/

let globalData = []; let finRez = [];
let chart;

let duration = 500; // Determines how long the animation between new points should be take
let startIterator = 1; // Determines how many points will be rendered on chart's init
let currentIterator = startIterator;
let maxIterator = 1;

let guiButton = document.getElementById('start');
let guiButtonState = 'Start';
let intervalId;

// Fetch data:
fetch('https://raw.githubusercontent.com/veleg/trade/main/trade.json')
  .then(response => response.json())
  .then(data => {
    parseData(data);
    createChart();
    initEvents();
  });

function initEvents() {
  guiButton.addEventListener('click', function() {
    if (guiButtonState === 'Stop') {
      // User clicked "Stop" -> stop animation and allow to resume
      intervalId = clearInterval(intervalId);
      guiButton.innerText = guiButtonState = 'Resume';
    } else {
      // If animation has finished, recreate chart
      if (guiButtonState === 'Restart') {
        createChart();
      }
      guiButton.innerText = guiButtonState = 'Stop';
      // Start animation:
      redrawChart(currentIterator += 1);
      intervalId = setInterval(function() {
        // If we reached last available point, stop animation:
        if (currentIterator === maxIterator) {
          intervalId = clearInterval(intervalId);
          currentIterator = startIterator;
          guiButton.innerText = guiButtonState = 'Restart';
        } else {
          redrawChart(currentIterator += 1);
        }
      }, duration);
    }
  });
}

function redrawChart(index) {
  // Set new subtitle on every redraw
  chart.setTitle(null, {
    text:  ' Заработано: ' + globalData[0].data[index][1]
  }, false);
    
    
    const newValues = globalData.map(series => series.data[index][1]);
    const maxIndex = newValues.indexOf(Math.max.apply(null, newValues));

  // To each series, add a point:
  chart.series.forEach(
    (series, seriesIndex) => {
            const enabled = maxIndex === seriesIndex && ((index < 5) || (index % 5 === 0));
      series.addPoint(
                {
          x: globalData[seriesIndex].data[index][0],
          y: globalData[seriesIndex].data[index][1]
                    <!-- dataLabels: { -->
                        <!-- enabled -->
                    <!-- }, -->
                    <!-- marker: { -->
                        <!-- enabled -->
                    <!-- } -->
        },
        false,
        false,
        false
      );
    }
  );

  // Now, once everything is updated, redraw chart:
  chart.redraw({
    duration
  });
}

function parseData(data) {
  Highcharts.objectEach(
    data,
    // Prepare Highcharts data-format:
    // series: [{
    //   data: [ [x, y], [x, y], ..., [x, y]]
    // }]
    (countryData, country) => {
            if (country !== 'Diamond Princess' && country !== 'Holy See') {
                globalData.push({
                    name: country,
                    data: countryData.map(p => [Date.parse(p.date), p.recovered / getCountryPopulation(country)])
                    <!-- data: countryData.map(p => [p.date, p.recovered / getCountryPopulation(country)]), -->
                    <!-- datas: countryData.date, -->
                    <!-- datass: countryData.map(p => [p.date, p.date]) -->
                });
            }       
            
        }
  );


  // Sort and limit dataset:
  globalData = globalData
    .sort((countryA, countryB) => {
      let countryALen,
        countryBLen;

      if (!countryA || !countryA.data || countryA.data.length === 0) {
        return 1;
      }

      if (!countryB || !countryB.data || countryB.data.length === 0) {
        return -1;
      }

      return countryB.data[countryB.data.length - 1][1] - countryA.data[countryA.data.length - 1][1];
    })
    .splice(0, 8);
        

  maxIterator = Math.max.apply(null, globalData.map(series => series.data.length - 1));
}


function createChart() {
    function format(y) {
    return y.toFixed(2);
  }

  chart = Highcharts.chart('container', {
    chart: {
      type: 'spline',
      marginLeft: 100
    },

    legend: {
      layout: 'proximate',
      align: 'right'
    },


    title: {
      floating: true,
      align: 'left',
      x: 93,
      y: 20,
      text: 'Confirmed cases per country per 1000 inhabitants'
    },
    subtitle: {
      floating: true,
      align: 'left',
      y: 60,
      x: 90,
      text:  ' Заработано: ' + globalData[0].data[0][1],
      style: {
        fontSize: '20px'
      }
    },
    tooltip: {
      split: true,
      pointFormatter: function() {
        <!-- var value = format(this.y); -->
        <!-- return `<span style="color:${this.color}">●</span> ${this.series.name}: <b>${value}</b><br/>`; -->
            }
    },

    yAxis: {
      title: {
        text: ''
      },
      maxPadding: 0.2,
      softMax: 1
    },

    xAxis: {

      gridLineWidth: 2,
      min: globalData[0].data[0][0],
      minRange: 7 * 24 * 3600 * 1000,
      type: 'datetime'
      <!-- categories: [1] -->
    },


    plotOptions: {
      series: {
        animation: {
          duration
        },
        <!-- marker: { -->
          <!-- symbol: 'circle' -->
        <!-- }, -->
        dataLabels: {
          formatter: function() {
            return format(this.y);
          }
        }
      }
    },
    series: globalData.map(series => {
      return {
        name: series.name,
        data: series.data.slice(0, startIterator).map(point => {
                    return { x: point[0], y: point[1] }
                })
      }
    })
  });
}


function getCountryPopulation(country) {
  return {
    "Заработано": 1,
    "Финансовый результат": 1
  }[country];
}

Product version
Highcharts JS v10.3.2 (2022-11-28)

It is necessary to skip days on the X axis that are not in the JSON file.
need:
2022-5-30
2022-5-31
2022-6-1
2022-6-2
2022-6-3
2022-6-6

Vuex cant read localstorage on page refresh

I store a user token in a vuex state.
When the page of my nuxt app is refreshed, i want this token to persist, to check for eligibility to visit user-related routes.

From a global middleware, i just dispatch an action like so

 context.store.dispatch('authModule/resetToken')

triggering the vuex action

resetToken(context) {
    context.commit('RE_AUTH')
  },

which triggers the following mutation

RE_AUTH: (state, token) => {

    if (!state.token && process.client && localStorage.getItem('auth-token')) {
      token = localStorage.getItem('auth-token')
      state.token = token
    }
  },

When i reload the page, the mutation is triggered, but the if condition does not resolve true and execute the code to reappend the token, even though there is the correct named token in localhost.

When i however then navigate to another page, the code does execute and reappends the token. I dont understand why, because global middleware should be executed first in lifecycle and vuex should have access to localstorage

document.querySelector().innerHTML not working properly

i’m trying to make a website and i’m trying to use a js function to write the header. Here is the js code(writeStuff.js):

document.querySelector(".WriteHeader").innerHTML = `
    <div>
        <img src="images/logo.png" alt="Wizards and Potters Logo">
        <title>Wizards & Potters, a Harry Potter/DnD webcomic</title>
        <div class="header">
            <h3 id="nav"><a id="headernav" href="0005.html">READ</a> ¦ ¦ ¦ ¦ <a id="headernav" href="archive.html">ARCHIVE</a> ¦ ¦ ¦ ¦ <a id="headernav" href="about.html">ABOUT</a></h3>
        </div>
    </div>
`;

And I call it in my page here:

    <body>
        <div class-'WriteHeader'></div>
        <h2 id="title"> 1. NPC Monologues <a href="0002.html">></a></h2>

And reference the script at the bottom:

        <p id="footer">ⒸAHumanIBelieve, 2023</p>
        <script src="writeStuff.js"></script>
    </body>
</html>```

I've tried changing the name of the js thing, the name of the js file, removing and replacing the dor.

Is there a way to hook into Next.js build-time execution?

I know that Next.js does some build-time execution for SSG. Is there a way to hook into this build-time execution to run some basic code?

Let’s say that these special functions are delimited with $, so:

// build-time only function
const $concat = (...args: string[]) => args.join(" ")

const x = $concat(
    "this",
    "that",
    "and the other"
)

would build to the following JS:

const x = "this that and the other"

This would be super useful for tailwind class name manipulations.

Java spring boot web socket not working with javascript WebSocket object

I created a web socket with spring boot’s TextWebSocket handler and it works perfectly fine with postman but it doesn’t work with the javascript Socket object.


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(locationHandler(), "/users/location")
                .addInterceptors(new HttpSessionHandshakeInterceptor())
                .setAllowedOrigins("*");
    }

    @Bean
    public LocationHandler locationHandler() {
        return new LocationHandler();
    }

}

Above is my configuration code.
This is my handler code:

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

public class LocationHandler extends TextWebSocketHandler {

        @Override
        public void handleTextMessage(WebSocketSession session, TextMessage msg) {
            System.out.println(msg.getPayload());
            try {
                session.sendMessage(new TextMessage("test"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

This is the error I get on the javascript side:

Event {
  "isTrusted": false,
  "message": "The operation couldn’t be completed. Connection refused",
}

This is my javascript code:

  let test = new WebSocket("ws://192.168.1.80:8080/");
  test.onerror = function(err) {
    console.log(err);
  }
  
  test.onopen = function() {
    console.log("opened");
    test.send('test work please');
  }

Nothing is received in the backend side.

I tried allowing cors but I’m not sure if I did it properly. I couldn’t find much online on the TextWebSocketHandler as most web sockets in spring are implemented with STOMP.

Blank Page is loading in github Pages

I have deployed my react app made using create-react-app by using the gh-pages npm package to github pages.

The steps I have performed are :

Step 1: Install gh-pages via the terminal
$ npm install gh-pages –save -dev

Step 2: Modified the package.json and added

“homepage”: “https://nemb0t.github.io/todo_typescript/”

Step 3: In the “scripts” section of package.json, added

“predeploy”: “npm run build”,
deploy”: “gh-pages -d build”,

Step 4: Ran the command ‘npm run deploy’.

I am not using react router or any other routers since mine is a simple todo list application.

This is what my github pages looks like:
Github pages preview

Please note I the app is working as expected in the development server (npm start) and the app also works as expected when ran after its build (“npm run build” and then “serve -s build”).
Note: when running build I replaced the homepage (“homepage”: “.”).

Github: https://github.com/NemB0t/todo_typescript

Site URL: https://nemb0t.github.io/todo_typescript/

I have tried tweeking the URL in the homepage of the package.json, tried many tweeks to the different tags but nothing seems to help.

The app is expected to look like this:
Expect Todo App

Kindly help in resolving the issue. I have been struggling with the problem the entire week and have tried out many solutions from stackover flow and other forums.

JS Promise function call that returns object

I have a async fetch function that waits 2 seconds and returns a object:

async function fetch() {
    var object;
    await setTimeout(() => { object = { name: 'User', data: 'API Data' } }, 2000);
    return object;
}

I want to display the object when the initialization is completely done (after 2 seconds)

fetch().then((val) => {
    console.log("DONE!"); 
    console.log(val.name);
}).catch((err) => {
    console.log("ERROR!");
    console.log(err);
});

The code prints both DONE and ERROR Cannot read properties of undefined (reading 'name')

I have tried with Promise, no luck

let promise = new Promise((resolve, reject) => {
    let request = fetch();
    if (request !== undefined)
        resolve(request);
    else
    reject(request);

}).then((val) => {
    console.log(val);
});

How can I properly check that fetch() has returned a value before printing without changing the inside of the function. I can delete the async and await in it but I am unable to edit it (I.E. adding a Promise inside)

Mantine date picker throws an objects are not valid as a react child error

I’m trying to use mantine Date in NextJS. When a user clicks on the date, that date suppose to display the date in the html text heading. For example, if a user picks the date jan 1st 2023, the text is supposed to look like Date: Sun Jan 01 2023... I’m testing it out using a console.log and it works. However, when I try to use it in the text heading this error gets thrown: Error: Objects are not valid as a React child (found: [object Date]). If you meant to render a collection of children, use an array instead.

I tried adding a map to it that didn’t work. Then I tried using const date = [...calendarVal] but it said TypeError: calendarVal is not iterable

import { useState, useEffect } from 'react';
import { Modal, Button, Group } from '@mantine/core';
import { Calendar, RangeCalendar } from '@mantine/dates';
import React  from 'react';

export default function Demo() {
  const [opened, setOpened] = useState(false);
  const [calendarVal, setCalendarVal] = useState(Date());
  const [hydrated, setHydrated] = React.useState(false);

  React.useEffect(() => {
    setHydrated(true);
  }, []);

  useEffect(() => {
    console.log(calendarVal)
  })

  if (!hydrated) {
    // Returns null on first render, so the client and server match
    return null;
  }
  
  return (
    <>
      <Modal
        opened={opened}
        onClose={() => setOpened(false)}
        title="Introduce yourself!"
      >
        {/* Modal content */}
      </Modal>

      <Group position="center">
        <Button onClick={() => setOpened(true)}>Open Modal</Button>
        
      </Group>
      
      <p>Date: {calendarVal}</p>
      <Group position='center'>
        <Calendar onChange={setCalendarVal} value={calendarVal}  />
      </Group>

    </>
  );
}

How can i fix this error ERROR TypeError: undefined is not an object (evaluating ‘userData.username’)

Can anyone help me to fix this error? the error says ERROR TypeError: undefined is not an object (evaluating ‘userData.username’) when I test this API in postman it gives results also when I am logging the username and profile pic value then in the backend its logs but when in frontend it’s giving me error What is the solution of this error and how can I display the username and profile coming from backend? and also one thing I get the user city name by expo location I also have a city in my user schema which is a string and when a user agrees on the permission of location then the city gets saved in the database

Backend:

router.get("/user", async (req, res) => {
    try {
      const city = req.body.city;
  
      console.log(city);
  
      const count = await User.countDocuments({ city: city });
      if (count === 0) {
        return res.status(404).json({ error: "No users found with that city" });
      }
  
      const randomUser = await User.aggregate([
        {
          $match: {
            city: city,
          },
        },
        {
          $sample: {
            size: 1,
          },
        },
        {
          $project: {
            username: 1,
            profilepic: 1, 
          },
        },
      ]);

      console.log(randomUser[0].username)
      console.log(randomUser[0].profilepic)
  
      res.json(randomUser);
    } catch (err) {
      console.log(err);
      res.status(500).json({ error: err });
    }
  });

Frontend:

import { StyleSheet, Text, View, Image } from 'react-native'
import React, { useState, useEffect } from 'react'

const SearchUserPage = () => {
  const [userData, setUserData] = useState();

  useEffect(() => {
    async function fetchUser() {
      try {
        const response = await fetch('http://10.0.2.2:3000/user');
        setUserData(response.data);
      } catch (error) {
        console.error(error);
      }
    }

    fetchUser();
  }, []);
  
  return (
    <View style={styles.container}>
      <View style={styles.userSection}>
        <View style={styles.imageContainer}>
          <Image
            style={styles.image}
            source={{ uri: userData.profilepic }}
            resizeMode="contain"
            overflow="hidden"
          />
        </View>
        <Text style={styles.text}>{userData.username}</Text>
      </View>
    </View>
  )
}

export default SearchUserPage

How to make loop not to continue until an event happens?

I am writing a function of a game:

function Game(){
    while(true){
        var level = 1;
        $("#level-title").text("Level " + level);
        var colorsOrder = [];
        var randColor = GenerateRandomSquareColor();
        colorsOrder.push(randColor);
        ButtonClickResponse(randColor);

        for(var i = 0; i < level; i++){
            var color;
            $(".btn").on("click", function(event) {
                ButtonClickResponse(this.id);
                color = this.id;
            });
            if(colorsOrder[i] != color){
                GameOver();
                return;
            }
        }
        level++;
    }
    
}

the “if statement” in the loop of function runs immediately when loop is started and doesnt wait for an above event to finish.

I searched for solving with “async await” and “promise” in google and stackoverflow, but didn’t really understand how it worked so couldn’t implemet it in my code.