What’s currently the best way to get onKeyUp events on Chrome in Android?

keyUp is not supported on Android Chrome due to using a virtual keyboard. e.key will always be Undefined, and e.keyCode will always be 229 no matter which key you use. This feature is depreciated https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event .

I want to know which key a user has done “keyUp” on last. What I have seen as proposed solutions are hacks, for example, if a user is using a textarea, just get the last character of the textarea target value. But these are not true solutions, if a user is editing the middle of a paragraph in a textarea, then this method will not work.

In modern Android Chrome browsers, what is the preferred way of getting a keyUp event?

Is there a way to set a cookie using JS and force a dynamic element reliant on the cookie to update without reloading the page?

apologies if the title question is confusing, but I’m not entirely sure how to ask or phrase this. Basically, I want a button to trigger (it opens a popup) on page load—easy enough.

However, the button is a “Find a Location” thing, so upon a user’s first-time (or cookie-less) visit, they see that button. If the user clicks it and inputs their location info, they get redirected to a page, and the button changes to one displaying their location, and the popup content also changes; the button gets fed a stored cookie with the location info, which is how the content updates.

I need to figure out a way to get this location info, via this cookie, injected on page load without the user having to enter their information at all, OR refreshing/navigating away from the page.

Right now, I have a function written to set the cookie upon load, and then automatically trigger the popup, but the button does not automatically update via the manual cookie setting unless the user reloads the page. I need everything to happen in one seamless motion. Is this feasible, or no?

I need to do this via Javascript, if it is even possible—no other methods, please. Also, this is not something I can do via the site’s back end or some CMS either.

Thanks.

When a node is created in JavaScript the value property is not updating [closed]

I am trying to make a sign-in system, and currently I am just using document.createElement('input') to create the input element then appending it to the container element.

But, when I try to access the value property later, it is not updating. I am really confused because when I select the input element in the Elements panel and then type $0.value in the console, the value is correct. It turns out inputElementCreatedInJavascript != $0. Shouldn’t they be the same object?!?

I have no idea how to solve this problem – I always thought that all referneces to an element were the same. Can someone explain this to me?!?

useSearchParams() should be wrapped in a suspense boundary at page

How can I add the Suspense tags to the following code :-

"use client";

import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense } from 'react'

import Form from "@components/Form";

const UpdatePrompt = () => {
    const router = useRouter();
    const searchParams = useSearchParams();
    const promptId = searchParams.get("id");

    const [post, setPost] = useState({ prompt: "", tag: "", });
    const [submitting, setIsSubmitting] = useState(false);

    useEffect(() => {
        const getPromptDetails = async () => {
            const response = await fetch(`/api/prompt/${promptId}`);
            const data = await response.json();

            setPost({
                prompt: data.prompt,
                tag: data.tag,
            });
        };

        if (promptId) getPromptDetails();
    }, [promptId]);

    const updatePrompt = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);

        if (!promptId) return alert("Missing PromptId!");

        try {
            const response = await fetch(`/api/prompt/${promptId}`, {
                method: "PATCH",
                body: JSON.stringify({
                    prompt: post.prompt,
                    tag: post.tag,
                }),
            });

            if (response.ok) {
                router.push("/");
            }
        } catch (error) {
            console.log(error);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Suspense>
            <Form
                type='Edit'
                post={post}
                setPost={setPost}
                submitting={submitting}
                handleSubmit={updatePrompt}
            />
        </Suspense>
    );
};

export default UpdatePrompt;

I tried adding it in the return statement but during deployment in Vercel this error showed :-
Error:
x Unexpected token. Did you mean {'}'} or &rbrace;?
,-[/vercel/path0/app/update-prompt/page.jsx:63:1]

Can someone help me in adding the Suspense tags in the above code. Thanks in Advance!

Why Webview2 set value of an input element but value desapears after submiting the form as never had been set?

I’m calling ExecuteScriptAsync and pass a script that find an input element and set its value. After I submit the form, the site behaves like there isn’t any text in the input. Clicking in the submit button, the text desapears. Clicking into the input element, same occurs. See the code below.

