JavaScript checkboxes not updating on check

I am mapping some data into a table. Each row of the table has a checkbox. In order to manage the state of the checkboxes I am adding or removing the checkbox id to the array.

I want to determine if a box should be checked by seeing if the id is contained in the array.

  const [bulkUpdateIds, setBulkUpdateIds] = useState([
    '7a678176-2703-4f89-63cb-08dc3e4b1e2f',
  ])

  function handleCheck(id) {
    console.log('running', bulkUpdateIds)
    const idArray = bulkUpdateIds
    if (idArray.includes(id)) {
      const index = idArray.indexOf(id)
      idArray.splice(index, 1)
      setBulkUpdateIds(idArray)
    } else {
      idArray.push(id)
      setBulkUpdateIds(idArray)
    }
  }

   cellRenderer: (params) => {
      return (
         <input
            type="checkbox"
            checked={bulkUpdateIds.includes(
                params.data.soVRecordID
            )}
            onChange={() =>
                handleCheck(params.data.soVRecordID)
            }
      />
  )
},

I can see that the id is being added and removed from the list, however it seems like the logic to determine if the box is checked or not only fires once.

Create webpack plugin to analyze modules and find import statement

I’ve been trying to create a plugin to solve the problem below:

  • Analyze the source code of my application to find for a particular import i.e import useT from ‘./useT’;
  • It should go through the dependency graph as multiple files can import this function
  • Once the files are found, traverse the AST and look for: const { t } = useT().actions;
  • Locate all the places where ‘t’ is called and save the arguments in a list (array)

I’ve been reading the documentation and trying to ‘tap’ inside of the different steps of the build process but it seems extremely complicated.

I was able to find the dependencies in one of my tries but the raw source code was not available in that part of the process.
In other tries, the step was analyzing all deps from node_modules when this is source code from my application and does not come from any npm modules.

I feel so frustrated.

Additionally, there are circular references and the objects (modules) are very large making it very hard to debug.

I appreciate all the help from anyone that already delt with Webpack in the past.

Thank you.

When I clicks on signup button Google OAuth automatically redirects to successRedirect even if I logged out

server.js

import connectDB from './db/connection.js'
import dotenv from 'dotenv'
import express from 'express'
import authRouter from './routes/auth.route.js'
import session from 'express-session'
import cors from 'cors'
import passport from 'passport'
import { oAuthConfig } from './middlewares/passport.js'

const app = express()
dotenv.config()
const PORT = process.env.PORT || 5000



app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cors({
    origin: 'http://localhost:5000',
    credentials: true,
}))



app.use(session({
    secret: 'secret',
    resave: false,
    saveUninitialized: false,
    cookie: {
        maxAge: 1000 * 60 * 60 * 24,
        secure: false,
    }
}))

oAuthConfig()
app.use(passport.initialize())
app.use(passport.session())


passport.serializeUser((user, done) => {
    done(null, user)
})

passport.deserializeUser((user, done) => {
    done(null, user)
})

app.use('/auth', authRouter)



app.listen(PORT, () => {
    connectDB()
    console.log(`Server is running on port ${PORT}`)
})

passport.js

import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import User from '../models/user.model.js';

export const oAuthConfig = (req,res) => {
    passport.use(
        new GoogleStrategy({
            clientID: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
            callbackURL: '/auth/google/callback',
            scope: ['profile', 'email'],
            prompt: 'select_account'
        },
            async (accessToken, refreshToken, profile, done) => {
                try {
                    let user = await User.findOne({ googleId: profile.id });

                    if (!user) {
                        user = new User({
                            googleId: profile.id,
                            displayName: profile.displayName,
                            email: profile.emails[0].value,
                            image: profile.photos[0].value
                        });
                        await user.save();
                        
                    }
                    return done(null, user);
                } catch (error) {
                    console.log("ERROR IN PASSPORT.JS ",error);
                    return done(error, null);
                }
            })
    );
}

auth.route.js

import express from 'express'
import { login, logout, signupWithGoogle, googleAuthCallback } from '../controllers/auth.controller.js'


const router = express.Router()

