HTTP request doesn’t works

I development a app web with MERN to upload information about stundents in a school, so, I make my backend with MongoDB and JS. For get the information about some studen, everything is good, but when i tried to update some information about the student, doesn’ update but the console.log appears the new information but not appers on the backend, this is my code where i try to update this information

import { useDispatch, useSelector } from "react-redux";
import { onLoadEvents3, onSetActiveEvent3, onUpdateEvent3 } from "../store";
import { systemApi } from "../api";
import Swal from "sweetalert2";

export const usePerDatStore = () => {
  const eventId = "64a5fc8e8f32a8a62adddf3b";
  const dispatch = useDispatch();

  const { event, activeEvent } = useSelector((state) => state.perdat);

  const setActiveEvent3 = (perdatEvent) => {
    console.log(perdatEvent);
    dispatch(onSetActiveEvent3(perdatEvent));
  };

  const startSavingEvent3 = async (perdatEvent) => {

    try {
      dispatch(onUpdateEvent3({...perdatEvent}));
      console.log("Data antes de entrar al backend", perdatEvent);
      const {data} = await systemApi.put(`/events/${eventId}`,perdatEvent);
      console.log("datos obtenidos del backend despues del put",data.evento.datos_personales);
      
      // Lógica adicional para guardar los datos editados en el backend
    } catch (error) {
      console.log(error);
      Swal.fire('Error al guardar', error.response.data.msg, 'error');
    }
  };

  const startLoadingEvents3 = async () => {
    try {
      const { data } = await systemApi.get(`/events/${eventId}`);
      const events = data.evento
     dispatch(onLoadEvents3(events));
    } catch (error) {
      console.log("Error al cargar el usuario");
      console.log(error);
    }
  };

  return {
    activeEvent,
    event,
    setActiveEvent3,
    startSavingEvent3,
    startLoadingEvents3,
  };
};

On my console.log appears the next output

perdatEvente output:

Data antes de entrar al backend 
{fname: 'Christian', snumber: '18400282', career: 'Mehcatronic', group: '11A', vinculacion: 'CETSA', …}
age: "26"
birth: "2001-09-09T01:30:00.000Z"
career: "Mehcatronic"
col: "El batan"
fname: "Christian"
gender: "Male"
group: "11A"
hnumber : "#2200"
mail:"[email protected]"
number:  "31113644888"
phone: "3111364"
snumber : "18400222282"
street: "Guadalupe Mero"
vinculacion: "CETSA"

This is the console.log from the data backend returns

data.event.datos_personales

    datos obtenidos del backend despues del put 
{fname: 'Christian', snumber: '18400282', career: 'Mehcatronic', group: '11A', vinculacion: 'CETSA', …}
age: "26"
birth: "2001-09-09T01:30:00.000Z"
career: "Mehcatronic"
col: "El batan"
fname: "Christian"
gender: "Male"
group: "11A"
hnumber: "#2200"
mail: "[email protected]"
number: "31113644888"
phone: "31113644800000000000000"
snumber: "18400222282"
street: "Guadalupe Mero"
vinculacion: "CETSA"

On the headers appears everything is good and the change is done but not.
If needed some more information or another code such as slice or PerDat.jsx please let me know.

I hope you can help me.
Regards.
y8.

How to know the correct nodejs package-name alternative to a vanilla javascript library?

TLDR

Given a downloaded vanilla javascript library file, how to locate the alternative in nodejs?
Some example mapping as below

js library nodejs package
sha256.js crypto-js
elliptic.js elliptic
Buffer.js buffer

Detail

I’m forking a git repo here where several javascript libraries was downloaded and used in a nodejs web app.

E.g. sha256.js file as imported here in javascript, the corresponding one for nodejs is crypto-js package as used here – this requires some tens of minute to figure it out

Some libraries will share same names for both; e.g. elliptic as used in js here and sample used in nodejs here

So what is the official way to map the package/library names between vanilla js and nodejs?


My google search on the topic results not helpful.

The similar post I could find is this one but that’s more specific in label-studio package


What I’ve been doing is the google search for the need

i.e.

gg nodejs {package name} alternative to {library name} in javascript

Or copy the usage js code and google search it for nodejs

gg js CryptoJS.SHA256() alternative for nodejs