await webView.CoreWebView2.ExecuteScriptAsync("var obj = document.evaluate("//descendant::input[@placeholder='Type the code']", document,  null,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; if (obj != undefined && obj != null) {obj.value='AP37060';}");

The text is changed, but it seems as nothing is there. Can somebody help me? Thanks.

AgGrid: Column Headers Misalign when scrolling down through table body

I am using React AgGrid. I have a table that contains about 25 rows and 10 columns with headers and sub-headers.

When I scroll all the way the to top right of the grid and then scroll down to the point where the column headers start to stay fixed and float down the screen and I scroll down, the column headers become misaligned (see attached screencaps).

I’ve tried removing columns from the column defs and it doesn’t seem to be a specific column that is causing the issue, but rather the way the grid is handling positioning the column headers.

Some potential hints.

  1. I have a sidebar nav next to the table. When I comment that out, the column defs don’t shift over as much when I scroll down.

  2. When I remove the left and right padding from the grid, it also doesn’t shift over as much.

  3. When I do both 1 and 2, the grid columns behave correctly.

How do you convert jquery function to vanilla Javascript? [closed]

I am new to javascript and have a small snippet of code that I want to convert from jQuery to Javascript. Any pointers or can someone help?

A little background on the code – this is a function to toggle between tabs that populates different content when toggled. Here is the code:

  $("document").ready(function () {
    $(".tab-slider--body").hide();
    $(".tab-slider--body:first").show();
  });
  var tabSlider = document.querySelectorAll(".tab-slider--nav li");

  $(".tab-slider--nav li").click(function () {
    $(".tab-slider--body").hide();
    var activeTab = $(this).attr("rel");
    $("#" + activeTab).fadeIn();
    if ($(this).attr("rel") == "tab2") {
      $(".tab-slider--tabs").addClass("slide");
    } else {
      $(".tab-slider--tabs").removeClass("slide");
    }
    $(".tab-slider--nav li").removeClass("active");
    $(this).addClass("active");
  });

How can the omnibox suggestions be styled in Firefox?

I built an extension for Chrome, which I want to use in Firefox. In chrome one can style suggestions using XML-syntax.

Screenshot from Chrome: Example of how the styling looks in chrome

I couldn’t find anything for Firefox and was wondering whether it was possible, and if so, how? If it’s not possible, are there plans to implement this?

I found these three documentation pages and the omnibox extension example.

beforeEach on Mocha does not reset object

I have the following in state.js:

var state = {};

function getState() {
  return state;
}

function setItem(key, value) {
  state[key] = value;
}

function resetState() {
  state = {};
}

exports.getState = getState;
exports.setItem = setItem;
exports.resetState = resetState;

In my Mocha test file, I have the following:

const { getState, setItem, resetState } = require("./state");
var assert = require("assert");

describe("...", function () {
    beforeEach(function() {
      resetState();
    })

    it("Case 1", function (done) {
      setItem("a", "b");
      assert.equal(JSON.stringify(getState()), JSON.stringify({"a": "b"}));
      done();
    });

    it("Case 2", function (done) {
      setItem("x", "y");
      assert.equal(JSON.stringify(getState()), JSON.stringify({"x": "y"}));
      done();
    });
});

Unfortunately, Case 2 fails because it looks like the resetState() function does not work here even though I’m calling it in beforeEach. What am I doing wrong?

Webpack served application not handling bundle.js file correctly

I have an application that uses module federation and webpack. Everything is working fine when I deploy the application locally to a nginx docker image. However, when the pipeline runs and I access it from the browser from its dev URL, I can see that the bundle.js and remoteEntry.js files have the content of index.html. So my page is rendered blank. Here is a screenshot, side by side, of both local and deployed applications sources:

enter image description here

This is my first time using webpack, so I don’t know what exactly is missing. Below is my webpack.config:

const HtmlWebPackPlugin = require("html-webpack-plugin");
const { ModuleFederationPlugin } = require("webpack").container;

const path = require("path");
const deps = require("./package.json").dependencies;

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./public/index.html",
  filename: "./index.html",
});