router.get('/google', signupWithGoogle,(req,res)=>{
    console.log("SESSION : ",req.session)
    console.log("USER : ", req.user)
})
router.get('/google/callback', googleAuthCallback,(req,res)=>{
    console.log("SESSION : ",req.session)
    console.log("USER : ", req.user)
    res.status(200).json(req.user)
})

router.get('/login', login)
router.get('/logout', logout)


export default router

auth.controller.js

import passport from 'passport';

export const signupWithGoogle = passport.authenticate('google', { scope: ['profile', 'email'] })
export const googleAuthCallback = passport.authenticate('google', { failureRedirect: '/login', session: false })

export const login = async (req, res) => {
        console.log("SESSION : ", req.session)
}

export const logout = async (req, res) => {
        try {

                req.logout((err) => {
                        req.session.regenerate(() => {
                                res.redirect('/login');
                        });
                });

        } catch (error) {
                console.log('Something went wrong.', error.message)
                res.status(500).json({ message: 'Something went wrong.' })
        }
}

I use react.js for frontend. The server and frontent is running in two different ports.

Whenever I click signup button, google OAuth doesn’t even show the choose account section. I tried adding prompt: 'select_acccounts but it didn’t solved the problem.

When I logout from my account and then I click signin button it should show the select account google window. Please help me to solve this problem.

Redux state gets erased on page reload when deployed but not locally

I’m facing an issue where my Redux state is getting erased every time I reload the page after deploying my React app. However, when running the app locally, the Redux state persists as expected across reloads.

Is this behavior normal when deploying a React app with Redux? I’m using react-redux for state management, and I’m wondering if there’s a configuration or setup step that I might be missing for production deployments.

I tried setting it also direcly from session storage on my App.tsx file but it’s not working

useEffect(() => {
      const storedData = sessionStorage.getItem('auth');
      if (storedData) {
        const auth = JSON.parse(storedData);
        if (auth && auth.isAuthenticated) {
          dispatch(login({
            user: auth.user,
            token: auth.token,
            pages: auth.pages
          }));
          dispatch(setAuthData(auth));
        }
      }
    }, [dispatch]);

How to dynamically load locales

Currently I have a default language and other supported languages

const resBundle: LanguageTranslation = {
  en: {
    get translation() {
      return require('../../i18n/en/translation.json');
    },
  },
};

const otherLanguages: LanguageTranslation = {
  es: {
    get translation() {
      return require('../../i18n/es/translation.json');
    },
  },
  fr: {
    get translation() {
      return require('../../i18n/fr/translation.json');
    },
  },
};

Soon I need to add two more locales so instead of adding it manually I would be nice to import that dynamically. This is my i18n setup

