Event listener / variable not passing correctly

I am making a small to-do list web app. I found a bug where after I create three todos and start editing them, the second edit starts changing not only the to-do in question, but also another one – the first one.
I have tried everything possible, and I am certain the problem lies within the todoId variable in the toDoCreator.js editTodo method. Also, it looks like there is something weird with the event listeners on the modal’s save button – I tried to solve that with another function resetting the event listeners but I still get two of them after the second edit.

I am using webpack, so I am not sure how to paste this here…
Thanks!

// from my UI.js

import checkmarkLogo from './assets/checkmark.svg';
import plusSvg from './assets/plus.svg';
import plusWhiteSvg from './assets/plus-white.svg';
import trashSvg from './assets/trash.svg';
import editSvg from './assets/edit.svg';
import todoManager from './toDoCreator.js';

export default function init() {
    getAssets();
    appendAssets();
    bindEvents();
}

export function getDom() {
    return {
        headerLogo: document.querySelector('.header-logo'),
        addProjectBtn: document.querySelector('#add-project-btn'),
        addTodoBtn: document.querySelector('#add-todo-btn'),
        todoModal: document.querySelector('.todo-modal'),
        todoModalSaveBtn: document.querySelector('#todo-modal-save-btn'),
        todoModalCloseBtn: document.querySelector('#todo-modal-close-btn'),
        todoContainer: document.querySelector('.todo-container')
    }
}

function bindEvents() {
    getDom().addTodoBtn.addEventListener('click', e => openTodoModal(e.target));
    getDom().addProjectBtn.addEventListener('click', openNewProjectModal);
    getDom().todoModalCloseBtn.addEventListener('click', () => getDom().todoModal.close())
}

export function getForm() { // does this really go here? It is DOM stuff after all....
    return {
        title: document.querySelector('#title'),
        description: document.querySelector('#description'),
        dueDate: document.querySelector('#dueDate'),
        project: document.querySelector('#project'),
        priority: document.querySelector('input[name="priority"]:checked') // is not getting the value!!
    }
}

export function renderTodos() { 
    getDom().todoContainer.textContent = "";
    for (let i = 0; i < todoManager.todoManager.todos.length; i++) {
        const currentTodo = todoManager.todoManager.todos[i];
        const newTodoDiv = document.createElement('div');
        const todoTitle = document.createElement('p');
        const todoDate = document.createElement('p');
        const checkbox = document.createElement('input');
        const detailsButton = document.createElement('button');
        const todoEditIcon = getAssets().editIcon;
        const todoTrashIcon = getAssets().trashIcon; // why doesn't it work if I don't take the trashIcon at this point and store it in a variable (i.e, I pass getAssets().trashIcon as a parameter when calling bindTodoButtons)
        
        newTodoDiv.classList.add('todo');
        newTodoDiv.setAttribute("id", i);
        todoTitle.textContent = currentTodo.title;
        todoDate.textContent = currentTodo.dueDate;
        checkbox.setAttribute("type", "checkbox");
        detailsButton.textContent = 'DETAILS';
        detailsButton.setAttribute("id", "details-btn");
        newTodoDiv.appendChild(checkbox);
        newTodoDiv.appendChild(todoTitle);
        newTodoDiv.appendChild(detailsButton);
        newTodoDiv.appendChild(todoDate);
        newTodoDiv.appendChild(todoEditIcon);    
        newTodoDiv.appendChild(todoTrashIcon);
        getDom().todoContainer.appendChild(newTodoDiv);
        bindTodoButtons(detailsButton, todoEditIcon, todoTrashIcon);
    }
}

export function removeSaveBtnEventListeners() {
    getDom().todoModalSaveBtn.removeEventListener('click', todoManager.todoManager.createTodo);
    getDom().todoModalSaveBtn.removeEventListener('click', () => todoManager.todoManager.editTodo(caller.id));
}