And of course, that takes maybe hour to figure out, and that will happen for every new package needed to map.

leetcode twoSum algorithm javascript [duplicate]

Example 1:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation:
Because nums[0] + nums[1] == 9, we return [0, 1].

const twoSum = function(nums, target) {
  const map = {}
  for (let i=0; i<nums.length;i++) {
    if (map[target-nums[i]] !==undefined ) return [map[target-nums[i]],i]
    else map[nums[i]] = i
  }
}

Now my question is…

if (map[target-nums[i]] !==undefined ) return [map[target-nums[i]],i]

From the code above, when i first coded this, i wrote:

if (map[target-nums[i]]) return [map[target-nums[i]],i]. (without !==undefined)

Thinking that if i have the pair in the hashmap, it would work, but it did not work, and when i looked up the answer, i realized i had to write !==undefined. Why are these considered different?

Workarounds for detecting key presses outside a Javascript application in-browser

I am currently working on an HTML/Javascript doc that would run on a second monitor in browser while the user is outside the page in a different application. While the user would be able to tab into the page and make their inputs then, I would like there to be a functionality for them to do so while tabbed out of the page for accessibility, ideally via keyboard keys. However, I am aware that JS does not support event listeners like this while you are outside the page due to security concerns.

Essentially, I am asking whether there exists an easy workaround for this such as running a tertiary application which has the ability to listen to key press events tabbed out, and interfaces with the HTML/JS doc in browser (via inputs or command execution), and if so how would I set up such a system. I am relatively new to JS and even less experienced in other languages (bar MATLAB), so if a better method exists than this then that might be plan B

As said before, I know that JS by itself cannot handle key press event listeners outside the application, however I don’t know if a workaround is possible by using another application in the background. I also don’t know whether such an application is easily available, or whether I would need to programme it myself (and if so what language to use and how to do it). I’ve tried looking into something like this, but I couldn’t find anything.

Dubai Call Girls 0581950410 WhatsApp Call Girls In Dubai

Dubai Call Girls 0581950410 WhatsApp Call Girls In Dubai
Dubai Call Girls 0581950410 WhatsApp Call Girls In Dubai
Dubai Call Girls 0581950410 WhatsApp Call Girls In Dubai
Dubai Call Girls 0581950410 WhatsApp Call Girls In Dubai

Dubai Call Girls 0581950410 WhatsApp Call Girls In Dubai
Dubai Call Girls 0581950410 WhatsApp Call Girls In Dubai
Dubai Call Girls 0581950410 WhatsApp Call Girls In Dubai

Getting the forEach is not a function TypeError

I’m currently a student learning JavaScript and I’m trying to create an application that displays data according to user input. The data should be populated using JavaScript. But I keep getting a type error for the forEach on line 10. Please help! This is the code:

document.addEventListener('DOMContentLoaded', () => {
  
  const myKey = config.MY_KEY;
  const host = config.HOST;

  const url = 'https://realty-in-us.p.rapidapi.com/locations/v2/auto-complete?input=new%20york&limit=10';

  // Create elements for each city
  function homeList(data) {
    data.forEach(city => {
      const element = document.createElement('ul');
      element.textContent = city;
      document.getElementById('house-list').appendChild('li');
    })
  }
  
  // Fetch data from API
  fetch(url, {
    method: 'GET',
    headers: {
      'X-RapidAPI-Key': myKey,
      'X-RapidAPi-Host': host
    }
  })

  .then (res => res.json())
  .then (data => homeList(data))
  .catch(error => console.error(error));
});

React Router: Component doesn’t update on route change after login/logout

I’m working on a React application that utilizes React Router for routing and has an authentication system. After logging in or logging out, the route changes correctly, but the component doesn’t update/render until I manually refresh the page. Additionally, after logging out, a blank screen appears on the login route until I manually refresh the page, and then the login screen appears.

I’ve already tried the following:

  • Ensuring that the AuthProvider component wraps the entire
    application, including the routing.
  • Adding a unique key to the
    rendered component in the protected route.
  • Clearing the token from
    the localStorage upon logout.

Below is my code snippet

App.js

const App = () => {
  return (
    <Router>
      <AuthProvider>
        <Switch>
          <Route path="/login" component={Login} />
          <ProtectedRoute path="/admin" component={AdminDashboard} />
          <ProtectedRoute path="/" component={Home} />
        </Switch>
      </AuthProvider>
    </Router>
  );
};