module.exports = {
  mode: "development",
  entry: "./src/index.tsx",
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
    modules: [path.resolve(__dirname, "src"), "node_modules"],
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
    publicPath: "mfe-prompt/", //This line only exists on the pipe. Locally, I have the exact same file without this single line
  },
  devServer: {
    static: path.join(__dirname, "dist"),
    port: 3000,
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
  },
  module: {
    rules: [
      {
        test: /.(ts|tsx|js)$/,
        exclude: /node_modules/,
        loader: "ts-loader",
      },
      {
        test: /.s[ac]ss$/i,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
    ],
  },
  plugins: [
    htmlPlugin,
    new ModuleFederationPlugin({
      name: "prompt_mfe",
      filename: "remoteEntry.js",
      exposes: {
        "./Prompt": "./src/containers/Prompt/Prompt.tsx",
      },
      shared: {
        ...deps,
        react: { singleton: true, eager: true, requiredVersion: deps.react },
        "react-dom": {
          singleton: true,
          eager: true,
          requiredVersion: deps["react-dom"],
        },
        "react-router-dom": {
          singleton: true,
          eager: true,
          requiredVersion: deps["react-router-dom"],
        },
        "@dds/react": {
          singleton: true,
          eager: true,
          requiredVersion: deps["@dds/react"],
        },
        "prop-types": {
          singleton: true,
          eager: true,
          requiredVersion: deps["prop-types"],
        },
      },
    }),
  ],
};

Don’t know if its useful, but this is my nginx conf:

worker_processes 4;

events {
    worker_connections 1024;
}

http {
    server {
        listen 80;
        root /usr/share/nginx/html;
        include /etc/nginx/mime.types;
        
        location / {
            root /usr/share/nginx/html;
            index index.html;
            try_files $uri $uri/ /index.html;
        }
    }
}

ParcelJS: Error: Does not have node 17172 when running dev server

seem to having an issue with ParcelJS. It was working and the build compiling with no issues. Went to restart the development server and now have an issue and it wont work. It throws the following error:

Error: Does not have node 17172
    at RequestGraph._assertHasNodeId (/Users/ollienorris/Documents/gsap-test/node_modules/@parcel/graph/lib/Graph.js:449:13)
    at RequestGraph.getNodeIdsConnectedTo (/Users/ollienorris/Documents/gsap-test/node_modules/@parcel/graph/lib/Graph.js:77:10)
    at RequestGraph.respondToFSEvents (/Users/ollienorris/Documents/gsap-test/node_modules/@parcel/core/lib/RequestTracker.js:459:26)
    at loadRequestGraph (/Users/ollienorris/Documents/gsap-test/node_modules/@parcel/core/lib/RequestTracker.js:873:18)
    at async RequestTracker.init (/Users/ollienorris/Documents/gsap-test/node_modules/@parcel/core/lib/RequestTracker.js:822:17)
    at async Parcel._init (/Users/ollienorris/Documents/gsap-test/node_modules/@parcel/core/lib/Parcel.js:188:28)
    at async Parcel.watch (/Users/ollienorris/Documents/gsap-test/node_modules/@parcel/core/lib/Parcel.js:260:7)
    at async run (/Users/ollienorris/Documents/gsap-test/node_modules/parcel/lib/cli.js:283:9)

I have had a Google of the issue, but there doesn’t seem to be anything there to help me fix the issue.

Any help would be appreciated!

Am getting “Cannot set property .. which has only a getter” error (javascript canvas width)

More completely, I got:
“Cannot set property clientWidth of #<Element> which has only a getter”
(Obviously I could have had a HTML <canvas> element, but this is a minimized example of my problem.)

But I found a solution: Instead of creating elements and appending, write a string of the HTML I want and use innerHTML = string. Is there a disadvantage in doing this?
Change ‘true’ to ‘false’ in the code to demo the solution:

<html>
  <head>
    <meta charset="utf-8">
    <style>
canvas { outline:1px dotted black; } 
    </style>
  </head>
  <body>
    <script>
  "use strict";
  if (true) { // this code has the error
    let elt = document.createElement('canvas');
    elt.setAttribute('id','canvas');
    elt.clientWidth = 500;
    elt.clientHeight = 500;
    document.body.appendChild(elt);
  } else {    // this has the workaround/solution
    let s = '<canvas id="canvas" width="500" height="500"></canvas>';
    document.body.innerHTML = s;
  }
  let ctx = canvas.getContext("2d");
  ctx.arc(250,250,200, 0, 6.2832);
  ctx.stroke();
    </script>
  </body>
</html>

How to send this data to Database using Express and MongoDB and React Native ? Issue with Sending Data to Backend Endpoint in React Native

I’m encountering an issue with sending data from my React Native frontend to a backend endpoint. I’ve provided the relevant code snippets below.I’m encountering an issue with sending data from my React Native frontend to a backend endpoint (/onboarding/v3). Below, I’ve provided relevant code snippets and additional details about my setup.

