Did I break my project by running `npm audit fix –force`?

I was building a React project with Vite and it was going great. I needed to add some charts and found out about the recharts package and really liked it so downloaded it into my project with the command npm i recharts.

I get the following message:

high severity vulnerabilities

I then ran npm audit, npm audit fix and npm audit fix --force and got this:

lots of warnings

Now when I try to start up my project with npm run dev I get this error in the console:

Uncaught TypeError: import_events.default is not a constructor

It says it’s coming from a file called Events.js but I do not have such a file in my project.

I tried running npm audit fix --force multiple times like my terminal told me to but it did not work.

Order bar chart using react-charts-js-2 ChartJS

I am creating bar graphs obtaining data for the month and it works fine but the order is never by the order of the months and it is also messed up in each rendering.

The data I receive from the API is the following:

{
{
    "_id": 2022,
    "sales": [
        {
            "month": "Dic",
            "year": 2022,
            "total": 8737.6
        },
        {
            "month": "Oct",
            "year": 2022,
            "total": 1936.0000000000002
        },
        {
            "month": "Sep",
            "year": 2022,
            "total": 526.8000000000001
        },
        {
            "month": "Nov",
            "year": 2022,
            "total": 2205.2000000000003
        }
    ]
}
}

So I use this code with react-chartjs-2 (chartjs) like this:

  const data = {
      labels: dataOfSalesPerMonth?.map((data) => data.month),
      datasets: [
        {
          label: "Venta Mensual",
          data: dataOfSalesPerMonth?.map((data) => data.total),
          backgroundColor: [
            "rgba(75,192,192,1)",
            "#ecf0f1",
            "#50AF95",
            "#f3ba2f",
            "#2a71d0",
          ],
          borderColor: "black",
          borderWidth: 2,
        },
      ]
    }
  

And in react I render it like this:

  return (
    <div className="w-full h-44">
      {
        Object.entries(sales).length &&
          <Bar
            data={data}
            options={options}
          />
      }
    </div>
  )

But the order is not correct, it always gives me the months mixed up and never in the same order:

Bar

How can I order it? Thanks.

JavaScript: Display input information in Alert [closed]

I am designing a form in HTML, where the user input his/her firstname and lastname.
When i click on submit button, it should display an alert with the following information:
“firstname” & “lastname”

Any idea on how to do this please?

Ive tried to search for a tutorial about this online, but could not find none.

How to execute scripts after document has been rendered?

I am trying to load scripts from a database. These scripts from databases are being fetched after the document has been completely rendered. When I check the dom tree after the document has been completely loaded, the scripts that are being fetched from database are present, but are able to be executed

I know that a browser first executes the scripts files and after its turn the scripts from database have came into dom. Browser in unaware of these scripts and no executed. Is there any other way that I can to fetch the scripts from a database and still be able to execute these scripts

How to send data from API to another HTML file

Im using a TMDB API to search for movies and add them to a watchlist.

In this javascript function im getting movie details based on user input and rendering the results to html using bootstrap.

const searchMovie =  async (searchInput) => {
    try { 
      axios.get(`https://api.themoviedb.org/3/search/movie?api_key={API_KEY}&language=en-US&query=${searchInput}&page=1&include_adult=false `)
      .then((response) => {
        console.log(response);
        let movies = response.data.results;
        let displayMovies = '';
        $.each(movies, (index, movie) => {
          displayMovies += `
          <div class="col-md-3">
          <div class="well text-center">
          <a href="https://www.themoviedb.org/movie/${movie.movie_id} target="_blank"><img src="https://image.tmdb.org/t/p/original${movie.poster_path}"></a>
            <h5>${movie.title}</h5>
            <h4>${movie.release_date}<h4>
            <a class="btn btn-primary" href="#">Add to watchlist</a>
          </div>
        </div>
          `;
        });
        
        $('#movies').html(displayMovies);
      })
    }catch(error) {
     console.log(error)
    }
}

I have another html file called watchlist.html that i want to send the movie selected from the search results to that file and build a watchlist.