PrivateRouter.js

const ProtectedRoute = ({ component: Component, ...rest }) => {
  const { isAuthenticated } = useContext(AuthContext);

  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated ? (
          <Component key={props.location.key} {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
};

Login.js

  const history = useHistory();
  const { isAuthenticated, setIsAuthenticated } = useContext(AuthContext);

  const handleLogin = (e) => {
    // Perform login logic, e.g., validate email and password
    // Assuming successful login for demonstration purposes
    localStorage.setItem("token", "your_token_here");
    setIsAuthenticated(true);

    console.log(isAuthenticated);
    history.replace("home");
  };
  return ( // jsx here // )


Unfortunately, none of these solutions have resolved the issue. I’ve also created a live demo on StackBlitz to showcase the problem. You can access it here: https://stackblitz.com/github/mehulk05/react-auth?file=src%2Fcomponents%2FLogin.jsx

Github: https://github.com/mehulk05/react-auth

Can anyone please help me understand why the component doesn’t update/render on route changes after login/logout, and why the login screen only appears after refreshing the page? Any insights or suggestions would be greatly appreciated.

Making scroll bar for canvas when scaling

I have a 3000 x 2000 picture.

so, canvas context size should be 3000 x 2000 , then the canvas size is 600 x 400.

This works well with scale x1 showing the picture correct ration and correct size(600,400).

However now, I want to scale this x2.

So, the upper-left half of image is shown in 600x400 but scroll bar is not appeared.

How can I make it ?

import React,{useState,useEffect,useRef} from 'react'


const TestCanvasPage = (props) =>{
    const ref_canvas_pic = useRef();
    useEffect(() =>{
        var chara = new Image();
        var ctx = ref_canvas_pic.current.getContext('2d');
        chara.src = "3000x2000.png";
        console.log(chara.src);
        ref_canvas_pic.current.width = 3000;
        ref_canvas_pic.current.height = 2000;
        chara.onload = () => { 
            ctx.clearRect(0, 0,ref_canvas_pic.current.width,ref_canvas_pic.current.height);
            ctx.drawImage(chara,0,0,
                ref_canvas_pic.current.width,
                ref_canvas_pic.current.height);  
        }
        ctx.scale(2,2); // make this scale x2
    });
    

    return (
            <canvas ref={ref_canvas_pic} style={{overflow:"scroll",width:"600px",height:"400px"}}></canvas>
    );    // I want scroll bar
}

export default TestCanvasPage;

Custom Tailwind CSS colors in chart.js

I have a React application that utilizes Chart.js for rendering charts. I want to customize the colors of labels in the chart using custom colors defined in my Tailwind CSS configuration. I have already set up custom colors in my tailwind.config.js and CSS files, but I’m unsure how to use these colors for my chart labels.

Here are the relevant components in my code:

index.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

.theme-light {
  --labelColor: #000000;
}

.theme-dark {
  --labelColor: #ffffff;
}

tailwind.config.js:

module.exports = {
  theme: {
    extend: {
      colors: {
        labelColor: 'var(--labelColor)',
      },
    },
  },
  plugins: [],
};

chart.jsx:

import React from 'react';
import { Bar } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);

const Graph = ({ chartData }) => {
  const options = {
    plugins: {
      legend: {
        display: true,
        labels: {
          usePointStyle: true,
          color: **labelColor**,
        }
      }
    },
    scales: {
      x: {
        ticks: {
          display: true,
          color: **labelColor**,
        }
      },
      y: {
        ticks: {
          display: true,
          color: **labelColor**,
        }
      }
    }
  }

  const datasets = [];

  chartData.forEach((data, index) => {
    datasets.push({
      label: data.name,
      data: data.data,
    });
  });

  const data = {
    labels: chartData[0].labels,
    datasets: datasets,
  }

  return <Bar data={data} options={options} />;
}

export default Graph;

Any suggestions on the most appropriate way to use custom Tailwind colors in this case?

Fixing chrome extion errors on rails

I have a rails app and all my chrome extensions are failing on it. What can be causing this ? I have bitwarden installed and the modal loads as a random black line. In the console i get this message DevTools failed to load source map: Could not load content for chrome-extension:// : System error: net::ERR_BLOCKED_BY_CLIENT for some other extensions.

I try fixing my app layout but nothign seems to change. The apps works fine is just the extensions.

The debugger of vscode is not working(variables,watch, call stack), the “call stack” will appear but stop suddenly

The debugger of vscode is not working(variables,watch, call stack), the result of the console.log() appear in terminal and the “call stack” will appear but stop suddenly.

enter image description here

my launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\src\index.ts",
            "console": "integratedTerminal",
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ]
        }
    ]
}

