React wrong result on the change of state

I’m new to react and working on simple eCommerce application. I am changing the quantity of in the cart when it is added more than one times but it gives wrong result(As we can see in the output the ‘quantity’ I print and in the object are different eg. before:1 after:2 but in the object it is 3).I’ll appreciate any help. Thank You!!

here is my reducer.js

export const initialState = {
    basket : [],

}


const reducer = (state, action) => {
    switch(action.type){
        case "ADD_TO_BASKET":
            const newIndex = state.basket.findIndex((basketItem)=> basketItem.id==action.item.id)
            if(newIndex >= 0){
                const newBasket = [...state.basket];
                console.log(newBasket);
                console.log("quantity "+newBasket[newIndex].quantity);
                newBasket[newIndex].quantity+=action.item.quantity;
                console.log(newBasket);
                console.log("quantity "+newBasket[newIndex].quantity);
                return{
                    ...state,
                    basket: [...newBasket]
                }
            }
            return{
                ...state,
                basket: [...state.basket ,action.item]
            }
            .
            .
            .

export default reducer;

here is my checkout.js:

import { useStateValue } from "./StateProvider"
function Checkout() {
    const [{basket}, dispatch] = useStateValue();
return (
        <div className='checkout'>
            <div className="checkout__left">
                <img src="https://images-na.ssl-images-amazon.com/images/G/02/UK_CCMP/TM/OCC_Amazon1._CB423492668_.jpg" alt="" className="checkout__ad" />
                <div>
                    <h2 className='checkout__title'>
                        Your Shopping Basket
                    </h2>
                    {basket.map(item => (
                        // console.log("checkout product quantity: "+JSON.stringify(item.quantity)),
                        <CheckoutProduct 
                            key={i++}
                            id = {item.id}
                            title = {item.title}
                            image = {item.image}
                            price = {item.price}
                            rating = {item.rating}
                            quantity = {item.quantity}
                        />
                    ))}
 .
 .
 .

StateProvider.js:

import React, { createContext, useContext, useReducer } from 'react'

//prepares the data layer
export const StateContext = createContext();

//wrap our app and provide the data layer
export const StateProvider = ({ reducer, initialState, children }) => (
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>
);

//pull infromation from the data layer
export const useStateValue = () => useContext(StateContext);

Output in console:

-> [{…}]0: {---, quantity: 3}length: 1[[Prototype]]: Array(0)
-> quantity 1
->[{…}]0: {---, quantity: 3}---
-> quantity 2

How to solve ERR_TOO_MANY_REDIRECTS that is happening due to one middleware that forces https connection?

My middleware

exports.redirectToHTTPS = (req, res, next) => {
    if (req.protocol == "https") {
        return next()
    }
    const redirect_not = req.query.redirect
    
    console.log("!!!!! Connection not secure")
    const redirect_url = ['https://', req.get('host'), req.originalUrl].join('')
    console.log("REDIRECT_URL:- " + redirect_url)
    return res.redirect(redirect_url)
}

in index.js

app.use(redirectToHTTPS)

I am using express.js and node.js

Need to wait for Google API but sleep function doesn’t work

I need to load Google Maps API in my svelte project.
I’m using js-api-loader npm package.

Here’s the peace of code that I use to load the Google API:

loader.js

import { Loader } from '@googlemaps/js-api-loader';

let googleIsLoaded = false;

async function loadGoogleMapsAPI() { 
  if (!googleIsLoaded) {
    const libraries = ['places'];
    try {
      const loader = new Loader({
        apiKey: API_KEY,
        version: 'weekly',
        libraries,
      });
      console.info('Loading Google API ...'); // LOGGED 1st -> OK
      await loader.load();
      console.info('Google API is loaded'); // LOGGED 6th -> KO
      googleIsLoaded = true;
    } catch (error) {
      throw new Error(`Google API Loader failed ${error.message}`);
    }
  }
}

When a page loads, it first hits the route defined below
route/index.svelte:

<script context="module">
  export const ssr = false;
</script>

<script>
  import MyComp from '$components/MyComp.svelte';
  import { loadGoogleMapsAPI } from '$lib/loader.js';

  init();

  async function init() {
    try {
      await loadGoogleMapsAPI();
    } catch (e) {
      console.error(e);
    }
  }

  <MyComp />

Then, MyComp.svelte below is loaded:

import { onMount } from 'svelte';

let google;
onMount(() => {
    console.log('mounted'); // LOGGED 2nd -> OK
    google = window.google;
    if (google === undefined) {
      console.log('google is undefined'); // LOGGED 3rd -> OK
      sleep(5000, init());
    } else {
      console.log('google is defined');
    }
});

async function init() {
    ...
    autocompleteWidget = new google.maps.places.Autocomplete(input, options); 
/////////// LOGGED 5th -> KO: EXCEPTION GOOGLE IS NOT DEFINED /////////
}

and here the helper function to make the sleep

helpers.js


export async function sleep(time, fn, ...args) {
  console.info('sleep ' + time + 'ms');  // LOGGED 4th -> OK
  await timeout(time);
  console.info('woken'); // LOGGED 7th -> KO
  return fn(...args);
}

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

But for whatever reason, the init() function is triggered ignoring the sleep(5000, init()) call :/

Thank you for your help.

console

loader.js: Loading Google API ...
MyComp.svelte: mounted
MyComp.svelte: google is undefined
helpers.js: sleep 5000ms
MyComp.svelte:106 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'maps')
helpers.js: Google API is loaded
helpers.js: woken

Get site-URL-parameter from iframe (same domain)

I’ve got two html pages (site, sub).
sub.html is embeded in the site page as an iframe.
On the sub page I am running the following js:

    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const param1 = urlParams.get('param1')
    const param2 = urlParams.get('param2')
    alert (param1 + param2)

It works fine. When I open …/sub.html?param1=hello&param2=world, I end up with “Hello World”.
But the URL-parameters are on “site.html” not on sub.html.
So I open site.html?param1=hello&param2=world how do I get those URL parameters?
I read that that is not possible if both sites are not on the same domain. In my case – they are on the same domain, so that should not a problem. At the time I am just testing it locally.

nested unique flat in javascript

Is there some super new ES JavaScript magic that can achieve this ? (I can write a function to achieve this, was just wondering if any new ES202* technique exists )

let arr = [
    ['cb', ''],
    ['cb', '34'],
    ['cb', '35'],
    ['rb', '1']
];

/*
Required Output : 
[['cb', ['34', '35']], ['rb', '1']]
*/

console.log([...new Set(arr.flat(1))])

IF else && statement in React JSX

Hey guys I am having trouble understanding how to create an IF else & statement in React. All documentation, videos and questions that I find online only show the method of doing one of them, either an IF else or an &&

Basically the IF statement I am trying to create within the JSX looks like this.

If(data.AP == "1" && data.MP == "1")
{
set.Text("Both")
}
else if(data.AP == "0" && data.MP == "1")
{
set.Text("Manager")
}
else if(Data.AP == "1" && data.MP == "0")
{
set.Text("Payroll")
}
else{
setText("Not Approved)
}

A fairly simple IF statement in Java but I can’t seem to find a way to translate this into JSX. So far this is the furthest I have got and it keeps giving me errors whenever I chop and change it depending on the documentation I am reading. I know how to use ?? Ternary operators and && operators but using them together doesnt seem to work for me.

 return (

   {
  data.MP == "1" && data.AP == "1" && (
     <td colSpan="1">{"Both"}</td> ) : null
  }

)

export json data as csv in react

Hey guys I’m trying to add a download button in order to export some Json data as csv but this is not working for me. The data i want to export is inside shareFilterHead and shareFilterRows and the data is in Json. I’m using the CsvDownloader from ‘react-csv-downloader’.

import React, {Component} from "react";
import DynamicTable from '@atlaskit/dynamic-table';
import styled from 'styled-components';
import CsvDownloader from 'react-csv-downloader';

export default class ShareFilter extends Component {

constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      shareFilterRows: []
    };
  }

componentDidMount() {
    fetch(AJS.contextPath() + "/rest/securityrestresource/1.0/results?check=ShareFilter")
    .then((res)=>{
        if(res.ok) {
            return res.json();
        }
    }).then((res)=>{
  this.setState({
    isLoaded: true,
    shareFilterRows: res.map((row, index) => ({
      key: `row-${index}-${row.filterID}`,
      cells: [{
        key: `${row.filterID}`,
        content: row.filterID,
        },
        {
        key: `${row.author}`,
        content: row.author,
        },
        {
        key: `${row.filtername}`,
        content: row.filtername,
        },
        {
        key: `${row.jql}`,
        content: row.jql,
        },]}))
  })
  })
  }

render() {
const { error, isLoaded, shareFilterRows } = this.state;
if (error) {
  return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
  return <div>Loading Shared Filters...</div>;
} else {
  return (<Wrapper>
    <div>
    <DynamicTable
      head={shareFilterHead}
      rows={shareFilterRows}
      rowsPerPage={10}
      defaultPage={1}
      loadingSpinnerSize="large"
      isLoading={false}
      isFixedSize
      defaultSortKey="filterID"
      defaultSortOrder="ASC"
      onSort={() => console.log('onSort')}
      onSetPage={() => console.log('onSetPage')}
      
      />
  </div>
  </Wrapper>
  );
  }
}
}

AJS.$(document).on("click", "#downloadShareFilterCheck", function(){

    <CsvDownloader
    filename="myfile"
    extension=".csv"
    separator=";"
    wrapColumnChar="'"
    columns={shareFilterHead}
    datas={shareFilterRows}
    text="DOWNLOAD" />


}); 

PurgeCSS: how to match css with backslash

I am using csspurge using the config file. I have css written as
lg:right-40 and in js it is referred as lg:right-40.
in js backslash is escaped hence purgecss is not able identify all the that contain

cssfile

.lg:right-40 {
    right: 10rem;
}
.lg:right-44 {
    right: 11rem;
}
.lg:right-48 {
    right: 12rem;
}
.lg:right-52 {
    right: 13rem;
}
.lg:right-56 {
    right: 14rem;
}

purgecss.config.js

   const TailwindExtractor = (content) => {
  // Treat every word in the bundle as a CSS selector
  return content.match(/[w-/\:]+(?<!:)/g) || []
}
    new PurgeCSS().purge({
      content: ['./src/**/*.jsx', './src/**/*.js'],
      css: ['./src/login/tailwind_backup.css'],
      safelist:{
        greedy:[/\/]
      },
      extractors: [{
        extractor: TailwindExtractor,
        extensions: ['js', 'jsx'],
      }],
      output: './src/login/tailwind.css'
    })

I want to match css classes with with js classes without

rrestrict the direct url file name with javascript?

hello I’m new to javascript

I just created my first website with 2 pages, eg page1.html and page2.html

if the user is not logged in (page1.html) still they can have access to other pages (page2.html) through URL

I want to stop url access with javascript

Please suggest me how to do it

Click event not working when using arrow functions (jQuery) [duplicate]

I want to add a class to an <h1> element when I click on it. I am using an arrow function, but it is not working.

Here is my code:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.min.js"></script>
        <link rel="stylesheet" href="css/style.css">
        <title>Test</title>
    </head>
    <body>
        <h1>Click me!</h1>
        <script src="js/script.js"></script>
    </body>
</html>
$(document).ready(start)

function start(){
    $('h1').click(()=>{
        $(this).toggleClass('h1-click')
    })
}

How can I run a function inside of a function in NodeJS? [duplicate]

class TestClass {
    async profile() {
        await ClientData (BASE_URL, function Data (response) { // ClientData is using `export async function` in another file that has function for getting body from a website url
            return response
        })
    }
}

const Client = new TestClass();
async function test() {
    console.log(await Client.profile().Data());
}

test();

It always give an output (node:5424) UnhandledPromiseRejectionWarning: TypeError: Client.run(...).Data is not a function, I do tried one thing previously with this:

async function test() {
    console.log(await Client.profile().Data);
}

test();

Instead of getting the output, it just gives me output undefined

How to display different data types in radial stacked chart using D3?

I’m trying to display data in a radial chart/donut chart where there is a threshold and an overshoot. The data I am displaying is in percent, tonnes, kg per capita, scale(0-1). I’m guessing I would have to convert the data to a common type like percent, but I’m unsure how to go about it.

The chart is supposed to look like this

Another example

Here is a snippet of the data:

Planetary Boundry Threshold Overshoot
Climate Change – 2.35 tonnes CO2 equivalent per capita yearly 18.95 tonnes CO2 equivalent per capita (2020)
Ocean acidification – 1.59 tonnes CO2 per capita yearly (until 2055) 15.33 tonnes CO2 per capita (2020)
Nitrogen 100% good or very good ecological condition (limit between moderate and good = 250-775 µg/L) 72.7%
Biodiversity / land use 0.6 (scale 0-1) 0.45

Ramda JS – Pass optional argument to the second function of a pipe

I am trying to refactor this code:

async function getUserDataByUsername(username, cached = true) {
  const usernameRef = firestore
    .collection("usernames")
    .doc(username.toLowerCase());

  const usernameDoc = await usernameRef.get();

  if (!usernameDoc.exists) {
    throw userErrors.userNotFound();
  }

  const { userId } = usernameDoc.data();

  return memoizedGetUserData(userId, cached);
}

For that, I have thought to split it in smaller parts, as follows:

function memoizedGetUserData(userId, cached = true) { 
  ... Fetching from LRU or DB ... 
}

async function getUserId(username) {
  const usernameRef = firestore
    .collection("usernames")
    .doc(username.toLowerCase());

  const usernameDoc = await usernameRef.get();

  if (!usernameDoc.exists) {
    throw userErrors.userNotFound();
  }

  const { userId } = usernameDoc.data();

  return userId;
}

async function getUserDataByUsername(username, cached = true) {
  const userId = await getUserId(username);

  return memoizedGetUserData(userId, cached);
}

Now, I want to apply Ramda to this module. I have never used this library before, but I have read that it is really cool, and makes the code easier to understand with some of it utilities.

What I am trying is to refactor the original method using the pipeline style, as follows:

import R from "ramda";

...

const getUserDataByUsername = R.pipeP(getUserId, memoizedGetUserData);

But… how can I pass the second optional parameter “cached”, only to the second argument of my pipe??

How to split object into multiple objects by props names in JS

I am trying to split object into multiple objects. Here is how it looks. It is actually array of objects.

[
  {
    interval_9_gun_time_milliseconds: 0,
    interval_9_net_time_milliseconds: 0,
    interval_9_gun_pace: '00:07:04',
    interval_8_gun_time_milliseconds: 0,
    interval_8_net_time_milliseconds: 0,
    interval_8_gun_pace: '00:07:04',
    entry_id: 200
  },
  {
    interval_9_gun_time_milliseconds: 0,
    interval_9_net_time_milliseconds: 0,
    interval_9_gun_pace: '00:02:04',
    interval_8_gun_time_milliseconds: 0,
    interval_8_net_time_milliseconds: 0,
    interval_8_gun_pace: '00:04:04',
    entry_id: 404
  },
  {
     entry_id: 1
  }
]

So expected result should be:

 [
      {
        interval_9_gun_time_milliseconds: 0,
        interval_9_net_time_milliseconds: 0,
        interval_9_gun_pace: '00:07:04',
        entry_id: 200
      },
      {
        interval_8_gun_time_milliseconds: 0,
        interval_8_net_time_milliseconds: 0,
        interval_8_gun_pace: '00:07:04',
        entry_id: 200
      },
      {
        interval_9_gun_time_milliseconds: 0,
        interval_9_net_time_milliseconds: 0,
        interval_9_gun_pace: '00:02:04',
        entry_id: 404
      },
      {
        interval_8_gun_time_milliseconds: 0,
        interval_8_net_time_milliseconds: 0,
        interval_8_gun_pace: '00:04:04',
        entry_id: 404
      }
    ]

Bottom line split and group object by interval_{number} and add other props, if object doesn’t have interval remove it.