function openTodoModal(caller) { //can I actually put this in the create to do fn?
    // Check where do I call it from, if class = todo then it means I'm editing, else it means I'm creating
    if(caller.classList.contains('todo')) {
        getDom().todoModalSaveBtn.addEventListener('click', () => todoManager.todoManager.editTodo(caller.id));
        getDom().todoModal.showModal();
    } else {
        getDom().todoModalSaveBtn.addEventListener('click', todoManager.todoManager.createTodo);
        getDom().todoModal.showModal();
    }
}

function updateModal(todoId) {
    const todoBeingEdited = todoManager.todoManager.todos[todoId];
    getForm().title.value = todoBeingEdited.title;
    getForm().description.value = todoBeingEdited.description;
    getForm().dueDate.value = todoBeingEdited.dueDate;
    getForm().project.value = todoBeingEdited.project;
// falta priority
}

function openNewProjectModal() {
    console.log("opening")
}

function getAssets() {
    // logo
    const logo = new Image();
    logo.src = checkmarkLogo;
    // plus sign
    const plusSign = new Image();
    plusSign.src = plusSvg;
    // white plus 
    const plusWhiteSign = new Image();
    plusWhiteSign.src = plusWhiteSvg;
    // edit
    const editIcon = new Image();
    editIcon.src = editSvg;
    editIcon.classList.add('todo-icon');
    // trash
    const trashIcon = new Image();
    trashIcon.src = trashSvg;
    trashIcon.classList.add('todo-icon');

    return {
        logo, plusSign, plusWhiteSign, editIcon, trashIcon
    }
}

function appendAssets() {
    getDom().headerLogo.appendChild(getAssets().logo);
    getDom().addProjectBtn.prepend(getAssets().plusSign);
    getDom().addTodoBtn.prepend(getAssets().plusWhiteSign);
}

function bindTodoButtons(detailsButton, todoEditIcon, todoTrashIcon) {
    // detailsButton.addEventListener('click', openDetailsModal);
    todoEditIcon.addEventListener('click', e => openTodoModal(e.target.parentNode));
    todoTrashIcon.addEventListener('click', e => deleteTodo(e.target.parentNode));
}

function deleteTodo(todo) {
    getDom().todoContainer.removeChild(todo);
}


// from my toDoCreator.js
// There are also project (categories) for the to-dos.
import { getForm, getDom, renderTodos, removeSaveBtnEventListeners } from "./UI"

const todoManager = {
    todos: [], 
    createTodo: function() {   
        const todo = {
            title: getForm().title.value,
            description: getForm().description.value,
            dueDate: getForm().dueDate.value,
            project: getForm().project.value
        }
        // check if the div about to be created already exists
        if(todoManager.todos.some(el => el.title === todo.title)) {
            console.log("already exists");
            // alert the user if it already exists.
        } else {
            todoManager.todos.push(todo); // can I substitute todoManager with "this"?
            renderTodos();
            removeSaveBtnEventListeners(); // could maybe be changed with another function that toggles the add/remove event list

        }
    },
    editTodo: function(todoId) {
        console.log(todoId);
        const newData = {
            title: getForm().title.value,
            description: getForm().description.value,
            dueDate: getForm().dueDate.value,
            project: getForm().project.value
        }
        todoManager.todos[todoId] = newData;
        renderTodos();
        removeSaveBtnEventListeners();
    },
};

export default { todoManager };
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Chicle&family=Josefin+Sans&family=Montserrat&family=Poppins&family=Varela+Round&display=swap" rel="stylesheet">
    <title><%= htmlWebpackPlugin.options.title%></title>