my code

let nome: string = "brother"
let age : number = 20
if(age<100){
    age +=10
}
console.log(age)

Restart the vscode and Uninstall python extension

ES6 ${variable name} does not work in console.log [closed]

Why ${variable} is not working inside a console.log statement? Also, is there any alternative?

I am trying the below code where count is a variable.

console.log('Address ${count} balance: ', await getBalances(address));

The output I am getting is:
Address ${count} balance

I expect the outcome as:
Address 1 balance
Address 2 balance

Recharts data doesn’t load unless I hit ctrl+s

I created a LineChart using recharts and I’m pulling data using axios from a db.json file hosted locally by json-server. Every time I load the page or reload the chart doesn’t show up. Only when I hit ctrl+s to save my file and trigger re-render does the chart show up. How do I get the chart to show up on initial page load?

I used Vite with SWC to initialize the project and versions are: [email protected], [email protected], [email protected]

Chart code:

<ResponsiveContainer width="100%" height={270}>
        <LineChart
          width={600}
          height={300}
          data={monthlyData}
          margin={{
            left: -20,
          }}
        >
          <CartesianGrid vertical={false} />
          <Tooltip />
          <XAxis axisLine={false} dataKey="name" tickSize={0} tickMargin={10} />
          <YAxis
            axisLine={false}
            domain={[0, maxY]}
            tickCount={maxY / 100 + 1}
            tickSize={0}
            tickMargin={10}
          />
          <Line
            type="monotone"
            dataKey="user"
            strokeWidth={2}
            stroke="#9BDD7C"
            dot={false}
          />
          <Line
            type="monotone"
            dataKey="guest"
            strokeWidth={2}
            stroke="#E9A0A0"
            dot={false}
          />
        </LineChart>
      </ResponsiveContainer>

White bar appearing on mobile view of my HTML/CSS/JS website

I am encountering a issue with my website, and I would greatly appreciate your expertise in helping me resolve it. When viewing my site on mobile devices (starting when I go below 608px), a white bar appears on the side of the screen, however, everything appears fine on desktop view. I created the website using HTML, CSS, and JavaScript. I have deployed the site on Netlify, and you can access it at the following link: https://ais-test-site.netlify.app/

I have spent considerable time troubleshooting this issue, but I have been unable to identify the root cause. I suspect there might be some CSS or viewport-related settings that I am missing. Unfortunately, my limited knowledge in this area has prevented me from finding a solution.

If anyone has encountered a similar problem or has expertise in mobile responsiveness and can offer some guidance, it would be helpful.

Thank you in advance for your assistance!

https://ais-test-site.netlify.app/

I tried the following:

  1. Inspecting the site on chrome
  2. Inspecting the grids
  3. Checking to see if I hard coded a specific width on any section
  4. Deleting and retyping sections of the code
  5. Adding overflow and overflow-x as hidden
  6. Tried setting if because I used both grid and flex it caused it but my knowledge is limited
  7. Inspecting and messing around with the media queries
  8. Finally checking to see if the js was the cause by again but my knowledge is limited so I may have missed something

(Webpack 5) Error: Plugin/Preset files are not allowed to export objects, only functions

I upgrade my webpack version from 4 to 5 and I found out that there are several loaders that I need to reinstall. After I install babel-loader and run npm run start , my console pops up this error below:

node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