enter image description here

User Model:

I’m using a MongoDB database with Mongoose to define my user schema. The schema includes fields for name, email, password, and various other user details. Of particular relevance to this issue is the areasOfInterest field, which is an array of objects containing title and items properties.

I have a React Native component AreasOfInterest where users select their areas of interest and rate their expertise. Upon pressing a “Next” button, I want to send this data to the backend.

I would appreciate any guidance on how to properly format the data and resolve the issue with sending it to the backend endpoint. I’ve included relevant code snippets below for reference.

Backend Endpoint:

I have a backend endpoint /onboarding/v3

Please fix my code
My User Model is below. after it

const mongoose = require("mongoose");

// Define schema for items within an area of interest
const InterestItemSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  stars: {
    type: Number,
    min: 1,
    max: 5,
    default: 1, // Default to 1 star
  },
});

// Define schema for areas of interest
const InterestSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  items: {
    type: [InterestItemSchema],
    default: [],
  },
});

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  image: {
    type: String,
    required: true,
  },
  friendRequests: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
  ],
  friends: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
  ],
  sentFriendRequests: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
  ],
  First_Name: {
    type: String,
    default: "",
  },
  Last_Name: {
    type: String,
    default: "",
  },
  Pronoun: {
    type: String,
    default: "",
  },
  Gender: {
    type: String,
    default: "",
  },
  Race: {
    type: String,
    default: "",
  },
  Country: {
    type: String,
    default: "",
  },
  State: {
    type: String,
    default: "",
  },
  City: {
    type: String,
    default: "",
  },
  Role: {
    type: String,
    default: "",
  },
  Student: {
    type: Boolean,
    default: false,
  },
  Mentor: {
    type: Boolean,
    default: false,
  },
  Affiliation: {
    type: String,
    default: "",
  },
  Headline: {
    type: String,
    default: "",
  },
  Education: {
    type: String,
    default: "",
  },
  Major: {
    type: String,
    default: "",
  },
  Degree: {
    type: String,
    default: "",
  },
  GradeYear: {
    type: String,
    default: "",
  },
  areasOfInterest: {
    type: [InterestSchema],
    default: [],
  },
  Career_Goals: {
    type: [String],
    default: [],
  },
  withOrgOnly: {
    type: Boolean,
    default: false,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  updatedAt: {
    type: Date,
    default: Date.now,
  },
});

const User = mongoose.model("User", userSchema);

module.exports = User;

// Backend Endpoint (Working (not sure about onboarding/v3) )

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcrypt");
const os = require("os");
const app = express();
const morgan = require("morgan");
const port = 8080;
const cors = require("cors");
const router = express.Router();

app.use(morgan("dev"));
app.use(cors());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(passport.initialize());
const jwt = require("jsonwebtoken");

const User = require("./models/user");

// POST endpoint for onboarding/v3
app.post("/onboarding/v3", async (req, res) => {
  try {
    const { userId, areasOfInterest } = req.body;

    const user = await User.findById(userId);
    console.log(user.name);
    console.log(areasOfInterest);
    if (!user) {
      return res.status(404).json({ message: "User not found" });
    }

    user.areasOfInterest = areasOfInterest;

    await user.save();

    res.status(200).json({ message: "Areas of interest updated successfully" });
  } catch (err) {
    console.log("Error updating areas of interest", err);
    res.status(500).json({ message: "Error updating areas of interest" });
  }
});

// Frontend Main Page.

import React, { useState, useContext } from "react";
import {
  View,
  Text,
  SafeAreaView,
  TextInput,
  TouchableOpacity,
  FlatList,
} from "react-native";
import Icon from "react-native-vector-icons/FontAwesome5";
import { CheckBox } from "react-native-elements";
import { AntDesign } from "@expo/vector-icons";
import axios from "axios";
import { UserType } from "../../UserContext";

const NavigationLine = ({ active }) => (
  <View
    style={{
      flex: 1,
      height: 5,
      backgroundColor: active ? "#57D5DB" : "#DBD4D4",
      marginHorizontal: 5,
    }}
  />
);