</head>
<body>
    <div class="container">
        <div class="header-container">
            <div class="header-logo"></div>
            <h1>LISTO!</h1>
        </div>
        <div class="grid">
            <div class="sidebar-container">
                <nav class="sidebar-links">
                    <ul>
                        <li id="inbox">Inbox</li>
                    </ul>
                    <h2 class="sidebar-title">Projects</h2>
                    <ul>
                        <li id="gym">Gym</li>
                        <li id="study">Study</li>
                        <li id="work">Work</li>
                        <button id="add-project-btn">Add project</button>
                    </ul>
                </nav>
            </div>
            <div class="main">
                <div class="todo-container"></div>
                <button id="add-todo-btn"></button>
            </div>
        </div>
        <dialog class="todo-modal"><!--Any way to uncheck all radio buttons by default-->
            <p id="errorMsg"></p>
            <form method="dialog" id="addTodoForm">
                <label for="title">Title</label>
                <input type="text" id="title" placeholder="Clean the house">
                <label for="description">Description</label>
                <textarea id="description" placeholder="Vacuum even the smallest little gap, then wash floors."></textarea> 
                <label for="dueDate">Due date</label>
                <input type="date" id="dueDate">
                <label for="project">Does it belong to an existing project?</label>
                <select id="project" name="project">
                </select>
                <label for="priority" id="label-priority">Priority</label>
                <fieldset id="priority">
                    <input type="radio" id="low" name="priority">
                    <label for="low" id="label-low">LOW</label> 
                    <input type="radio" id="medium" name="priority">
                    <label for="medium" id="label-medium">MEDIUM</label> 
                    <input type="radio" id="high" name="priority">
                    <label for="high" id="label-high">HIGH</label> 
                </fieldset>
                <div class="form-buttons">
                    <button type="submit" id="todo-modal-save-btn">Save</button>
                    <button type="submit" id="todo-modal-close-btn">Close</button>
                </div>
                
            </form>
        </dialog>
    </div>
</body>
</html>

How to pass stringified JSON as enviorment variable to AWS Lambda (Using GUI)

I am trying to pass stringified JSON an env var to AWS Lambda, but I can’t parse it back.

It works locally (VSCode, Windows), but fails on AWS.

It looks as follow:
{"foo":"bar","hello":"world"}

Passing it through ENV var on launch.json in VSCode works, but fails when I pass it on Lambda.

Unexpected token in JSON at position 0
And if I log the value it got from the ENV I see that it replace every with \

How to launch an app by clicking a button in a email? [closed]

Recently I tried ig reset password, they sent me an email, when I clicked the “reset” button on my laptop, it opened a website for the user to reset password, but when I clicked the “reset” button on my iphone safari, it opened my ig app automatically!
Apparently the “reset” button has 2 links, it activate different link in different device.

How to distinguish between laptop and phone in the email?
How to lauch an app directly by a button in the email?
I would appreciate it if anyone could discuss it with me!

I need to filter an array consisting of dates and time by a date [duplicate]

I have an array that contains hours of seven days, like this:

let arr = [
  "2023-12-12T00:00",
  "2023-12-12T01:00",
  "2023-12-12T02:00",
  "2023-12-12T03:00",
  "2023-12-12T04:00",
  "2023-12-12T05:00",
  "2023-12-12T06:00",
  "2023-12-12T07:00",
  "2023-12-12T08:00",
  "2023-12-12T09:00",
  "2023-12-12T10:00",
  "2023-12-12T11:00",
  "2023-12-12T12:00",
  "2023-12-12T13:00",
  "2023-12-12T14:00",
  "2023-12-12T15:00",
  "2023-12-12T16:00",
  "2023-12-12T17:00",
  "2023-12-12T18:00",
  "2023-12-12T19:00",
  "2023-12-12T20:00",
  "2023-12-12T21:00",
  "2023-12-12T22:00",
  "2023-12-12T23:00",
  "2023-12-13T00:00",
  "2023-12-13T01:00",
  "2023-12-13T02:00",
  "2023-12-13T03:00",
  "2023-12-13T04:00",
  "2023-12-13T05:00",
  "2023-12-13T06:00",
  "2023-12-13T07:00",
  "2023-12-13T08:00",
  "2023-12-13T09:00",
  "2023-12-13T10:00",
  "2023-12-13T11:00",
  "2023-12-13T12:00",
  "2023-12-13T13:00",
  "2023-12-13T14:00",
  "2023-12-13T15:00",
  "2023-12-13T16:00",
  "2023-12-13T17:00",
  "2023-12-13T18:00",
  "2023-12-13T19:00",
  "2023-12-13T20:00",
  "2023-12-13T21:00",
  "2023-12-13T22:00",
  "2023-12-13T23:00",
  "2023-12-14T00:00",
  "2023-12-14T01:00",
  "2023-12-14T02:00",
  "2023-12-14T03:00",
  "2023-12-14T04:00",
  "2023-12-14T05:00",
  "2023-12-14T06:00",
  "2023-12-14T07:00",
  "2023-12-14T08:00",
  "2023-12-14T09:00",
  "2023-12-14T10:00",
  "2023-12-14T11:00",
  "2023-12-14T12:00",
  "2023-12-14T13:00",
  "2023-12-14T14:00",
  "2023-12-14T15:00",
  "2023-12-14T16:00",
  "2023-12-14T17:00",
  "2023-12-14T18:00",
  "2023-12-14T19:00",
  "2023-12-14T20:00",
  "2023-12-14T21:00",
  "2023-12-14T22:00",
  "2023-12-14T23:00"
];