const useI18n = () => {
  const [initialized, setInitialized] = useState(i18n.isInitialized);
  useEffect(() => {
supportedLanguages.forEach(language => { // currently I am importing all the languages from phrase but only want to load specific language that I need to support based on supportedLanguages config
        if (language in otherLanguages) {
          resBundle[language] = otherLanguages[language];
        }
      });

I tried doing something like

let myPath= `../../i18n/${initial}/translation.json` // where initial was 'fr'
 import(myPath)
      .then(module => console.log('woo', module)) // I got invalid call

also tried

const myI= require(`../../i18n/${myPath}) // still invalid call cannot transform

Any help is appreciated.

Insert multiple rows php msyql

Hello I would like to insert multiple rows into my mysql database the problem is that for numRows i always get 1 as resul no matter how much row i have added. And $_POST["product_name"][$i] gives back nothing as well

$numRows = count($_POST["product_name"]);
    echo "<script>alert('$numRows');</script>";

for ($i = 0; $i < $numRows; $i++) {
        $test = $_POST["product_name"][$i];
        echo "<script>alert('$test');</script>";
}

the input field:

<td><input type="text" class="form-control" name="product_name[]" onchange="Calc(this)"></td>

And this is the add row function

function btnAdd() {
            var v = $('#Trow').clone().appendTo('#Tbody');
            $(v).find("input").val('');
            $(v).removeClass("d-none");
        }

Get URL Using JavaScript [closed]

I need to capture the URL of the browser for some transformations.

I’ve used

window.location.href

However this bringing back the value of the server path, instead of the browser URL

My URL looks like this:

https://example.com/user/test-user

but using window.location.href, and setting the value to a variable, i get this:

https://example.com/pages/server/path/uservalidation.html

Ofc I’ve made up the url’s, but that’s what’s going on.

thanks for any help

Highcharts is not being rendered in an basic vue js app. Empty div being returned

I have a simple Vue js app. I am trying to render highcharts into the app. I know I am getting data from the database that I am not using in there chart tight now. But I will later. Right now I just wanted to console that data, that I am able to. But am not able to render a simple highcharts bar chart.

I am very new to vue js. What am I missing?

package.json

{
  "name": "my-dashboard",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^1.6.8",
    "core-js": "^3.8.3",
    "crypto-browserify": "^3.12.0",
    "dotenv": "^16.4.5",
    "highcharts": "^11.4.1",
    "highcharts-vue": "^2.0.1",
    "os-browserify": "^0.3.0",
    "path": "^0.12.7",
    "path-browserify": "^1.0.1",
    "stream-browserify": "^3.0.0",
    "vm-browserify": "^1.1.2",
    "vue": "^3.2.13"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "browser": true,
      "es2021": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser",
      "ecmaVersion": 2021
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "not ie 11"
  ]
}

componenets/BarChart.vue

<template>
  <div class="chart-container">
    <highcharts :options="chartOptions"></highcharts>
  </div>
</template>

<script>
import Highcharts from "highcharts";
import axios from "axios";

export default {
  name: "BarChart",
  components: {
    Highcharts,
  },
  data() {
    return {
      chartOptions: {
        chart: {
          type: "column", // Use "column" for bar chart
        },
        title: {
          text: "Crop Production by Country",
        },
        xAxis: {
          categories: ["USA", "China", "Brazil", "EU", "India", "Russia"],
          crosshair: true,
        },
        yAxis: {
          title: {
            text: "1000 metric tons (MT)",
          },
        },
        tooltip: {
          valueSuffix: " (1000 MT)",
        },
        series: [
          {
            name: "Corn",
            data: [406292, 260000, 107000, 68300, 27500, 14500],
          },
          {
            name: "Wheat",
            data: [51086, 136000, 5500, 141000, 107180, 77000],
          },
        ],
      },
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      try {
        const response = await axios.get(
          "http://localhost:3001/api/web?startDate=2023-04-01&endDate=2023-04-03"
        );
        const data = response.data;
        console.log(data);

        // Assuming data from API is properly formatted
        const categories = [
          ...new Set(data.map((item) => item.report_date)),
        ].sort();

        // Update chart options with fetched data
        this.chartOptions.xAxis.categories = categories;
        this.chartOptions.series[0].data = data.map((item) => item.value);

        // Set new chart options to trigger reactivity
        this.chartOptions = { ...this.chartOptions };
        console.log(this.chartOptions);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },
  },
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px; /* Set a desired height for the chart container */
}
</style>

App.vue

<template>
  <div id="app">
    <h1>Multiple Charts Example</h1>
    <BarChart />
  </div>
</template>

<script>
import BarChart from "./components/BarChart.vue";

export default {
  name: "App",
  components: {
    BarChart,
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

This is only rendering Multiple Charts Example and no chart.

What am I missing?

How to update a JSON file for a Playwright test

I have a JSON file that contains a value that I need to update as a step of a Playwright test as well as containing other values that need to remain unchanged. I have found a solution but it’s not working for me because it “Cannot file module {file}”. The file path I’m giving is definitely correct.

My json file is called temp.json and contains:

{
    "updateThis": "Original Value", 
    "dontUpdateThis": "Static Value"
}

This is the Playwright test:

const { test, expect } = require('@playwright/test');

const fs = require('fs')
const filename = 'tests/testdata/temp.json'
const data = require(filename);

test('update json key value', async() => {
    data.updateThis = "New Value"

    fs.writeFile(filename, JSON.stringify(data), function writeJSON() {
        console.log(JSON.stringify(data));
        console.log('writing to ' + fileName);
    })
})

Thanks

userscript (violentmonkey) script runs on first page, does not run on subsequent pages

I am trying to make a userscript that will open the invoices from Amazon in new tabs, so that I can try to categorize my spending better. It’s a PITA.

Here’s the link:
https://www.amazon.com/cpe/yourpayments/transactions

My script works on the first page, but when I press the “Next Page” button at the bottom and the script doesn’t run on the new pages. I’ve tried the different @run-at options but they don’t make a difference.

I think is due to some sort of dynamic generation or loading of the subsequent pages, but I don’t know how to hook that and I don’t seem to be phrasing my search terms in a way that I’m getting hints on how to help it.

// ==UserScript==
// @name        Open payment invoices in new tab
// @namespace   Violentmonkey Scripts
// @match       https://www.amazon.com/cpe/yourpayments/transactions*
// @grant       none
// @version     1.0
// @author      -
// @description 2/5/2024, 12:24:35 PM
// ==/UserScript==


var TargetLink = document.querySelectorAll('.a-span12 a');

var len = TargetLink.length;

for(var i=0; i<len; i++)
{
   TargetLink[i].setAttribute('target', '_blank');
}

Validation not shown

I am new to this forum and also to coding. I have to/want to make a Website with login and register for now and everything is working fine but the validation to show over the inputbox if something is missing or the passwords don’t match worked yesterday but now its broken.A YT video helped me with the code and i tried not to copy everything so it doesn’t look like i wanted to steal the code but even with the code that shown in the YT Video is not working. I thouht i changed the code so i got my old one from github but it’s not working either. Sorry for my bad english.
Is there something wrong with my validate.js file down below?
Thats the github for the other code https://github.com/lpeitz/WebsiteSchool

const validation = new JustValidate("#signup");

validation
    .addField("#name", [
        {
            rule: "required"
        }
    ])
    .addField("#email", [
        {
            rule: "required"
        },
        {
            rule: "email"
        },
        {
            validator: (value) => () => {
                return fetch("validate-email.php?email=" + encodeURIComponent(value))
                       .then(function(response) {
                           return response.json();
                       })
                       .then(function(json) {
                           return json.available;
                       });
            },
            errorMessage: "email already taken"
        }
    ])
    .addField("#password", [
        {
            rule: "required"
        },
        {
            rule: "password"
        }
    ])
    .addField("#password_confirmation", [
        {
            validator: (value, fields) => {
                return value === fields["#password"].elem.value;
            },
            errorMessage: "Passwords must match"
        }
    ])
    .onSuccess((event) => {
        document.getElementById("signup").submit();
    });
    
  

I tried everything in my power but i need help

Dynamically populate categories based on selected product type

Unable to access productTypeId inside foreach loop. In if (productType.Id == productTypeId)

 <select name="productType" id="productType" class="form-select">
     <option value="" selected>Choose Product Type...</option>
     @foreach (var productType in Model.ProductTypes)
     {
         <option value="@productType.Id">@productType.Name</option>
     }
 </select>

 <select name="category" id="category" class="form-select">
     <option value="" selected>Choose Category...</option>
 </select>

 <script>
     
     function populateCategories(productTypeId) {
         var categories = document.getElementById("category");
         categories.innerHTML = ""; 

         var defaultOption = document.createElement("option");
         defaultOption.text = "Choose Category...";
         defaultOption.value = "";
         categories.appendChild(defaultOption);
         
         var productTypeId;
         document.getElementById("productType").addEventListener("change", function () {
             var productTypeId = this.value;
             populateCategories(productTypeId); 
         });
     @foreach (var productType in Model.ProductTypes)
     {
         if (productType.Id == productTypeId)
         {
             @foreach (var category in productType.Categories)
             {
                 <text>
                                     var option = document.createElement("option");
                     option.text = "@category.Name";
                     option.value = "@category.Id";
                     categories.appendChild(option);
                 </text>
             }
         }
     }
         }

    
 </script>

I want to Access productTypeId inside foreach loop.OR is there Any other way of Dynamically populate categories.

how to fix height of scrollbar track

Need to fix the height of the scrollbar track and it should be starting with that blue colour only and the background should be of grey colour can you please guide me with the implementation.

I tried implementing without fixing the height and background colour as transparent.

Actual Expected
enter image description here enter image description here