const InterestList = ({ data }) => {
  const [expanded, setExpanded] = useState(false);
  const [ratings, setRatings] = useState(Array(data.items.length).fill(0));
  const [selectedItems, setSelectedItems] = useState(
    Array(data.items.length).fill(false)
  );

  const handleRatingChange = (index, rating) => {
    const newRatings = [...ratings];
    newRatings[index] = rating;
    setRatings(newRatings);
  };

  const toggleCheckbox = (index) => {
    const newSelectedItems = [...selectedItems];
    newSelectedItems[index] = !selectedItems[index];
    setSelectedItems(newSelectedItems);
    // Reset rating to 0 when unchecking the checkbox
    if (!newSelectedItems[index]) {
      handleRatingChange(index, 0);
    }
  };
  return (
    <View>
      <TouchableOpacity
        onPress={() => setExpanded(!expanded)}
        style={{
          flexDirection: "row",
          alignItems: "center",
          backgroundColor: "#F1F1F3",
          width: "90%",
          height: 50,
          borderRadius: 20,
          marginTop: 15,
          paddingHorizontal: 20,
          borderColor: "#D9D9D9",
          borderWidth: 1,
          marginHorizontal: 15,
        }}
      >
        <Icon
          name={expanded ? "caret-down" : "caret-right"}
          size={15}
          color="#9C9C9C"
        />
        <Text style={{ flex: 1, marginLeft: 10 }}>{data.title}</Text>
      </TouchableOpacity>
      {expanded && (
        <FlatList
          data={data.items}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({ item, index }) => (
            <View
              style={{
                flexDirection: "row",
                alignItems: "center",
                backgroundColor: "#F1F1F3",
                width: "90%",
                height: 50,
                borderRadius: 20,
                marginTop: 5,
                marginHorizontal: 15,
                borderWidth: 0.1,
              }}
            >
              <TouchableOpacity
                onPress={() => toggleCheckbox(index)}
                style={{ marginLeft: 20, marginRight: 10 }}
              >
                <Icon
                  name={selectedItems[index] ? "check-square" : "square"}
                  size={20}
                  color="#000"
                />
              </TouchableOpacity>
              <View style={{ flex: 1 }}>
                <Text style={{ fontSize: 13 }}>{item}</Text>
              </View>
              {selectedItems[index] && ( // Show stars only if checkbox is selected
                <View style={{ flexDirection: "row", marginRight: 20 }}>
                  {[1, 2, 3, 4, 5].map((star) => (
                    <TouchableOpacity
                      key={star}
                      onPress={() => handleRatingChange(index, star)}
                      style={{ marginRight: 4 }}
                    >
                      <AntDesign
                        name="star"
                        size={20}
                        color={ratings[index] >= star ? "#FFD700" : "#D3D3D3"}
                      />
                    </TouchableOpacity>
                  ))}
                </View>
              )}
            </View>
          )}
        />
      )}
    </View>
  );
};