I want to filter this array by the date i get as URL parameter. for example i get 2023-12-14 as URL parameter. i want to use this date to filter the array.

i tried using filter() but i didn’t know what conditions i should write to show my desired result.

How to append data based on a condition inn file using Nodejs

I have a file. I need to append an annotation ( @Circuit(name = backendB) ) if “createEvent” name exists and annotation is not present in that file. I’m not sure how to proceed further. Can anyone
help me what is the way to check and append using streams.

async function appendData() {
  let file_path = "./File/controller.java"

  try {
    let txt = "( @Circuit(name = backendB) )"
    
    const readstream = fs.createReadStream(file_path);
    const updtstrem = fs.createWriteStream("./FileUpload/auditcontroller_test.java")

    readstream
      .on("data", (data) => {
        let temp = data.toString()

        let pos = temp.toString().indexOf("createEvent")
      })
  }
}

How to impliment react js bulid in Laravel 10 for production

I have React JS build in react.zip file:

file stature is like this :


react
|    asset-manifest.json
|___ assets
|    |    css
|    |    fonts
|    |    javascript
|    |    media
|    |    sass
|    favicon.ico
|    index.html
|    logo192.png
|    manifest.json
|    robots.txt
|___ static
|    |___ css
|    |    |    main.f3bcd66c.css
|    |    |    main.f3bcd66c.css.map
|    |___ js
|    |    |    787.f4bb98cd.chunk.js
|    |    |    787.f4bb98cd.chunk.map
|    |    |    main.af7c97e4.js
|    |    |    main.af7c97e4.js.LICENSE.txt
|    |    |    main.af7c97e4.js.map

How to implement this build in Laravel project for view on production server.

I have tried this to build unzip in side public folder.

  1. Route defined :
    Route::get('/', function () {
        return view('frontend.index');
    });
  1. root/resource/view/frontend/index.blade.php code :
    <!DOCTYPE html>
    <html lang="{{ app()->getLocale() }}">
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">

            <title>Your Application Name</title>

            <script src="{{ asset('react/static/js/main.af7c97e4.js') }}" defer></script>

        </head>
        <body>
            <div id="root"></div>
        </body>
    </html>

Some react build files data looks like this :
a) asset-manifest.json code :

    {
      "files": {
        "main.css": "/static/css/main.f3bcd66c.css",
        "main.js": "/static/js/main.af7c97e4.js",
        "static/js/787.f4bb98cd.chunk.js": "/static/js/787.f4bb98cd.chunk.js",
        "index.html": "/index.html",
        "main.f3bcd66c.css.map": "/static/css/main.f3bcd66c.css.map",
        "main.af7c97e4.js.map": "/static/js/main.af7c97e4.js.map",
        "787.f4bb98cd.chunk.js.map": "/static/js/787.f4bb98cd.chunk.js.map"
      },
      "entrypoints": [
        "static/css/main.f3bcd66c.css",
        "static/js/main.af7c97e4.js"
      ]
    }