How to Integrate tinymce editor in ReactJs

I am new in Reactjs,working with nextjs and i am trying to integrate Editor
in my page but i am getting following error

"TypeError: editor1 is null"

How can i fix this ? I tried with following code, Where i am wrong ?

const handleSubmit = (e: any) => {
  e.preventDefault();
  let editor: any = null;
  const content = editor.getContent();

  const data = {
    first: e.target.name.value,
    last: e.target.cat_name.value,
    content: content, // add the content to the data object
  }
};

<Editor
  onInit={(evt, ed) => editor = ed} // set the editor reference
  initialValue="<p>This is the initial content of the editor.</p>"
  init={{
    height: 500,
    menubar: false,
    plugins: [
      'advlist autolink lists link image charmap print preview anchor',
      'searchreplace visualblocks code fullscreen',
      'insertdatetime media table paste code help wordcount'
    ],
    toolbar: 'undo redo | formatselect | ' +
    'bold italic backcolor | alignleft aligncenter ' +
    'alignright alignjustify | bullist numlist outdent indent | ' +
    'removeformat | help',
    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
  }}
/>

useEffect() hook failing to run, infinite re-render errors, no evidence the hook is running at all

I am building this react app that make a fetch req to an api I had built and hosted elsewhere. Api is functional with no problems, plus when I run fetchPhotos() outside of useEffect() and it fetches the information just fine, so I do not think it is an issue with the api.

I really have no clue what the issue is. I looked through serveral articles and other examples of code to see what coule be the issue but everything should be in order. I have an empty bracket dependency which sould fix the re-render issue according to other posts on here, I uninstalled and re-stalled react, I tried writing a seperate useEffect hook to console.log text but it did not run. Maybe I need to import it another way?

Here is my code

Here are the erros

How to render RapidAPI data on another HTML page?

I am new to JavaScript and this is my first question here. I’ve been trying for week to render my RapidApi data on another HTML page. I made search form on my index page and then put its values as my api call parameters in order to influence my API response. I used fetch to do so. The issue is that my API data keeps rendering on the same index page which is understandable since I don’t know how to render it on a separate page. This also means that my CSS styling options are limited since I cannot design API data as I want without messing up my index page. If you have any sort of solution that is not way too complicated I would really appreciate your help.

Here is part of my code:

const input = document.getElementById(`location`);
const guests = document.getElementById(`guests`);
const check = document.querySelectorAll(".date");
let id;


document.getElementById(`submit`).addEventListener(`click`, function () {
    locationId();
    
});

    async function locationId () {
        let hotelId = input.value;
        const options = {
            method: 'GET',
            headers: {
                'X-RapidAPI-Key': '//API key goes here',
                'X-RapidAPI-Host': 'tripadvisor16.p.rapidapi.com'
            }
        };
  let response = await fetch(`https://tripadvisor16.p.rapidapi.com/api/v1/hotels/searchLocation?query=${hotelId}`, options);
         if (!response.ok) throw new Error(`Woops something went wrong`);
         let data = await response.json();
         let geoId = await (data.data[0].geoId);
         id= parseInt(geoId);
        return (fetch(`https://tripadvisor16.p.rapidapi.com/api/v1/hotels/searchHotels?geoId=${id}&checkIn=${check[0].value}&checkOut=${check[1].value}&pageNumber=1&adults=${guests.value}currencyCode=USD`, options))
         .then(response => response.json())
         .then(data => {
            let list = data.data.data;
          displayObjectElements(list)

          function displayObjectElements (object) {
            let display = ``;
            let price = ``;
            object.forEach(element => {
                display+= `<div class = "objectResults">
                <ul class="hotel__lists">
               <li><h2 class = "title">${element.title}</h2></li>
               <li><img class= "hotels--photo "src="${element.cardPhotos[0].sizes.urlTemplate.split("?")[0] + `?w=500&h=500`}" alt=image--photo/></li>
                <li><p>Ranking:${element.bubbleRating.rating}&#9734 out of 5&#9734</p></li>`
                if(!element.priceForDisplay) {
                    display+= `<li><p>There is no price to display</p></li>`
                    display+= `<li><button class="booking-btn">Click to book</button></li>`
                   
                } else {
                price =element.priceForDisplay.substring(1);
                price= parseInt(price);
                // console.log(price);
                display+= `<li><p>Price: $${price} in total</p></li>`
                display+= `<li><button class = "booking-btn">Click to book</button></li>
                </ul>
                </div>`
                // console.log(display);
                
            }});
        
            document.body.innerHTML = display;
           
          }
 })
         .catch(err => console.error(err));
}
    