Error: Plugin/Preset files are not allowed to export objects, only functions. In /Users/jessiechen/Desktop/Sampling_frontend/node_modules/babel-preset-stage-0/lib/index.js
    at createDescriptor (/Users/jessiechen/Desktop/Sampling_frontend/node_modules/@babel/core/lib/config/config-descriptors.js:159:11)
    at createDescriptor.next (<anonymous>)
    at step (/Users/jessiechen/Desktop/Sampling_frontend/node_modules/gensync/index.js:261:32)
    at evaluateAsync (/Users/jessiechen/Desktop/Sampling_frontend/node_modules/gensync/index.js:291:5)
    at /Users/jessiechen/Desktop/Sampling_frontend/node_modules/gensync/index.js:44:11
    at Array.forEach (<anonymous>)
    at Function.async (/Users/jessiechen/Desktop/Sampling_frontend/node_modules/gensync/index.js:43:15)
    at Function.all (/Users/jessiechen/Desktop/Sampling_frontend/node_modules/gensync/index.js:216:13)
    at Generator.next (<anonymous>)
    at createDescriptors (/Users/jessiechen/Desktop/Sampling_frontend/node_modules/@babel/core/lib/config/config-descriptors.js:101:41)

This is my package.json file

{
  "scripts": {
    "start": "webpack-dev-server --open",
    "build": "webpack --mode production"
  },
  "dependencies": {
    "@babel/runtime": "^7.22.6",
    "@fortawesome/fontawesome-free": "^6.4.0",
    "@popperjs/core": "^2.11.8",
    "bootstrap": "^5.3.0",
    "bootstrap-icons": "^1.10.5",
    "regenerator-runtime": "^0.13.11",
    "style-loader": "^3.3.3",
    "vee-validate": "^2.2.8",
    "vue": "^2.6.10",
    "vue-router": "^3.1.3",
    "vuex": "^3.1.2",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1",
    "xlsx": "^0.18.5"
  },
  "devDependencies": {
    "@babel/core": "^7.22.9",
    "@babel/plugin-transform-runtime": "^7.22.7",
    "@babel/preset-env": "^7.22.9",
    "babel-core": "^6.26.0",
    "babel-loader": "^9.1.3",
    "babel-preset-env": "^1.6.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-preset-vue": "^2.0.2",
    "css-loader": "^3.3.2",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.5.3",
    "install": "^0.13.0",
    "npm": "^9.8.0",
    "path": "^0.12.7",
    "vue-loader": "^14.2.3",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^5.88.1"
  }
}

This is my webpack.config.js file

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    resolve: {
        extensions: ['.js', '.jsx','.vue', '.css'],
        modules: [
            'node_modules'
        ]  
    },
    module: {
        rules: [
            {
                test: /.vue?$/,
                exclude: /(node_modules)/,
                use: 'vue-loader'
            },
            {
                test: /.js?$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            },
            {
                test: /.css$/i,
                use: [{loader:'style-loader'}, {loader: 'css-loader'}],
            },
            {
                test: /.(png|jpe?g|gif)$/i,
                use: [
                  {
                    loader: 'file-loader',
                    options: {
                        esModule: false
                    }
                  },
                ],
            },
        ]
    },
    plugins: [new HtmlWebpackPlugin({
        template: './src/index.html'
    })],
    devServer: {
        historyApiFallback: true
    },
    externals: {
        // global app config object
        config: JSON.stringify({
            apiUrl: 'http://localhost:4000'
        })
    },
}

I’ve tried to adjust my webpack into this below but this version still not working the same error keeps popping up:

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    resolve: {
        extensions: ['.js', '.jsx','.vue', '.css'],
        modules: [
            'node_modules'
        ]  
    },
    module: {
        rules: [
            {
                test: /.vue?$/,
                exclude: /(node_modules)/,
                use: 'vue-loader'
            },
            {
                test: /.js?$/,
                exclude: /(node_modules)/,
                use: {
                    loader: 'babel-loader',
                    options:{
                        presets: [
                            ['@babel/preset-env', { targets: "defaults" }]
                        ],
                        plugins: ['@babel/plugin-proposal-class-properties']
                    }
                }
            },
            {
                test: /.css$/i,
                use: [{loader:'style-loader'}, {loader: 'css-loader'}],
            },
            {
                test: /.(png|jpe?g|gif)$/i,
                use: [
                  {
                    loader: 'file-loader',
                    options: {
                        esModule: false
                    }
                  },
                ],
            },
        ]
    },
    plugins: [new HtmlWebpackPlugin({
        template: './src/index.html'
    })],
    devServer: {
        historyApiFallback: true
    },
    externals: {
        // global app config object
        config: JSON.stringify({
            apiUrl: 'http://localhost:4000'
        })
    },
}