b) index.html code :

    <!doctype html>
    <html lang="en">

    <head>
        <meta charset="utf-8" />
        <link rel="icon" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <meta name="theme-color" content="#000000" />
        <meta name="description" content="Web site created using create-react-app" />
        <link rel="apple-touch-icon" href="/logo192.png" />
        <link rel="manifest" href="/manifest.json" />
        <title>React App</title>
        <base href="/./" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" />
        <link rel="stylesheet" href="assets/css/owl.carousel.css" />
        <link rel="stylesheet" href="assets/css/bootstrap.min.css" />
        <link rel="stylesheet" href="assets/css/style.css" />
        <script defer="defer" src="/static/js/main.af7c97e4.js"></script>
        <link href="/static/css/main.f3bcd66c.css" rel="stylesheet">
    </head>

    <body><noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="root"></div>
        <script src="./assets/javascript/jquery.min.js"></script>
        <script src="./assets/javascript/owl.carousel.min.js"></script>
        <script src="./node_modules/owl.carousel/dist/owl.carousel.min.js"></script>
        <script src="./assets/javascript/bootstrap.bundle.min.js"></script>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="./assets/javascript/gsap.min.js"></script>
        <script src="./assets/javascript/ScrollTrigger.min.js"></script>
        <script src="./assets/javascript/gsap/ScrollToPlugin.min.js"></script>
        <script src="./assets/javascript/serviceSec.js"></script>
    </body>

    </html>

Now when I hit url ‘/’ showing error in console :

=> Uncaught TypeError: e is undefined in OwlCarousel.js file.

Where is issue to implement this react js build?

how can i tell to chrome to inspect an element in my js function?

Suppose we have a function like this:

function showProps(el){
    inspect(el);
}

what is the solution for this that when we call this function the chrome open the inspecting window and locate the el element?

In the chrome console when used inspect(document.body) it does what we want and opens the inspecting section and select the body element.
but when we run in my function, it says the inspect() method is undefined and unknown.

How can I add a scroll delay during autoplay with react-native-reanimated-carousel

I am using react native reanimated carousel. What I intend is to extend the time spent viewing each rendered item before scrolling to the next item. Like an autoplay delay. Here is the code:

  <Carousel
            loop
            width={width}
            data={data}
            scrollAnimationDuration={1000}
            autoPlay={true}
            renderItem={({item, index}) => {
              const {title, desc, image: Image, style} = item;
              return (
                <View
                  style={{
                    flex: 1,
                    justifyContent: 'center',
                  }}>
                  <Image height={height / 3} style={style} />
                  <Text
                    style={[
                      styles.textCenter,
                      styles.whiteColor,
                      {fontSize: 24, marginTop: 20, fontWeight: '900'},
                    ]}>
                    {title}
                  </Text>
                  <Text
                    style={[
                      styles.textCenter,
                      styles.whiteColor,
                      styles.font12,
                      styles.p20,
                      {maxWidth: 350, alignSelf: 'center', lineHeight: 18},
                    ]}>
                    {desc}
                  </Text>
                </View>
              );
            }}
          />

Here is the output, the current display duration is about 1 second. I would like to extend it to 3 seconds or so.

enter image description here

how to open JSON file from URL in next.js

I’m trying to open a JSON file after uploading it to the server from a URL .. then parsing it and viewing its features of it inside google Maps.. but it is unable to open it as an error is being returned from “fs” lib.

here is my code :

"use client"
import React from 'react'
import { GoogleMap, useJsApiLoader } from '@react-google-maps/api';
import { useState } from "react";
import { createClient } from '@supabase/supabase-js';
import { subaBaseURL, subaBaseKey,googleMapsApiKey } from './enums'
import { v4 as uuid } from 'uuid';
import { promises as fs } from 'fs';