I already tried with localStorage and sessionStorage but as a newbie I am just now sure how to put the whole API data in storage. Also, I desperately tried with window.location object as well but as I assumed that did nothing but open a new tab. Again, thanks in advance for any help!

DRF parses number array as string array

When I make a POST request from JavaScript to my Django Rest Framework backend, my array of numbers is interpreted as a list of strings on the backend, causing this error:
cargo: ["Incorrect type. Expected pk value, received str."]

This is how I make the request in JavaScript:

const data = new FormData();
data.append("cargo", JSON.stringify([1, 2]));
fetch(url, {method: "POST", body: data}).then(//<more code>

In my Django Rest Framework serializer, I define the cargo field like this:

cargo = serializers.PrimaryKeyRelatedField(                                                     
    many=True, queryset=models.CustomCargo.objects.all()                                        
)                                                                                               

I post an array of numbers but DRF thinks it’s an array of strings so I get an error because it’s expecting integers (PrimaryKeyRelatedField). I need to use multipart/form-data because I’m posting a file too, so I can’t use application/json, which does work. Is there a way to fix this in the JavaScript code (I’d rather not convert strings to integers on the backend)?

Break line toolkit jquery

[enter image description here][1]

Password::
Enter password that must be (i) 6-24 characters long (ii) Must contain a number (iii) Must contain a capital letter”, “title”: “Password”}’/>



Iam want to woking but it is not working about show tooltip jquery


  [1]: https://i.stack.imgur.com/JU6qo.png

How to put an array of objects into an object name data for datatables

I have an array of objects as follows:

[
  {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [
        137.89094924926758,
        36.93143814715343
      ]
    },
    "properties": {
      "@geometry": "center",
      "@id": "way/323049815",
      "id": "way/323049815",
      "landuse": "winter_sports",
      "name": "糸魚川シーサイドバレースキー場",
      "name:en": "Itoigawa Seaside Valley Ski Resort",
      "name:ja": "糸魚川シーサイドバレースキー場",
      "source": "Bing",
      "sport": "skiing",
      "website": "https://www.seasidevalley.com/",
      "wikidata": "Q11604871",
      "wikipedia": "ja:糸魚川シーサイドバレースキー場"
    },
    
    [snip]

I want to add the above array into a data object in javascript as follows.

{
    "data": [
        //my data here.
    ]
}

I have tried this;

          let mydata = {
            "data": skidata
          }

but is places back slashed a lot like this snippet;

{
    "data": "[{"type":"Feature","geometry":{"type":"Point","coordinates"...

How do I remove the back slashes in javascript please?

how can I connect my database to the permission sweetalert2 login form

I’ve been using sweetalert2 login form for the sake of permission,
how can I connect my database to the permission sweetalert2 login form.

I have been stucked with this, please help.

<button class="btn btn-warning confirmation" href="index.php"><i class="icon-edit"></i></button>

    <script>
        $('.confirmation').on('click',function (e) {
                e.preventDefault();
                const href = $(this).attr('href')
                Swal.fire({
                  title: 'Admin Permission',
                  html: `<input type="text" id="login" class="swal2-input" placeholder="Username">
                  <input type="password" id="password" class="swal2-input" placeholder="Password">`,
                    showCancelButton: true,
                    cancelButtonColor: 'gray',
                    confirmButtonText: 'Grant',
                    confirmButtonColor: 'green',
                  focusConfirm: true,
                    showCloseButton: true,
                    customClass: {
                        confirmButton: 'btnconfirm',
                            cancelButton: 'btncancel',
                            title: 'permissiontitle',
                    },
                  preConfirm: () => {
                    const username = Swal.getPopup().querySelector('#login').value
                    const password = Swal.getPopup().querySelector('#password').value
                        if (!login || !password) {
                          Swal.showValidationMessage(`Please Enter Username and Password`)
                        }
                        return {
                                username: username,
                                password: password
                            }
                      }
                    }).then((result) => {
                      // do something...
                    })
        })
</script>

cloud function deployment fails

My cloud function deployment has been failing and I have not been able to find a resolution after reviewing Google docs and many other collaborative sites. I do not know why I am not able to deploy.

The error I get after firebase deploy –only functions is:

Functions deploy had errors with the following functions:
functions:stripePaymentIntentRequest(us-central1)
i functions: cleaning up build files…
Error: There was an error deploying functions

index.js

const functions = require("firebase-functions");
const stripe = require("stripe")(
"sk_test"
);

exports.stripePaymentIntentRequest = functions.https.onRequest(
async (req, res) => {
    cors(req, res, async () => {
        res.set("Access-Control-Allow-Origin", "*");

       if (req.method === "OPTIONS") {
        // Send response to OPTIONS requests
           res.set("Access-Control-Allow-Methods", 
          "GET");
        res.set("Access-Control-Allow-Headers", 
          "Content-Type");
        res.set("Access-Control-Max-Age", "3600");
        res.status(204).send("");
     } else {
    res.send("Hello World!");
    }

  const { codeItem } = req.body;

    try {
   
    const paymentInt = await 
   stripe.paymentIntents.create({
      amount: 100,
      currency: "usd",
      automatic_payment_methods: {
        enabled: true,
      },
    });

    res.send({
      paymentIntent: paymentInt.client_secret,
      success: true,
    });
  } catch (error) {
    res
      .status(error.res.status)
      .send({ success: false, error: error.message });
  }
 });
}
);

functions package.json

{
 "name": "functions",
 "description": "Cloud Functions for Firebase",
 "scripts": {
    "serve": "firebase emulators:start --only 
    functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
},
   "engines": {
     "node": "16"
    },
"main": "index.js",
"dependencies": {
    "firebase-admin": "^10.0.2",
    "firebase-functions": "^4.1.0"
},
"devDependencies": {
    "firebase-functions-test": "^0.2.0"
},
     "private": true
}

Check if a string matches the beginning of a regex

I have many string to match against a regex. Many strings start with the same substring. To speed up my search, I would like to check whether the regex could match a string which begins with the common substring…

Example

I have a regex like for instance: /^(.[3e]|[o0]+)+l+$/ and many strings, like for instance these:

...
goo
goober
good
goodhearted
goodly
goods
goody
goof
goofball
google
goon
goose
...
held
helical
helices
helicopter
helipad
heliport
hell
help
hellion
helm
helmet
...

Half of the strings start with goo: I’d like to test whether goo is a valid beginning for a match. It’s not (no string starting with goo can ever match that regex), thus I’d discard all those words at once.

The other half start with hel: I’d like to test whether hel is a valid beginning for a match. It is (some strings starting with hel may match that regex), thus I proceed testing those strings.

Is there any function to do this with a generic regex, without having to manually re-engineer it?

Create a visit-counter that counts down using HTML and JS [closed]

Using HTML and JS, I am attempting to create a unique visit counter that counts down from 500. Once 0 is reached, a flag is set to true and a program is run. I’ve found some counters online, though they don’t count down, nor do they output a value that can be used (I could scrape the value, if needed). I’m trying to figure out how to detect unique page views, but I’m in over my head. Any help would be greatly appreciated, thank you :]

I have tried both of the below, but they did not fit my requirements:

https://contactmentor.com/build-website-visitor-counter-javascript/

https://medium.com/@codefoxx/how-to-count-the-number-of-visits-on-your-website-with-html-css-javascript-and-the-count-api-2f99b42b5990

Thanks in advance :]