Why is my this part of the program showing infinite rerenders in react , please check it

When I click the btn, the onclick function is suppose to pass the JSX from a another component, but calls the component 200+ times, and react breaks the operation and shows “React limits too many re-renders leading to an infinite loop”

then code

import React, { useState, useEffect } from "react";
import fetchAPI from "../../utils/fectch-api";
import SearchEl from "../../utils/searchel";

function Search() {
  const [SearchResults, setSearchResults] = useState([]);
  const [query, setQuery] = useState({ query: "" });

  async function showdata() {
    let data;
    data = query.query ? await fetchAPI("hashtag_post", "hashtag", "love") : "";
    console.log(data);
    const dataObj = data.body.edge_hashtag_to_top_posts.edges.concat(
      data.body.edge_hashtag_to_media.edges
    );
    const readableObj = dataObj.map((item) => {
      return {
        comments_disabled: item.node.comments_disabled,
        Pic_dimensions: item.node.dimensions,
        photo_url: item.node.display_url,
        like_count: item.node.edge_liked_by,
        caption: item.node.edge_media_to_caption,
        comment_count: item.node.edge_media_to_comment,
        user_id: item.node.id,
        is_video: item.node.is_video,
        posts_owner: item.node.owner,
        post_shortcode: item.node.shortcode,
        thumbnail_resources: item.node.thumbnail_resources,
      };
    });
    setSearchResults(readableObj);
    console.log(readableObj);
  }

  function handlequerychange(e) {
    setQuery({ [e.target.name]: e.target.value });
  }

  const searchItems = SearchResults.map((item) => {
    console.log(item);
    return <SearchEl obj={item} />;
  });

  return (
    <>
      <div className="sticky top-0 bg-slate-800 rounded-xl flex items-center justify-between gap-2 px-1 mx-4 my-2">
        <button
          onClick={() => {
            showdata();
          }}
          className="w-12 cursor-pointer aspect-square hover:rounded-[100%] hover:bg-slate-600"
        >
          <i className="fa-solid fa-magnifying-glass text-[1.2em"></i>
        </button>
        <input
          className="w-[100%]  text-lg outline-none border-0 bg-slate-800 py-1"
          type="text"
          name="query"
          onChange={handlequerychange}
          placeholder="Search"
        />
      </div>
      <div className="grid grid-cols-3 grid-row-[auto] overflow-y-scroll hide-scrollbar">
        {searchItems}
      </div>
    </>
  );
}

export default Search;

Initially, I am not using the query string because I need to test if it works or not. So please tell me where did the code got so many re-renders from … Thank you!

I was trying to create JSX elements for every object that came from the API but I showed too many references

Edit ckeditor toolbar button

I added ckeditor using this syntax <script src="https://nightly.ckeditor.com/full/ckeditor.js"></script>. My ckeditor editor toolbar looks like below.

enter image description here

I would like to add new functionalities to an existing icon.

How can I do that ?

TS5055 error when extracting JavaScript from cshtml file

While this does appear to work, Visual Studio is raising TS5055 errors when editing the Javascript files. What I want to do is extract the JavaScript declared in the view into a separate file rather than just embedding it in the end of the .cshtml file within a @section scripts { }

So for instance instead of:

@section scripts{
    <script type="text/javascript">
        var userDetailUrl = '@Url.Action("Detail", "UserManagement", new {userId="@userId"})';

        // ...

        function loadData() {
            fetch('GetUsers')
                .then(response => {
                if (response.ok) {
                     return response.json();
                }
                throw new Error(response.statusText);
            }).then(data => {
                 asyncTable.update({
                      rows: data.map(user => ({
                          pid: user.pid,
                          name: user.lastName + ', ' + user.firstName,
                          action: '<a href="' + userDetailUrl.replace('@userId', user.userId) + '">' + user.pid + '</a>'
                   }))
            }, {
                loading: false
            });
        });

    </script>
}

I want to move the functions and such into a separate .js file nested under the view’s cshtml file. So for instance:

 - List.cshtml
     - List.cshtml.js

using Visual Studio 2022 file nesting rules.

In this way my script section is updated to:

@section scripts{
    <script type="text/javascript">
        var userDetailUrl = '@Url.Action("Detail", "UserManagement", new {userId="@userId"})';
    </script>
    <script src="@Url.Content("~/Views/UserManagement/List.cshtml.js")" asp-append-version="true"></script>
}

with the script file (List.cshtml.js) containing the loadData() and other relevant functions.

Now this all works, but in Visual Studio, if I have the .cshtml.js file open in the editor, without making any changes at all, within a few seconds I get a TS5055 error:

Cannot write file ‘…./UserManagement/List.cshtml.js’ because it
would overwrite input file. Adding a tsconfig.json file will help
organize projects….

This appears under a Project of “Miscellaneous” rather than the specific web project.

Now my thoughts here is that with ASP.Net MVC creating JS automatically for views, perhaps it is somehow expecting to reserve a .cshtml.js file for it’s own use, though I cannot see any such script file normally being generated for views.

Where it gets very odd is if I rename the file to something like “List.scripts.js”. I change the <script src="@Url.Content("~/Views/UserManagement/List.scripts.js")" asp-append-version="true"></script>

Now the TS5055 error does not come up when I have the file open in the VS editor, however, when running the application it returns a 404 for the script file! I have double-checked in IIS going to the Views/UserManagement folder and explored to ensure this wasn’t something like going to a different location where a “copy local” might be an issue, the file is present at that location but somehow it isn’t located. When the file and reference are named “List.cshtml.js”, the file is found and works. I had tried without the “asp-append-version” in case that was being problematic but that doesn’t make any difference.

As far as I can see, the code is working despite the TS5055 error when the script file is open in the editor, but I don’t know if this will manifest into actual problems later and I would prefer not having to start ignoring errors in the build output.

nodeJS throws heap out of memory exception while iterating large json file?

I have a situation where i need to process large json file (array of json objects) in nuxt3 application.

While iterating the large JSON file. node throws javascript heap out of memory exception. To counter this, I converted the large JSON into smaller chunks and tried processing it. It still fails and gives the same exception.

I also tried to build nuxt app with NODE_OPTIONS=--max_old_space_size=8192 nuxi build It doesn’t help either.

Is there any way to handle this better?

super expression must either be null or a function at Object._inherits

when i try to import a class( with super initialize) in to another class, i get this error

super expression must either be null or a function Object._inherits

and my code doesnt work,
below is imported class

export default class ToDo extends Editor{
#toDoEditor = null;
initialize(id, settings): void
{
    super.initialize(id, settings);
    this.#createEditor();
}}

Any hints at all as to what is wrong would be appreciated.

Use multiple firebase instances in Angular project

I’m trying to use two Firebase instances in my Angular project. I found some articles regarding the usage of InjectionToken but I’m wondering if there is a more straightforward solution. In app.module.ts I initialize the app and provide FirebaseApp and Firestore. Is there any possibility of initializing two apps and providing them both to FirebaseApp and Firestore? I have a const environment that keeps the two configurations: firebaseOne and firebaseTwo. Is there any solution? For now, inside my app.module.ts in imports, I have this:

imports: [
  //... code
    AngularFireModule.initializeApp(environment.firebaseOne),
    provideFirebaseApp(() => initializeApp(environment.firebaseOne)),
    provideFirestore(() => getFirestore()),
  ],

Mapping is not working inside react-bootstrap-carousel

I am using react bootstrap carousel . And I wanted to use mapping inside it. But it is not working. Can someone help me with that

import React from "react";
import "../../styles/Banner.css";
import Carousel from "react-bootstrap/Carousel";

const data = [
  "https://rukminim1.flixcart.com/flap/1680/280/image/1defb861e409319b.jpg?q=50",
  " https://rukminim1.flixcart.com/flap/1680/280/image/685712c6cefb3c02.jpg?q=50",
  "https://rukminim1.flixcart.com/flap/1680/280/image/8d4150cc4f3f967d.jpg?q=50",
  "https://rukminim1.flixcart.com/flap/1680/280/image/685712c6cefb3c02.jpg?q=50",
];

const Banner = () => {
  return (
    <Carousel className="carasousel">
      <Carousel.Item>
        {data.map((imag, i) => {
          return (
            <>
              <img src={imag} alt="img" key={i} className="banner_img" />
            </>
          );
        })}
      </Carousel.Item>
    </Carousel>
  );
};

export default Banner;

It supposed to show one item at a time but it is showing all four together.

Another Issue:
And I also wanted to remove the lower slide indicator from the carousel . Is there any way to remove it.

Wanted to remove this indicator

How do I properly initialize HavokPlugin in BabylonJS 6.18.0

As for the topic, I have a BabylonJS project and want to implement physics, I have upgraded version from 5.57.0 to 6.18.0 so my package.json looks like so

{
  "name": "roulette",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babylonjs/core": "^6.18.0",
    "@babylonjs/havok": "^1.0.0",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.7.13",
    "@types/react": "^18.0.0",
    "@types/react-dom": "^18.0.0",
    "mobx": "^6.9.0",
    "mobx-react-lite": "^3.4.3",
    "node-sass": "^8.0.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.4.2",
    "web-vitals": "^2.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

in my main scene component I import and initialize havok plugin like so,

import {
  ArcRotateCamera,
  DirectionalLight,
  HemisphericLight,
  Mesh,
  Scene,
  Vector3,
} from "@babylonjs/core";
import { HavokPlugin } from "@babylonjs/core/Physics";
import { observer } from "mobx-react-lite";
import type { WheelState } from "../../store/gameStore/types";
import { useStore } from "../../store/rootStoreProvider";
import { SceneComponent } from "./SceneComponent";
import styles from "./spinningWheel.module.scss";
import { createBall } from "./utils/createBall";
import { createGround } from "./utils/createGround";
import { createSkyBox } from "./utils/createSkyBox";
import { createSpinningWheel } from "./utils/createSpinningWheel";

import HavokPhysics from "@babylonjs/havok";

async function getInitializedHavok() {
  return await HavokPhysics();
}

let spinningBase: Mesh;
let ball: Mesh;

const onSceneReady = (scene: Scene) => {
  // scene.debugLayer.show();
  new HemisphericLight("light1", new Vector3(0, 1, 0), scene);
  const light = new DirectionalLight("light", new Vector3(-1, -2, -2), scene);
  light.intensity = 0.3;
  const camera = new ArcRotateCamera(
    "camera",
    -Math.PI * 0.5,
    Math.PI * 0.25,
    12,
    Vector3.Zero(),
    scene
  );
  camera.setTarget(Vector3.Zero());
  const canvas = scene.getEngine().getRenderingCanvas();
  camera.attachControl(canvas, true);
  createSkyBox(scene);
  createGround(scene);
  ball = createBall(scene);
  ball.position.y = 0.7;
  ball.position.x = 1;
  const spinningWheel = createSpinningWheel(scene);
  spinningBase = spinningWheel.spinningBase;

  const havokInstance = getInitializedHavok();
  scene.enablePhysics(
    new Vector3(0, -9.81, 0),
    new HavokPlugin(true, havokInstance)
  );
};

const onRender = (scene: Scene, wheelState: WheelState) => {
  if (spinningBase !== undefined) {
    const deltaTimeInMillis = scene.getEngine().getDeltaTime();

    if (wheelState === "idle") {
      const rpm = 2;
      spinningBase.rotation.y +=
        (rpm / 60) * Math.PI * 2 * (deltaTimeInMillis / 1000);
    }
    if (wheelState === "spinning") {
    }
  }
};

export const SpinningWheel = observer(() => {
  const {
    gameStore: { wheelState },
  } = useStore();
  return (
    <div className={styles.spinningWheelcontainer}>
      <SceneComponent
        antialias
        onSceneReady={onSceneReady}
        onRender={(scene) => onRender(scene, wheelState)}
        id="my-canvas"
        className={styles.canvas}
      />
    </div>
  );
});

and i am getting error that

this._hknp.HP_World_Create is not a function
TypeError: this._hknp.HP_World_Create is not a function
    at new HavokPlugin (http://localhost:3000/static/js/bundle.js:256236:29)
    at onSceneReady (http://localhost:3000/main.ccaac105aa02db67abb4.hot-update.js:65:94)
    at http://localhost:3000/static/js/bundle.js:2203:7
    at commitHookEffectListMount (http://localhost:3000/static/js/bundle.js:37382:30)
    at commitPassiveMountOnFiber (http://localhost:3000/static/js/bundle.js:38875:17)
    at commitPassiveMountEffects_complete (http://localhost:3000/static/js/bundle.js:38847:13)
    at commitPassiveMountEffects_begin (http://localhost:3000/static/js/bundle.js:38837:11)
    at commitPassiveMountEffects (http://localhost:3000/static/js/bundle.js:38827:7)
    at flushPassiveEffectsImpl (http://localhost:3000/static/js/bundle.js:40712:7)
    at flushPassiveEffects (http://localhost:3000/static/js/bundle.js:40664:18)

and also after upgrading to version 6 i get error from the inspector

Script error.
    at http://localhost:3000/static/js/bundle.js:49478:58
Cannot read properties of undefined (reading 'Inspector')
TypeError: Cannot read properties of undefined (reading 'Inspector')
    at DebugLayer._createInspector (http://localhost:3000/static/js/bundle.js:84586:23)
    at http://localhost:3000/static/js/bundle.js:84651:16
    at LoadScript.script.onload (http://localhost:3000/static/js/bundle.js:234436:9)

I hope this information is sufficient.
Thanks a lot for any help.

Cannot read properties of null using Reactjs

I am working on Reactjs and using “nextjs framework”,Right now i am trying to create component (functional) but i am getting following error

Cannot read properties of null (reading 'useState')

Here is my current code,Where i am wrong ?

import React from 'react'
import Link from "next/link";
import { useEffect, useState } from "react";
import { error } from 'jquery';

const clearinputs = (event) => {
    const data = {
      name: state.name
    };
    setState({
      ...state,
      name: ""
    });
  }

const [state, setState] = useState({
    name: "",
    email: "",
  });

chart.js – Can we update the legend label if user click any data from dataset?

my query is can we update the specifi lable font size and color if user click any specific portion of doughnut chart. like below

enter image description here

in above image as use can see, if user click on Green poriton of doughnut then want change the color/size of corresponding legend label, is this possible?

sample code here

   // config
      const config = {
        type: "doughnut",
        data: {
          labels: ["Green", "Red", "Blue"],
          datasets: [
            {
              data: [60, 80, 100],
              borderWidth: 0,
              backgroundColor: ["#009900", "#ff0000", "#3399ff"],
              hoverBackgroundColor: ["#009900", "#ff0000", "#3399ff"],
              cutout: "80%"
            }
          ]
        },
        options: {
          plugins: {
            legend: {
              position: "right",
              labels: {
                font: {
                  size: 11
                },
                usePointStyle: true,
                pointStyle: "circle"
              }
            }
          }
        }
      };

      // render init block
      const myChart = new Chart(document.getElementById("myChart"), config);

I am running a google script that brings my emails into a spreadsheet, I need assistance troubleshooting a duplication error

I have been running a script to collect task data for my company, it’s been running since 09/03/2023, it seems to have begun duplicating entries at some point and I am struggling to see which tasks are required, or duplication.

This is my script:

function getEmails() {
  // Get the first 100 emails in the inbox with the label "HCA"
  var threads = GmailApp.search('label:"Emprevo"', 0, 100);
  
  // Loop through the threads and retrieve the relevant data
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      var message = messages[j];
      var subject = message.getSubject();
      var body = message.getPlainBody();
      var emailDate = message.getDate(); // Get the date the email was sent
      
      // Parse the email content to extract the job data
      var jobData = parseEmailBody(emailDate, subject, body);
      
      // Write the job data to the Google Sheet
      var sheet = SpreadsheetApp.getActive().getActiveSheet();
      sheet.appendRow(jobData);
      
      // Mark the email as read and remove the "HCA" label
      message.markRead();
      threads[i].removeLabel(GmailApp.getUserLabelByName("Emprevo"));
    }
  }
}

function parseEmailBody(emailDate, subject, body) {
  // Parse the email body to extract the relevant data
  // and return it as an array of values
  var senderRegex = /From: (.*?<(.+?)>)/;
  var matches = body.match(senderRegex);
  var sender = matches ? matches[1] : '';
  return [emailDate, subject, sender, body];
}

I thought it may be due to thread grouping in Gmail settings, but i have since removed this setting and it still does not work.

The emails are being categorised, and archived as anticipated so I can’t see a risk in the trigger pulling in the email twice.

Get my second y-axis in charts.js to always display the 100% tick

I have a scatter chart using recharts that looks like the following:

1

The right-y-axis represents the percentage and it is displaying the correct values as I intended. However, I’d like to adjust it so that the 100% is always displayed. Is this possible?

To build what I currently have, I basically have two nearly-identical datasets, the difference is that one of them is hidden and I changed the ticks callback to display the percentage based on the maximum y values in the points.

Here’s my dataset config:

datasets: [
  {
    label,
    data: data
      ? Array.from({ length: data.x.values.length || 0 }, (_, i) => ({
          x: data.x.values[i],
          y: data.y.values[i],
        }))
      : [],
    backgroundColor: color,
    borderColor: color,
    pointRadius: 1.2,
    fill: false,
  },
  {
    data: data
      ? Array.from({ length: data.x.values.length || 0 }, (_, i) => ({
          x: data.x.values[i],
          y: data.y.values[i],
        }))
      : [],
    backgroundColor: 'transparent',
    borderColor: 'transparent',
    pointRadius: 0,
    fill: false,
    yAxisID: 'y1',
  },
],

And here’s my scales config:

scales: {
  x: {
    title: {
      display: true,
      text: data?.x.title || '',
    },
    ticks: {
      callback: formatPlotTicks,
    },
  },
  y: {
    title: {
      display: true,
      text: data?.y.title || '',
    },
    type: 'linear',
    display: true,
    position: 'left',
    ticks: {
      callback: formatPlotTicks,
    },
  },
  y1: {
    type: 'linear',
    display: true,
    position: 'right',
    ticks: {
      callback: (value) => {
        const percentageValue = ((value as number) / maxYValue) * 100;
        if (percentageValue > 100.5) {
          return '';
        }
        return `${percentageValue.toFixed(0)}%`;
      },
    },
  },
},

How to make a post request in Node with Mongoose

I was following a tutorial(https://medium.com/weekly-webtips/building-restful-apis-with-node-js-and-express-a9f648219f5b) to build an API but it’s from 2 years ago and I can’t quite seem to change the code to accommodate more recent updates in the library. I’m able to get the get request to work but not the post. When I do

.post(addNewCoordinates);

I get “Error: Route.post() requires a callback function but got a [object Undefined]”

Which the internet said to add async await which I did. Am I missing something else??

The setup I have with the mongodb is I created a database in the compass GUI and that’s literally it.(i technically have a collection in the database)

Here is my index.js

import express from 'express';
import routes from './src/routes/coordinatesRoutes';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';

const app = express();
routes(app)
const PORT = 1234;
// Will print at localhost:{Port}
app.get('/', (req, res) =>
  res.send(`Node and express server running on port ${PORT}`)
)
// Will print in terminal
app.listen(PORT, () =>
console.log(`Your server is running on port ${PORT}`))

// Database Setup

// mongoose connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/coordinates', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
//bodyparser setup
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

coordinatesController.js:

import mongoose from 'mongoose';
import { InputDataSchema } from '../models/coordinatesModel'
const InputData = mongoose.model('InputData', InputDataSchema);
const addNewCoordinates = async  (req,res) => {
  let newCoordinates =  new InputData(req.body);
   await newCoordinates.save((err, coordinates) => {
    if (err) {
      res.send(err)
    }
    res.json(coordinates)
  })
}

export default addNewCoordinates;

coordinatesModel.js:

import mongoose from 'mongoose';
const Schema = mongoose.Schema;
export const InputDataSchema = new Schema({
  latitude: {
    type: Number,
    required: "Enter latitude"
  },
  longitude: {
    type: Number,
    required: "Enter longitude"
  },
  altitude: {
    type: Number,
    required: "Enter altitude"
  },
  ecef: {
    type: Array
  },
  created_date: {
    type: Date,
    default: Date.now
  }
})

coordinatesRoute.js

import { addNewCoordinates } from '../controllers/coordinatesController'
const routes = (app) => {
    //create route for donations
    app.route('/lla')
      //create get request
      .get((req, res) =>
      res.send('GET request successful!'))
      //create post request
      .post((req, res) =>
      res.set('POST request successful!'));
      // This crashes and gives me a Route.post() requires a callback function but got a [object Undefined] so I'm just trying to focus on getting a post without really any data.
     //.post(addNewCoordinates);

    // create a new route so you can get these donation entries by their ID's
    app.route('/lla/:timestamp')
      //create put request
      .put((req, res) =>
      res.send('PUT request successful!'))
      //create delete request
      .delete((req, res) =>
      res.send('DELETE request successful'))
  }
  export default routes;

Thanks for any help!!

Form (type=file) stacks previous form submissions

I am writing a program that uploads photos to a cloud and then uses the url from the cloud to display the photos.
My problem is that during the fetch POST request on the form, if I submit a photo it’s fine but if I submit again it shows the photo from the previous submit too (doubling the image on the page). However it does not actually re upload the photo to the cloud, just displays it twice.

Here is the fetch request.

//function for uploading photos
const uploadPhoto = (thePhotos) => {
  console.log("uploadPhoto started...")
  const photos = document.getElementById("photoContainer");

  const today = new Date();
  const month = today.getUTCMonth() + 1;
  const day = today.getUTCDate();
  const year = today.getUTCFullYear();
  const d = document.createElement("div");
  d.innerHTML = month + "/" + day + "/" + year;

  thePhotos.forEach((image) => {
    const imgBox = document.createElement("div");
    imgBox.className = "newphoto";
    photos.insertBefore(imgBox, photos.children[0]);
    const img = document.createElement("img");
    img.src = "cloud-link-url" + image.link;
    imgBox.appendChild(img);
    if (image.link == thePhotos[0].link) {
      imgBox.appendChild(d);
    }
    if (image.imageMediaMetadata.time) {
      const popupid = document.createElement("div");
      popupid.className = "photo-overlay";
      popupid.setAttribute(
        "data-id",
        "This was taken on " + image.imageMediaMetadata.time
      );
      imgBox.appendChild(popupid);
    }
  });
};





//On uploading a new photo
form.onsubmit = async (event) => {
  event.preventDefault();
  let unique = Date.now();
  const formData = new FormData(form);
  loadingIcon.style.display = "block";

  fetch(`/upload?unique=${unique}`, {
    method: "POST",
    body: formData,
    headers: {
      "Cache-Control": "no-cache", //no cache did not stop the duplication
    },
  })
    .then((response) => {
      if (!response.ok) {
        const reserr = document.getElementById("error");
        reserr.innerHTML =
          "Bad network connection. Please refresh and try again.";
        reserr.style.display = "block";
        throw new Error("Bad network connection (onsubmit)");
      }
      console.log("Response OK");

      return response.json();
    })
    .then((data) => {
      console.log("data", data); //2nd+ time array grows with each addition.
      loadingIcon.style.display = "none";
      //Tried to use a function here instead to see if the duplication would stop.
      uploadPhoto(data);
      form.reset();
    })
    .catch((error) => {
      console.log(error);
    });

Because the duplication is not actually a double upload I think the problem lies here. I debugged the server side code and it is fine and working.
The data variable in the console logs show that on the second+ time uploading the array grows.

I tried stopping it from caching and clearing data variable but no go. I tried finding a way to clear the input fields but no go. I also looked into server side but highly doubt it is there.

How can I escape a comma when creating a CSV file in JavaScript? [duplicate]

I’m writing to a CSV file in Node.js and I’d like to add a hyperlink to some of the fields, as the =HYPERLINK function can be recognized by excel and some other spreadsheet apps.

So for example, I have this function

const addHyperlink = (url, str) => `=HYPERLINK("${url}", "${str}")`;

And the function is used as follows:

const processToCSVFormat = () => {
  ...
  return `${author}, ${date}, ${addHyperlink(purchaseURL, title)}, ...`
}

The issue is of course that when the CSV is parsed in excel, it picks up the comma and separates the function into the next column, like

Column 1 | =HYPERLINK("https://google.com" | "Google") | Column 4 | Column 5 | ...

I know that the comma needs to be escaped, but I’ve been unable to get it working looking at past answers – I may be doing it incorrectly though. I tried:

return ${author}, ${date}, "${addHyperlink(purchaseURL, title)}", ...

Thanks!