const containerStyle = {
    width: '100',
    height: '400px'
};

const center = {
    lat: 29.95375640,
    lng: 31.53700030
};

function Map() {

    const [isUploadingFile, setIsUploadingFile] = useState(false)
    const [thefile, setTheFile] = useState([])
    const [theName, setTheName] = useState("")
    const [map, setMap] = React.useState(null)
    const [isLoading, setIsLoading] = useState(false)
  
    const supabase = createClient(subaBaseURL, subaBaseKey);
  
  
    function toggleFileUploading() {
      setIsUploadingFile(!isUploadingFile)
    }
    function toggleLoading(){
        setIsLoading(!isLoading)
    }
  
    async function uploadShapeFile(e) {
      e.preventDefault()
      toggleLoading()
      let myUUID = uuid();
      const finalFileName = `${myUUID}${theName}.json`;
      const { data, error } = await supabase.storage.from('kml_files').upload(`test/${theName}/${finalFileName}`, thefile)
      const publicUrl = supabase.storage.from('kml_files').getPublicUrl(`test/${theName}/${finalFileName}`)
      console.log(publicUrl)
      createNewInput(publicUrl['data']['publicUrl'])
    }



    async function createNewInput(fileURL) {
      try {
        const response = await fetch(fileURL);
        console.log(response)
        const geojsonData = await response.json();
        const file = await fs.readFile(geojsonData.url, 'utf8');
        const data = JSON.parse(file);
        console.log(data.geometryType)
        // Assuming the GeoJSON features are in the 'features' property
        const geojsonFeatures = geojsonData.features;
    
        // Use the map instance to add GeoJSON features
        if (map) {
          // Clear existing markers or layers if needed
          // For example: map.data.forEach(feature => map.data.remove(feature));
    
          // Add GeoJSON features to the map
          geojsonFeatures.forEach(feature => {
            const geometry = feature.geometry;
            const attributes = feature.attributes;
    
            // Create a new Google Maps Data layer feature
            const googleFeature = new window.google.maps.Data.Feature({
              geometry: new window.google.maps.Data.Polygon([geometry.rings]),
              properties: attributes,
            });
    
            // Add the feature to the map
            map.data.add(googleFeature);
          });
    
          // Automatically fit the map to the bounds of the GeoJSON features
          const bounds = new window.google.maps.LatLngBounds();
          map.data.forEach(feature => {
            feature.getGeometry().forEachLatLng(latLng => {
              bounds.extend(latLng);
            });
          });
          map.fitBounds(bounds);
        }
      } catch (error) {
        console.error('Error loading GeoJSON data:', error);
      }

    }

    const { isLoaded } = useJsApiLoader({
        id: 'google-map-script',
        googleMapsApiKey: googleMapsApiKey
    })


    const onLoad = React.useCallback(function callback(map) {
        // This is just an example of getting and using the map instance!!! don't just blindly copy!
        const bounds = new window.google.maps.LatLngBounds(center);
        map.fitBounds(bounds);

        setMap(map)
    }, [])

    const onUnmount = React.useCallback(function callback(map) {
        setMap(null)
    }, [])

    return isLoaded ? (
        <>
              {isUploadingFile &&
        <button onClick={toggleFileUploading} type="button" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">Upload new file </button>
      }
      {!isUploadingFile &&
        <div>
          <form onSubmit={uploadShapeFile}>
            <label for="file_name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">File name</label>
            <input type="text" id="file_name" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" onChange={e => setTheName(e.target.value)} required />
            <br></br>
            <label class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" for="file_input">Upload file</label>
            <input class="block w-full text-sm text-gray-900 border border-gray-300 rounded-lg cursor-pointer bg-gray-50 dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="file_input" type="file" onChange={e => setTheFile(e.target.files[0])} required />
            <br></br>
            <button type="submit" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">Upload</button>
            <button onClick={toggleFileUploading} type="button" class="text-white bg-gray-800 hover:bg-gray-900 focus:outline-none focus:ring-4 focus:ring-gray-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-gray-800 dark:hover:bg-gray-700 dark:focus:ring-gray-700 dark:border-gray-700">Cancel</button>

          </form>
        </div>

      }
        <GoogleMap
            mapContainerStyle={containerStyle}
            center={center}
            zoom={10}
            onLoad={onLoad}
            onUnmount={onUnmount}
        >
            { /* Child components, such as markers, info windows, etc. */}
            <></>
        </GoogleMap>

        </>
    ) : <></>
}