const AreasOfInterest = ({ navigation }) => {
  // Use userId to send backend
  const { userId, setUserId } = useContext(UserType);
  const interestData = [
    {
      title: "Accounting",
      items: [
        "Financial Accounting",
        "Cost Accounting",
        "Managerial Accounting",
        "Auditing",
        "Tax Accounting",
        "Forensic Accounting",
      ],
    },
    {
      title: "Finance",
      items: [
        "Investment Management",
        "Financial Risk Management",
        "Corporate Finance",
        "Public Finance",
        "Personal Finance",
      ],
    },
    {
      title: "Human Resources",
      items: [
        "Learning & Development",
        "Performance Management",
        "HR Information Systems",
        "Compensation & Benefits",
        "Recruiting & Staffing",
        "Organizational Structure",
        "Employee & Labor Relations",
        "Diversity Equity & Inclusion",
      ],
    },
    {
      title: "Information Technology",
      items: [
        "Systems Security",
        "Data Management",
        "IT Management",
        "Network Administration",
        "Software Development",
        "Web Development",
      ],
    },
    {
      title: "Legal",
      items: [
        "Litigation",
        "Risk Management",
        "Contract Law",
        "Import/Export Law",
        "Compliance Policies & Procedures",
        "Property Law",
        "Intellectual Property Law",
        "Employment Law",
        "Ethics",
        "Law Enforcement",
        "Criminal Justice",
      ],
    },
    {
      title: "Manufacturing",
      items: [
        "Plant Management",
        "Fabrication & Machining",
        "Reliability & Asset Management",
        "Procurement",
        "Distribution",
        "Production Installation",
      ],
    },
    {
      title: "Operations",
      items: [
        "Improve Processes",
        "LEAN & Six Sigma",
        "Production Planning & Control",
        "Quality Management",
        "Supply Chain Management",
        "Design Process",
      ],
    },
    {
      title: "Marketing & Communication",
      items: [
        "Sales Support",
        "Marketing Communications",
        "Advertising Strategy",
        "Pricing Strategy",
        "Market Research",
        "Social Media Strategy",
        "Brand Management",
        "Copy & Content Creation",
        "Imaging/Graphics",
      ],
    },
    {
      title: "Sales",
      items: [
        "Capture Management",
        "Building a Book of Business",
        "Channel Strategy",
        "Sales Forecasting",
        "Enterprise Sales",
        "Inside Sales",
        "Objection Handling",
        "Business Development",
      ],
    },
    {
      title: "Management",
      items: [
        "Delegation",
        "Emotional Intelligence",
        "Improve Processes",
        "Product Management",
        "Project Management",
        "Decision Making",
        "Negotiation Skills",
        "Develop Others",
        "Change Management",
        "Priority Management",
        "Effective Communication",
        "Conflict Management",
      ],
    },
    {
      title: "Leadership",
      items: [
        "Team Building",
        "Shaping Culture",
        "Setting Vision & Strategy",
        "Strategic Thinking",
        "Product Development",
        "Service Development",
        "Value Creation",
      ],
    },
    {
      title: "Healthcare",
      items: [
        "Dentistry",
        "Health Sciences",
        "Physician",
        "Veterinarian",
        "Pharmacist",
        "Healthcare Management",
        "Patient Care",
      ],
    },
    {
      title: "Education",
      items: [
        "Teaching",
        "Education Administration",
        "School Counseling",
        "Curriculum Development",
      ],
    },
    {
      title: "Consulting",
      items: [
        "Management Consulting",
        "Corporate Consulting",
        "Independent Consulting",
      ],
    },
    {
      title: "Government & Public Administration",
      items: [
        "Revenue & Taxation",
        "Law Enforcement",
        "Public Management & Administration",
        "Environmental & Resource Planning",
        "National Security",
        "Governance",
      ],
    },
    {
      title: "Customer Service",
      items: [
        "Customer Retention",
        "Customer Management",
        "Customer Support",
        "SaaS Customer Experience",
      ],
    },
    {
      title: "Engineering",
      items: [
        "Civil Engineering",
        "Chemical Engineering",
        "Mechanical Engineering",
        "Electrical Engineering",
        "Industrial Engineering",
        "Aerospace Engineering",
        "Biomedical Engineering",
        "Environmental Engineering",
        "Computer Engineering",
        "Materials/Textiles Engineering",
        "Nuclear Engineering",
        "Architecture",
      ],
    },
    {
      title: "Sciences",
      items: [
        "Agricultural Science",
        "Social Science",
        "Biology",
        "Chemistry",
        "Political Science",
        "Physics",
        "Psychology",
        "Mining & Petroleum",
      ],
    },
    {
      title: "Social Services",
      items: [
        "Therapists",
        "Probation Officer",
        "Rehabilitation Counselor",
        "Career Counselor",
        "Social Worker",
        "Substance Abuse Counselor",
        "Mental Health Counselor",
        "Clergy",
      ],
    },
    {
      title: "Creative / Design",
      items: [
        "Creative Arts",
        "Graphic Design",
        "Interior Design",
        "Product Design",
        "User Experience",
      ],
    },
  ];

  const [initialInterestData, setInitialInterestData] = useState([]);
  // Search Logic
  // TODO: Later Search Logic
  // Handle Next
  const handleNext = async () => {
    try {
      // Construct the data object to send
      const dataToSend = initialInterestData.map((interest) => ({
        title: interest.title,
        selectedItems: interest.items
          .filter((item, index) => selectedItems[index])
          .map((item, index) => ({
            name: item,
            rating: ratings[index],
          })),
      }));
      console.log(dataToSend);
      // Make the HTTP request to the backend API
      const response = await axios.post(
        "http://172.20.10.3:8080/onboarding/v3",
        dataToSend
      );

      // Handle response as needed (e.g., show success message, navigate to next screen)
      console.log("Response from backend:", response.data);
      navigation.navigate("Career"); // Navigate to the next screen
    } catch (error) {
      // Handle error (e.g., show error message)
      console.error("Error sending data to backend:", error);
    }
  };

  return (
    // Margin Top is missing in this. i want same level of margin as my previous pages.
    <SafeAreaView style={{ flex: 1, alignItems: "center", marginTop: 40 }}>
      <TouchableOpacity
        onPress={() => {
          navigation.goBack();
        }}
        style={{
          position: "absolute",
          top: 3,
          left: 20,
          justifyContent: "center",
          alignItems: "center",
          flexDirection: "row",
        }}
      >
        <Icon name="chevron-left" size={24} color="#000" />
      </TouchableOpacity>
      <Text style={{ fontWeight: "bold", fontSize: 20, marginBottom: 5 }}>
        Areas of Interest
      </Text>
      <View style={{ width: 400, height: 1.5, backgroundColor: "#DBD4D4" }} />

      <FlatList
        data={interestData}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => <InterestList data={item} />}
        ListHeaderComponent={() => (
          <>
            <Text
              style={{ fontSize: 17, marginTop: 10, paddingHorizontal: 15 }}
            >
              Select areas of interest and rate your expertise in each to
              receive personalized mentoring recommendations. Rate your
              expertise with the star system (1 - 5) to establish your
              proficiency.
            </Text>
            <Text
              style={{
                fontSize: 11,
                color: "#9C9C9C",
                textAlign: "left",
                marginTop: 10,
                paddingHorizontal: 15,
              }}
            >
              Your ratings are confidential and not displayed on your profile.
              We recommend selecting at least 3 options.
            </Text>

            <View
              style={{
                flexDirection: "row",
                alignItems: "center",
                backgroundColor: "#F1F1F3",
                width: "90%",
                height: 50,
                borderRadius: 20,
                marginTop: 15,
                paddingHorizontal: 20,
                borderColor: "#D9D9D9",
                borderWidth: 1,
                marginHorizontal: 15,
              }}
            >
              <Icon name="search" size={15} color="#9C9C9C" />
              <TextInput
                placeholder="Search Here"
                style={{ flex: 1, marginLeft: 10 }}
              />
            </View>
          </>
        )}
      />
      <View style={{ flexDirection: "row", height: 10, marginVertical: 10 }}>
        <NavigationLine active={true} />
        <NavigationLine active={true} />
        <NavigationLine active={true} />
        <NavigationLine active={false} />
        <NavigationLine active={false} />
      </View>
      <TouchableOpacity
        onPress={handleNext}
        style={{
          backgroundColor: "#09A1F6",
          padding: 10,
          borderRadius: 30,
          width: "90%",
          height: 50,
          justifyContent: "center",
          alignItems: "center",
          marginBottom: 10,
        }}
      >
        <Text style={{ color: "#fff", fontSize: 24, fontWeight: "bold" }}>
          Next
        </Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

export default AreasOfInterest;

Trying to use swiper js with npm but I can not( Pure JS

I want to use swiper js for my project and I want to install it using npm. Many times there were errors with the installation, but after fixing the errors there were no errors, but the slider did not work. Before this I installed it using a cdn file and everything worked, but I want to use npm. Help please, I’ve been sitting all day trying to do this.

Here’s my code:

import Swiper from "swiper";
import "../node_modules/swiper/swiper.css";
import "../node_modules/swiper/modules/navigation.css";
import { Navigation } from "swiper/modules";
const controlMain = async function () {
  await model.setDefault();
  document.querySelector(".main-spinner").classList.add("active");

  const topAuthorsMarkup = `
  <section class="top-authors">
  <h2 class="heading-secondary">Top authors</h2>
  <!-- Список слайдов -->
  <div class="swiper top-authors__list">
    <div class="swiper-wrapper">
      ${model.state.default.topAuthorsNames
        .map((authorName, i) => {
          return `
        <div class="swiper-slide top-authors__item">
          <figure class="top-authors__author">
            <img class="top-authors__img"
                 src="${model.state.default.topAuthorsImgs[i]}"
                 alt="${authorName} image" />
            <figcaption class="top-authors__description">
              <h3 class="top-authors__name">${authorName}</h3>
              <p class="top-authors__text">
                ${model.state.default.topAuthorsDescription[i]}
              </p>
            </figcaption>
            <a class="top-authors__link" href="#"></a>
          </figure>
        </div>
      `;
        })
        .join("")}
    </div>
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</section>
`

Here’s video