export default React.memo(Map)

and here is the error am getting :

./src/app/components/Map/Map.jsx:8:0
Module not found: Can't resolve 'fs'
   6 | import { subaBaseURL, subaBaseKey,googleMapsApiKey } from './enums'
   7 | import { v4 as uuid } from 'uuid';
>  8 | import { promises as fs } from 'fs';
   9 |
  10 | const containerStyle = {
  11 |     width: '100',

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./src/app/components/index.js
./src/app/page.js

Having trouble setting svg color when rendering svg file

I’m creating a svg logo maker for a class project and the program works great expect when logo.svg is generated the fill is left blank and for the life of me I’m unable to figure out why. When ran in the terminal using “node index”, inquirer prompts the user for all needed questions and they all are shown in the generated file expect in the shape tag. Any help is greatly appreciated!

Example svg file:

<svg version="1.1" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <circle cx="150" cy="100" r="80" fill=""/> <text x="150" y="125" font-size="60" text-anchor="middle" fill="pink">ABC</text> </svg>

Heres my index.js file:

class svg {
  constructor() {
    this.textElement = "";
    this.shapeElement = "";
  }
  render() {
    return `<svg version="1.1" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
                ${this.shapeElement}
                ${this.textElement}
                </svg>`;
  }
  setText(text, color) {
    this.textElement = `<text x="150" y="125" font-size="60" text-anchor="middle" fill="${color}">${text}</text>`;
  }
  setShape(shape, color) {
    this.shapeElement = shape.render(color);
  }
}

function writeFile(fileName, data) {
  fs.writeFile(fileName, data, (err) => {
    if (err) throw err;
    console.log("The file has been created!");
  });
}

async function start() {
  let svgString = "";
  const svgFile = "logo.svg";

  const answers = await inquirer.prompt(questions);

  let userText = answers.text;
  let userTextColor = answers["text-color"];
  let userShape = answers.shape;
  let userShapeColor = answers["shape-color"];

  const newSvg = new svg();
  newSvg.setText(userText, userTextColor);

  switch (userShape) {
    case "Square":
      newSvg.setShape(new Square(), userShapeColor);
      break;
    case "Circle":
      newSvg.setShape(new Circle(), userShapeColor);
      break;
    case "Triangle":
      newSvg.setShape(new Triangle(), userShapeColor);
      break;
    default:
      console.log("Invalid shape");
  }
  svgString = newSvg.render();
  writeFile(svgFile, svgString);
}

start();

How can I use debounce to avoid triggering the graphQL query on every keystroke in react?

I was given a new task and I have to debounce the input value to prevent a backend request on each keystroke and on the other hand CollectionsAutocomplete should have an internal useState with an input value, that is linked to the generalQuery variable.
Right now I was able to add the internal useState but I don’t know how to apply the debounce.
The CollectionsAutocomplete is a component that is located in our library and I use it in a different project.
Here is the CollectionsAutocomplete in the library:

type CollectionsAutocompleteProps = GenericFetchAutocompletePropsWrapperType<StyleCollection>
  & {
    targetBrandNumber: string;
    queryVariables?: Exact<{
      brandNumber: string;
      generalQuery?: InputMaybe<string> | undefined;
      pagination: PaginationInput;
    }> | undefined;
    onInputChange?: (inputValue: string) => void;
  };

export const CollectionsAutocomplete = (props: CollectionsAutocompleteProps): ReactElement => {
  const { queryVariables, targetBrandNumber, value, handleOnBlur, handleOnChange, handleOnFocus, limitTags, onInputChange } = props;
  const [inputValue, setInputValue] = useState<string>('');

  return (
    <GenericFetchAutocomplete<
      StyleCollection,
      GetAllCollectionsQuery,
      GetAllCollectionsQueryVariables,
      true>
      limitTags={limitTags}
      value={value}
      dataMapper={(data): Array<StyleCollection> =>
        data.collections?.edges?.map((edge) => edge?.node).filter(sortUtil.isDefined) ?? []}
      fetchQuery={GetAllCollectionsDocument}
      inputLabels={{
        plural: 'Collections',
        single: 'Collection',
      }}
      queryOptions={{
        fetchPolicy: 'network-only',
        context: { clientName: GraphClientNames['backend'] },
        variables: {
          generalQuery: queryVariables?.generalQuery ?? inputValue,
          brandNumber: targetBrandNumber,
          pagination: {
            first: 100,
            after: null,
          },
          ...queryVariables ?? {},
        },
      }}
      tagLabelFormatter={(option): string => `${option.collectionTerm} (${option.collectionName})`}
      textFieldProps={{
        ...props.textFieldProps,
        placeholder: value.length === 0 ? 'Select' : '',
        sx: {
          ['& ::placeholder']: {
            color: '',
          },
        },
      }}
      idKey='collectionNumber'
      optionLabelFormatter={(option): string => `${option.collectionTerm} (${option.collectionName})`}
      multiple
      onBlur={handleOnBlur}
      onChange={handleOnChange}
      onFocus={handleOnFocus}
      onInputChange={(event): void => {
        const newValue = (event.target as HTMLInputElement).value;
        setInputValue(newValue);
        onInputChange?.(newValue);
      }}
    />
  );
};

here is how I use the CollectionsAutocomplete in my project:

<CollectionsAutocomplete
                  value={collectionsValue}
                  textFieldProps={{ required: true }}
                  targetBrandNumber={selectedBrands[0]?.brandNumber}
                  queryVariables={{
                    pagination: {
                      first: 200,
                      after: null,
                    },
                  }}
                  handleOnChange={(e, v): void => {
                    if (v !== null) {
                      setCollectionsValue(v);
                    } else {
                      setCollectionsValue([]);
                    }
                  }}
                  onInputChange={(newValue: string): void => {
                    console.log('Input value changed:', newValue);
                  }}
                />

I’m a bit lost about how to apply the logic.

How can I add onclick href to “Got It ! ” button in customizable cookie consent banner script

Here is the location of the script creation : https://app.websitepolicies.com/policies/create/cookie-consent-banner

<script src="https://cdn.websitepolicies.io/lib/cconsent/cconsent.min.js" defer></script>
<script>
  window.addEventListener("load", function() {
    window.wpcb.init({
      "border": "thin",
      "corners": "small",
      "colors": {
        "popup": {
          "background": "#ffe4e1",
          "text": "#000000",
          "border": "#c25e5e"
        },
        "button": {
          "background": "#c25e5e",
          "text": "#ffffff"
        }
      },
      "position": "bottom",
      "content": {
        "button": "Got It !",
        "message": "This website uses cookies to ensure you get the best experience on our website"
      }
    })
  });
</script>

Please see the result in the attached image.
Thank you.

Favicon generator issue

how can i change the default favicon (if a website doesn’t have a favicon, it shows a blurry image of a sphere.) I want to include an image i have created .. let’s say “/[email protected]” ,i need this as default if no other images are present. How do i do it ?

btw, here’s the link :
https://www.google.com/s2/favicons?domain=${domain}&sz=${size}

i tried :
<Avatar
<img
src={https://www.google.com/s2/favicons?domain=${i.link}&sz=64}
className=”w-14″
alt=””
onError={(e) => {
// If the favicon fails to load, set the source to the fallback image
e.target.src = ‘/[email protected]’;
}}
/>
yet i get the blurry favicon.