Getting error in updating a document in mongodb using mongoose as ODM and nextjs in frontend [closed]

import React, { useEffect, useState } from 'react'
import Image from 'next/image'
import underline from "../Image/underline.png"
import Link from "next/link"
import { useUser } from '@clerk/clerk-react'
import { ClerkProvider } from '@clerk/nextjs'
import { Github } from 'lucide-react'
import DialogViewer from "../Components/Dialog"
import { FaTrashAlt } from "react-icons/fa";
import { MdEdit } from "react-icons/md";

const FormDisplay = () => {
    const { isLoaded, user } = useUser()
    console.log(user)
    const [formdata, setFormdata] = useState({
        name_project: "",
        desc_project: "",
        url_project: "",
        name_comp: "",
        date_comp: "",
        url_comp: "",
        image_url: "",
        website_url: ""
    })
    let name, value;
    const handleInput = (e) => {
        name = e.target.name;
        value = e.target.value;
        setFormdata({ ...formdata, [name]: value })
    }

    const submit = async (e) => {
        e.preventDefault()
        const { name_project, desc_project, url_project, name_comp, date_comp, url_comp, image_url, website_url } = formdata
        const formData = {
            "name_project": name_project,
            "desc_project": desc_project,
            "url_project": url_project,
            "prizes": [
                {
                    "name_comp": name_comp,
                    "date_comp": date_comp,
                    "url_comp": url_comp
                }
            ],
            "image_url": image_url,
            "website_url": website_url,
            "clerkID": user.id
        }

        const response = await fetch("/api/addProject", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(formData)
        })

        const result = await response.json()
        console.log(result)
        if (result.success === true) {
            window.location.reload()
        }

    }
    return (
        <div className='w-auto pl-5'>
            <form action="">
                <br />
                <div className='flex gap-2 text-lg font-bold text-black '><p className='w-56 text-left pl-5'>Title:</p> <input type="text" name="name_project" id="name_project" onChange={handleInput} placeholder='Enter Title...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Description:</p> <textarea name="desc_project" id="desc_project" onChange={handleInput} placeholder='Enter Description...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Project URL:</p> <input type="text" name="url_project" id="url_project" onChange={handleInput} placeholder='Enter Project URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Image URL:</p> <input type="text" name="image_url" id="image_url" onChange={handleInput} placeholder='Enter Image URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Website URL:</p> <input type="text" name="website_url" id="website_url" onChange={handleInput} placeholder='Enter Website URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Name of Competition:</p> <input type="text" name="name_comp" id="name_comp" onChange={handleInput} placeholder='Enter Name of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Date of Competition:</p> <input type="text" name="date_comp" id="name_comp" onChange={handleInput} placeholder='Enter Date of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>URL of Competition:</p> <input type="text" name="url_comp" id="url_comp" onChange={handleInput} placeholder='Enter URL of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>

                <button className='bg-black text-white font-bold px-4 py-2 rounded-md mt-8' onClick={submit}>Submit</button>
            </form>
        </div>
    )
}

const Page = () => {
    const [projectData, setprojectData] = useState(null)
    const [runned, setRunned] = useState(false)
    const { isLoaded, user } = useUser()
    const [selectedProjectId, setSelectedProjectId] = useState(null);

    const getProjectData = async () => {
        if (!runned) {
            try {
                const response = await fetch("/api/getProject");
                const data = await response.json();
                setprojectData(data.data);
                // console.log("Fetched Data:", data);
                setRunned(true);
            } catch (error) {
                console.error("Cannot fetch data: ", error);
            }
        }
    };
    const deleteData = async (item) => {
        const _id = item.currentTarget.id
        console.log(_id)
        const confirmed = window.confirm("Are you sure you want to delete this project?")
        if (confirmed == true) {
            try {
                const response = await fetch("/api/deleteProject", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ _id: _id })
                })
                const data = await response.json()
                console.log(data)
                if (data.success === true) {
                    window.location.reload()
                }
            } catch (error) {
                console.log("Cannot delete the project: ", error)
            }
        }
    }

    useEffect(() => {
        getProjectData();
    }, []);

    const Edit_FormDisplay = (item) => {
        const [data, setData] = useState()

        const [formdata, setFormdata] = useState({
            name_project: "",
            desc_project: "",
            url_project: "",
            name_comp: "",
            date_comp: "",
            url_comp: "",
            image_url: "",
            website_url: ""
        })
        useEffect(() => {
            const fetchOneProjectData = async () => {
                const _id = item.currentTarget.id
                console.log(_id)
                try {
                    const response = await fetch("/api/getOneProject", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ _id: _id })
                    })
                    const result = await response.json()
                    console.log(result)
                    setData(result.data)
                } catch (error) {
                    console.log("Cannot delete the project: ", error)
                }
            }

            fetchOneProjectData()
        }, [item])

        useEffect(() => {
            if (data) {
                setFormdata({
                    name_project: data.name_project || "",
                    desc_project: data.desc_project || "",
                    url_project: data.url_project || "",
                    name_comp: data.prizes?.[0]?.name_comp || "",
                    date_comp: data.prizes?.[0]?.date_comp || "",
                    url_comp: data.prizes?.[0]?.url_comp || "",
                    image_url: data.image_url || "",
                    website_url: data.website_url || ""
                });
            }
        }, [data]);
        const handleInput = (e) => {
            const { name, value } = e.target;
            setFormdata({ ...formdata, [name]: value });
        };

        const submit = async (e) => {
            e.preventDefault();
            const { name_project, desc_project, url_project, name_comp, date_comp, url_comp, image_url, website_url } = formdata;
            const formData = {
                name_project,
                desc_project,
                url_project,
                prizes: [
                    {
                        name_comp,
                        date_comp,
                        url_comp
                    }
                ],
                image_url,
                website_url,
            };

            try {
                const response = await fetch("/api/editProject", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(formData)
                });
                const result = await response.json();
                console.log(result);
                if (result.success) {
                    window.location.reload();
                }
            } catch (error) {
                console.log("Error editing project:", error);
            }

        }
        return (
            <div className='w-auto pl-5'>
                <form action="">
                    <br />
                    <div className='flex gap-2 text-lg font-bold text-black '><p className='w-56 text-left pl-5'>Title:</p> <input type="text" name="name_project" id="name_project" onChange={handleInput} placeholder='Enter Title...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Description:</p> <textarea name="desc_project" id="desc_project" onChange={handleInput} placeholder='Enter Description...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Project URL:</p> <input type="text" name="url_project" id="url_project" onChange={handleInput} placeholder='Enter Project URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Image URL:</p> <input type="text" name="image_url" id="image_url" onChange={handleInput} placeholder='Enter Image URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Website URL:</p> <input type="text" name="website_url" id="website_url" onChange={handleInput} placeholder='Enter Website URL...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Name of Competition:</p> <input type="text" name="name_comp" id="name_comp" onChange={handleInput} placeholder='Enter Name of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>Date of Competition:</p> <input type="text" name="date_comp" id="name_comp" onChange={handleInput} placeholder='Enter Date of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>
                    <div className='flex gap-2 text-lg font-bold text-black mt-3'><p className='w-56 text-left pl-5'>URL of Competition:</p> <input type="text" name="url_comp" id="url_comp" onChange={handleInput} placeholder='Enter URL of Competition...' className='bg-white px-2 rounded-md text-box font-normal text-base' /></div>

                    <button className='bg-black text-white font-bold px-4 py-2 rounded-md mt-8' onClick={submit}>Submit</button>
                </form>
            </div>
        )
    }


    return (
        <div className='bg-black sm:h-auto h-auto w-auto pt-16 text-white border-b-2 border-gray-600 scale-100 '>
            <h1 className='cedarville-cursive-regular text-4xl font-extrabold tracking-wide text-center mt-5 mb-14'>My Projects</h1>
            <div className='w-auto text-right mr-8'>
                {!user ? "" : !user.publicMetadata.role ? "" : user.publicMetadata.role === "admin" ? <DialogViewer trigger_name={"+ Add New Project"} title={"Add a New Project"} description={"Fill the following fields to create/add a new project"} formElement={<FormDisplay />} /> : ""}
            </div>
            <Image src={underline} width={470} height={50} alt='underline' className='brightness-[100] absolute top-[6.7rem] left-[32rem] scale-75'></Image>

            {projectData === null ? (<div> Loading.... </div>) :

                (Array.isArray(projectData) && projectData.map((data) => {
                    return (
                        <div className='flex bg-gray-600 bg-opacity-50 m-3 rounded-lg h-96 scale-[98%] hover:scale-100 transition-all h-auto' key={data.name_project}>
                            <div className='w-[50%] p-7'>
                                <div className="relative w-[500px] h-[300px]" style={{ backgroundImage: `url(${data.image_url})`, backgroundSize: "contain", backgroundRepeat: "no-repeat", backgroundPosition: "center" }}>
                                    {/* <Image
                                    src={data.image_url}
                                    fill  // ✅ Makes the image fill the container
                                    className="rounded-lg object-cover"
                                    alt="card-image"
                                /> */}
                                </div>
                            </div>
                            <div className='w-[70%] p-7'>
                                <div className="w-[100%] text-right flex gap-3 justify-end ">
                                    {!user ? "" : !user.publicMetadata.role ? "" : user.publicMetadata.role === "admin" ?
                                        <button className='text-red-500 bg-black w-8 h-8 text-center rounded-md pl-2' id={data._id} onClick={deleteData}><FaTrashAlt /></button>
                                        : ""}
                                    {!user ? "" : !user.publicMetadata.role ? "" : user.publicMetadata.role === "admin" ? <button
                                        onClick={Edit_FormDisplay}
                                        id={data._id}
                                        className="bg-black text-green-500 h-8 w-auto font-bold rounded-lg px-2"
                                    ><DialogViewer trigger_name={<MdEdit />} title={"Edit an existing Project"} description={"Fill the following fields to edit a new project"} formElement={<Edit_FormDisplay />} /></button> : ""}
                                </div>
                                <div className='flex mb-7'>
                                    <div className='w-[65%] border-r-2 border-r-white mr-3'>
                                        <h2 className='text-white text-3xl font-extrabold tracking-wider mb-5 border-b-2 border-r-white mr-3 w-40'>{data.name_project}</h2>
                                        <p>{data.desc_project}</p>
                                    </div>
                                    <div>
                                        <h3 className='text-red-400 text-xl font-extrabold tracking-wide mb-5 border-b-2 border-b-white mr-3 w-20'>Prizes</h3>
                                        <p className=''>
                                            {Array.isArray(data.prizes) && data.prizes.map((data) => {
                                                console.log(data)
                                                return (
                                                    <>
                                                        <div className='flex' key={data.name_comp}><p>Name: &nbsp;</p><p className='cursor-pointer text-blue-600' >{data.name_comp}</p></div>
                                                        <p className='font-bold'>Participated in: {data.date_comp}</p>
                                                    </>
                                                )
                                            })}
                                        </p>
                                    </div>
                                </div>
                                <Link href={data.url_project} target='_blank'><button className='bg-green-500 text-black h-9 w-44 font-bold rounded-lg'><div className='flex'><Github className="h-5 w-5 pt-1 ml-3" /> &nbsp;&nbsp;View On Github</div></button></Link>&nbsp;&nbsp;
                                <Link href={data.website_url} target='_blank'><button className='bg-green-500 text-black h-9 w-32 font-bold rounded-lg'>Visit Website</button></Link>
                            </div>
                        </div>
                    )
                }))}
        </div>

    )
}



export default Page

This is the Dialog Viewer

import React from 'react'
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "../../components/components/ui/dialog"

const DialogViewer = ({ trigger_name, title, description, formElement }) => {
    return (
        <div>
            <Dialog className="text-black w-96">
                {trigger_name === "+ Add New Project"
                    ? (
                        <DialogTrigger className='bg-green-500 text-black h-9 w-auto font-bold rounded-lg px-2'>
                            {trigger_name}
                        </DialogTrigger>
                    )
                    : (
                        <div className="bg-black text-green-500 h-8 w-auto font-bold rounded-lg px-2">
                            <DialogTrigger>
                                {trigger_name}
                            </DialogTrigger>
                        </div>
                    )
                }
                <DialogContent className='text-black'>
                    <DialogHeader>
                        <DialogTitle className='text-black text-2xl font-extrabold text-center'>{title}</DialogTitle>
                        <DialogDescription className='text-lg'>
                            <p className='text-center'>{description}</p>
                            {formElement}
                        </DialogDescription>
                    </DialogHeader>
                </DialogContent>
            </Dialog>
        </div>
    )
}

export default DialogViewer

I have been trying to implement a page where I can display all the projects from the MongoDB database and perform all crud operations. The create, read, and delete functions are working fine. But when it comes to the edit part it is becoming a bit complex.

I am also getting this error: –
This error is according to me related to the function EditFormDisplay which is being called by a button. What can be an alternate method for this?

Error message: –
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.

For Your Info Dialog Viewer is taken from Schad cn UI which I made a separate component and its details are the props that I can pass from any component according to my need where I need to use it.

Please help me solve the problem in the above image

HTML Table Filtering via JavaScript Results in Disappearance of Sub-Tables

Using the following JavaScript, I am successfully filtering a table; however, sub-tables within each row are disappearing.

function filter_country_table_country_name_or_code() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("country_name_or_code_input");
  filter = input.value.toUpperCase();
  table = document.getElementById("country_table");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

function clear_country_table_country_name_or_code_field() {
    document.getElementById('country_name_or_code_input').value = "";
    filter_country_table_country_name_or_code()
}
<table id="country_table">
  <tr>
    Main Table Content Row 1
    <table>
      <tr>
        <td>
          Sub-Table Content Row 1
        </td>
      </tr>
    </table>
  </tr>
  <tr>
    Main Table Content Row 2
    <table>
      <tr>
        <td>
          Sub-Table Content Row 2
        </td>
      </tr>
    </table>
  </tr>
</table>

What could be causing this and what needs to change in my JavaScript?

Thank you.

How can I force an Infinity number to be a string in JavaScript, when I cannot control how I receive the input?

We receive data from a client. They pass it as XML which we use an automation platform (make.com) to translate.

We do not know the data coming in, we use a JavaScript function to process data.

One piece of data is represented as an Infinite number. We cannot convert it to String but we need to. Sample code below of the struggle.

function ____(val){
    return ``+val;
}
console.log(____(23E1028))

We need this function to return the string value, but we cannot control the data being passed to the function.

Some attempts:

23E1028
Infinity
String(23E1028)
'Infinity'
''+23E1028
'Infinity'
23E1028.charAt(0);
VM193:1 Uncaught TypeError: Infinity.charAt is not a function
23E1028
Infinity
String(23E1028)
'Infinity'
''+23E1028
'Infinity'
23E1028.charAt(0);
VM193:1 Uncaught TypeError: Infinity.charAt is not a function
function ____(val){
  return ``+val;
}
console.log(____(23E1028))

Is this a good use case for composition via higher-order functions?

I have a JavaScript project I’m working on and am wondering if I should switch from a long list of switches and if/then statements to a more compositional approach as I contemplate adding in a new, relatively large, feature.

In short, my program takes a large JSON file and does 2 recursive runs on it. The first run gathers information needed for the second run and does some structural edits, and the second performs performs a variety of straightforward html and formatting conversions to markdown.

The incoming JSON is pretty ubiquitous in the type and quantity of properties they have (around 4-6 properties). The main conversion loop in question here, will per JSON node, do the following:

  1. Pass the node to about 5 different functions that will always run on every node (linkify, turndown conversion, some other formatting conversions, etc)
  2. Based on the structure and type of the node, (about 15-20 options available), perform specific tasks that are exclusive to each other (this is done in a switch statement).
  3. The loop then will write the output to a map which later writes the content to markdown pages.

Another important note is that I have about 15 configuration options that are set once and performed uniformly across the entire JSON conversion process.

This setup works great so far. But here’s the kicker, the last main feature I need to implement is support for embedded script statements (found in the preconversion source JSON) that can:

  1. turn on/off configuration options on the fly
  2. treat certain nodes as a different type
  3. turn on/off certain conversions on each node
  4. perform certain text search/replacement
  5. Lots of other actions

And each of these actions can be performed:

  1. On the current node, or children only, or recursively down to all grandchildren
  2. Lots of other action parameters…

I needed a list-like entity anyway to pass down to each recursive call to keep track of what the action script wanted, so I was thinking maybe that’s the way to go for all the functionality?

Abstractly, what I have now is not an explosion of the kinds of actions that can be performed, because that feature set is pretty much all implemented, but instead an explosion of the combinations of actions that can be implemented per node.

I was thinking that rather than just a carefully ordered list of imperative if/then and switch statements, I would just re-work all the functionality into a set of discrete functions that can be composed, per node, based on the final result of all the configuration options, the action script tweaks, the structure of the nodes, etc. I would imagine that the final result would be a stack of objects that, containing relevant info and methods, could just be executed in order on the current node until satisfied.

Does this sound like a good use of composition via factory functions here?

Vue charts js crashing on line chart

Using vue charts js I’m having problems with line charts that have a lot of data, such as a 30-day report with each point in the line chart being one minute of each day, that is (43800 points). This way the chart takes a long time to assemble and after assembly the zoom functionality of the same get

Apexcharts line and area charts only showing tooltips if grid is enabled

I’m using vue-apexcharts wrapper (tried both 1.6.x and 1.7.0 versions) and apexcharts 4.4.0 / 4.5.0 (also tried both versions). I was able to do extensive customizations to chart visuals, but I’m stuck for days trying to show the default tooltip when the chart contents are hovered without enabling the grid option.
Here’s the desired result, except for the horizontal lines in chart’s content:
line chart containing tooltip, but also containing horizontal grid lines

So I believed that setting chart option tooltip.enabled to true was enough for rendering that beautiful tooltip in the chart, close to the place I’m hovering, but in my charts it is not. There’s probably other settings preventing my chart from working as desired.
What I found out is that I need to set grid.show to true for tooltip to appear. If I try to set grid.yaxis.lines.show to false, to try to trick the settings to show my tooltip and not to render the grid horizontal lines, the tooltip does not show up. If I disable the yaxis lines but enable grid.xaxis.lines.show my tooltip also works, but then I have to deal with undesired vertical lines, same problem as before.

Here are the objects that I feed to my vue-apexcharts wrapper, except that I anonymized my data:

series = [
   {
       "name": "my y axis title",
       "data": [
           [
               1659236400000,
               "74.83"
           ],
           [
               1659841200000,
               "83.75"
           ],
           [
               1660446000000,
               "318.74"
           ],
...
           [
               1665284400000,
               "296.60"
           ],
           [
               1665889200000,
               "200.08"
           ],
           [
               1666494000000,
               "192.09"
           ],
       ]
   }
]

options = {
   "colors": [
       "#9C27B0"
   ],
   "chart": {
       "type": "line",
       "toolbar": {
           "show": false
       },
       "zoom": {
           "enabled": false
       }
   },
   "fill": {
       "colors": [
           "#9C27B0"
       ],
       "opacity": 0.8,
       "type": "solid"
   },
   "grid": { //if I disable grid, or disable both axis, my tooltip stops working
       "show": true,
       "xaxis": {
           "lines": {
               "show": false
           }
       },
       "yaxis": {
           "lines": {
               "show": true
           }
       }
   },
   "legend": {
       "show": false
   },
   "tooltip": { //I can delete tooltip object and the grid tooltip keeps working
       "enabled": true,
       "intersect": false
   },
   "annotations": {
       "yaxis": [],
       "xaxis": [],
       "points": []
   },
   "stroke": {
       "width": 2,
       "curve": "straight",
       "lineCap": "round"
   },
   "xaxis": {
       "axisTicks": {
           "show": true
       },
       "labels": {
           "show": true,
           "rotate": 0,
           "hideOverlappingLabels": true
       },
       "convertedCatToNumeric": true
   },
   "yaxis": {
       "max": 700,
       "min": 0,
       "title": {
           "text": "my axis title"
       },
       "labels": {}
   }
}

How can I access the ${orderId} and ${payment} which is present in the method chaining of the promise to my last block of promise?

const cart = ["shoes","shirts","boxers","pants"]

function creatOrder(cart){
    return new Promise((resolve,reject)=>{
        if(!ValidateCart(cart)){
            const err = new Error('Cart is not valid')
            reject(err)
        }
        const orderId = 'MK899'
        if(orderId){
            resolve(orderId)
        }
    })
}

function ProceedtoPayment(orderId){
    return new Promise((resolve,reject)=>{
        if(!orderId){
            reject("Payment has failed.Please try again after some time")
        }
        const payment = "$500"
        if(payment){
            resolve(payment)
        }
    })
}

function UpdateWalletBalance(payment){
    return new Promise((resolve,reject)=>{
        if(!payment){
            reject("Balance did not change since Payment failed")
        }
        const remaningBalance = "$100"
        if(remaningBalance){
            resolve(remaningBalance)
        }
        
    })
}


creatOrder(cart)
.then((orderId)=>{
    console.log(orderId, "OrderId verified.Please move on to the payment")
    return orderId
})
.catch((err)=>{
    console.log(err.message)
})
.then((orderId)=>{
    return ProceedtoPayment(orderId)
})
.then((payment)=>{
    console.log(`Payment of ${payment} has been received`)
    return payment
})
.catch((payment)=>{
    console.log(payment)
})
.then((payment)=>{
    return UpdateWalletBalance(payment)
})
.then((remaningBalance)=>{
    console.log(`your remaining money is ${remaningBalance}`)
})
.catch((remaningBalance)=>{
    console.log(remaningBalance)
})

function ValidateCart(){
    return true
}

Method chaining: I want to access the orderId and payment which is present at the topmost of the .then in the last .then of promise. I am unable to so it is throwing me an error of ReferenceError: payment is not defined.

I tried returning the parameter and returning the function inside then block but it did not work. What could be wrong or am I missing something

Highlight new text in ckeditor 5

I’m trying to create a plugin that insert text and highlight it. This is my execute command:

execute: (label) => {
  const selection = editor.model.document.selection;
  if (!selection.isCollapsed) {
    return;
  }

  const text = label || "missing placeholder";

  editor.model.change((writer) => {
    const insert = writer.createText(text);
    // insert.setAttribute("highlight", true);
    const range = editor.model.insertContent(insert);
    writer.setAttribute("highlight", true, range);
  });
},

The text is inserted right, but when it comes to hightlight it, browser console print this error:

Uncaught CKEditorError: optionsMap[whichHighlighter] is undefined
Read more: https://ckeditor.com/docs/ckeditor5/latest/support/error-codes.html#error-optionsMap[whichHighlighter] is undefined
    getActiveOption highlightui.ts:263
    _addDropdown highlightui.ts:206
    updateBoundObservableProperty observablemixin.ts:728
    attachBindToListeners observablemixin.ts:763
    attachBindToListeners observablemixin.ts:762
    fire emittermixin.ts:240
    set observablemixin.ts:139
    refresh highlightcommand.ts:42
    Command command.ts:111
    fire emittermixin.ts:240

Actually I have this configuration of CkEditor:

const editorConfig = {
  toolbar: {
    items: [
      ...
      "highlight",
      ...
    ],
    shouldNotGroupWhenFull: true,
  },
  plugins: [
    ...
    Essentials,
    ...
    Highlight,
    ...
  ],
  extraPlugins: [MyPlugin],

I need some other configuration?

How to make vertical scrolling like Instagram Reel or Youtube Shorts

I have implemented a vertical scroll feature on my website using scroll-snap-type. The problem is, when scrolling quickly, DIVs are skipped. Can I prevent this?

It works pretty well with normal scrolling, on smartphones the scroll movement is quicker than on desktops, so its mainly a mobile friendly problem.

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scrolling</title>
  <style>
    html {
      background-color: #f5f5f5;
    }

    /* Der Header bleibt immer oben sichtbar */
    .header {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background: rgba(255, 255, 255, 0.9);
      padding: 15px;
      text-align: center;
      font-size: 1.5rem;
      font-weight: bold;
      z-index: 1000;
    }

    .videos {
      margin-top: 60px; /* Platz für den fixierten Header */
    }

    .video-box {
      display: flex;
      align-items: center;
      scroll-snap-align: start;
    }

    .video-box .inner {
      box-sizing: border-box;
      padding: 8px;
      margin: 0 auto;
      height: 100vh;
      max-width: 100%;
    }
  </style>
</head>

<body>

  <div class="header">Das ist ein Beispiel für den Header</div>

  <section class="videos">
    <div class="video-box">
      <div class="inner">Hallo 1</div>
    </div>
    <div class="video-box">
      <div class="inner">Hallo 2</div>
    </div>
    <div class="video-box">
      <div class="inner">Hallo 3</div>
    </div>
    <div class="video-box">
      <div class="inner">Hallo 4</div>
    </div>
  </section>

  <script>
    document.documentElement.style.scrollSnapType = "y mandatory";
  </script>

</body>

</html>

Why am I getting 403 Forbidden Error in fetching API?

I’m using React and from getting the user’s playlist id from Spotify, I received an error of

  • Failed to load resource: the server responded with a status of 403 ()
  • Error fetching (the Spotify playlist id): 403
  1. The access token is working
  2. The refresh token is working
  3. The stored access and refresh token in local storage is working

My Code:

async function refreshAccessToken(refreshToken) {
  try {
    const response = await fetch("https://accounts.spotify.com/api/token", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: `Basic ${btoa("(client id):(client secret)")}`,
      },
      body: new URLSearchParams({
        grant_type: "refresh_token",
        refresh_token: refreshToken,
      }),
    });

    const data = await response.json();
    console.log("Spotify API Response:", data);

    const accessToken = data.access_token;

    const playlistResponse = await fetch("https://api.spotify.com/v1/me/playlists", {
        method: "GET",
        headers: {
          Authorization: `Bearer ${accessToken}`, 
        },
      });
          const playlists = await playlistResponse.json();
        console.log(playlists)
    if (data.access_token) {
      localStorage.setItem("spotifyAccessToken", data.access_token);
      return data.access_token;
    }
  } catch (error) {
    console.error("Error refreshing token:", error);
  }

}


function Token() { 
  const [accessToken, setAccessToken] = 
useState(localStorage.getItem("spotifyAccessToken") || "");
  const [refreshToken, setRefreshToken] = 
useState(localStorage.getItem("spotifyRefreshToken") || "");

  useEffect(() => {
    console.log("Updated access token:", accessToken);
  }, [accessToken]);

  useEffect(() => {
    const storedAccessToken = localStorage.getItem("spotifyAccessToken");
    const storedRefreshToken = localStorage.getItem("spotifyRefreshToken");
    console.log("Stored Access Token:", localStorage.getItem("spotifyAccessToken"));
    console.log("Stored Refresh Token:", localStorage.getItem("spotifyRefreshToken"));

    if (!storedAccessToken || !storedRefreshToken) {
       const token = "(my access token)";
       const refresh = "(my refresh token)"; 

      localStorage.setItem("spotifyAccessToken", token);
      localStorage.setItem("spotifyRefreshToken", refresh);
      setAccessToken(token);
      setRefreshToken(refresh);
    }

    if (storedRefreshToken) {
      const fetchNewToken = async () => {
        const newToken = await refreshAccessToken(storedRefreshToken);
        if (newToken) {
          setAccessToken(newToken);
          localStorage.setItem("spotifyAccessToken", newToken);
        }
      };
      fetchNewToken();
    }
  }, []);


  useEffect(() => {
    const interval = setInterval(async () => {
      const newToken = await refreshAccessToken(refreshToken);
      if (newToken) setAccessToken(newToken);
    }, 1000 * 60 * 50); 

    return () => clearInterval(interval);
  }, [refreshToken]);

  return null; 
}

export default Token;

My Home Component to access the data:

 const [playlists, setPlaylists] = useState([]);
  const [accessToken, setAccessToken] = 
useState(localStorage.getItem("spotifyAccessToken") || "");
  useEffect(() => {
    const handleStorageChange = () => {
      const newToken = localStorage.getItem("spotifyAccessToken");
      if (newToken) setAccessToken(newToken);
    };

    window.addEventListener("storage", handleStorageChange);
    return () => window.removeEventListener("storage", handleStorageChange);
  }, []);
  console.log("Access Token:", accessToken);


   const playlistIds = useMemo(() => [
   "2TA2qT9p2e91lGZEozyGlI",
   "4Ap2xIU37l1NAShncyota",
   "0Y44bc2Fd2IfbhqSPnNlTC",
   "6jA8JKtuPrsNCTbnvgYkBt",
   "4GX8ccKz938Q2BtF8NMdX2",
   "37i9dQZF1DZ06evO2yXXGB"
  ], []);


  useEffect(() => {
    if (!accessToken) {
      console.warn("No access token available. Cannot fetch playlists.");
      return;
    }

    const fetchPlaylists = async () => {
      try {
        const responses = await Promise.all(
          playlistIds.map(async (id) => {
            const response = await fetch(`https://api.spotify.com/v1/playlists/${id}`, 
{
              headers: { Authorization: `Bearer ${accessToken}` },
            });

            if (!response.ok) {
              console.warn(`Error fetching ${id}: ${response.status} 
${response.statusText}`);
              if (response.status === 403) return { error: "Forbidden: Check your 
Spotify scopes." };
              if (response.status === 401) return { error: "Unauthorized: Your token 
may be expired." };
              if (response.status === 429) return { error: "Rate limit exceeded. Try 
again later." };
              return { error: `HTTP ${response.status}` };
            }

            const contentType = response.headers.get("content-type");
            if (!contentType || !contentType.includes("application/json")) {
              console.error(`Invalid JSON response for ${id}:`, await 
response.text());
              return { error: "Invalid response format (Not JSON)" };
            }

            return await response.json();

          })
        );

        setPlaylists(responses);
      } catch (error) {
        console.error("Error fetching playlists:", error);
      }
    };

    console.log("Playlist IDs:", playlistIds);

    fetchPlaylists();
    setTimeout(() => fetchPlaylists(), 2000);
  }, [accessToken, playlistIds]);

Failed to load resource: the server responded with a status of 403 ()

Error fetching (the Spotify playlist id): 403

How to display Portable Text block content images in SvelteKit

I’m trying to render a blog post from Sanity Studio in my SvelteKit project.

Currently, all of the text etc is being displayed, but images within the block content aren’t. Below is what I have tried so far:

Here is my /blog/[slug]/+page.svelte file currently:

<script lang="ts">
  import { PortableText } from "@portabletext/svelte";
  import BodyImage from "$lib/components/BodyImage.svelte";

  export let data;
  const { post } = data;
</script>

<article>
  <h1>{post.title}</h1>

  <PortableText
    value={ post.body }
    components={{
      image: BodyImage
    }}
  />
</article>

The /blog/[slug]/+page.ts file:

import client from "$lib/sanity/client";

export async function load({ params }) {
  const { slug } = params;
  const post = await client.fetch(
    /* groq */ `
      *[_type == "post" && slug.current == $slug][0]{
        title,
        body[]{
          ...,
          _type == "image" => {
            asset,
            alt
          }
        },
        author,
        publishedAt,
        _updatedAt
      }
    `,
    { slug }
  );
  return { post };
}

The BodyImage.svelte component:

<script lang="ts">
  import client from '$lib/sanity/client';
  import imageUrlBuilder from '@sanity/image-url';
  
  export let value;
  
  const builder = imageUrlBuilder(client);
  const imageUrl = builder.image(value.asset).width(800).url();
</script>

<img src="{imageUrl}" alt="{value.alt}" />

How can I get the images to render? There’s no errors in my console or anything, and the block content object being retrieved in the main +page.svelte file definitely has the images inside as when I console.log(post), I can see images within the portable text object, along with their asset and alt values. I think the issue may be to do with getting those values to BodyImage.svelte? When I update BodyImage.svelte with these console logs:

<script lang="ts">
  import client from '$lib/sanity/client';
  import imageUrlBuilder from '@sanity/image-url';
  
  export let value;
  console.log("Alt: " + value.alt); // Added this
  
  const builder = imageUrlBuilder(client);
  const imageUrl = builder.image(value).width(800).url();
  console.log("Image URL:" + imageUrl); // Added this
</script>

<img src="{imageUrl}" alt="{value.alt}" />

Nothing is logged to the console, but I do get this error message:
Unknown block type "image", specify a component for it in the 'components.types' prop, although I’m not sure what to do next.

Thanks 🙂

How to get React app that works in Sandbox to work on desktop?

I created a React app on Windows 10 localhost but couldn’t get it to work, so created same app on Sandbox and got it to work. Now I want to port that code back to desktop, but still not working.

Here is the Sandbox working app:
https://codesandbox.io/p/sandbox/toolpad-dashboard-d5p6c6

What I was trying to do was to navigate to child pages without them also being in the left navigation bar, but to have the path still show up in the Breadcrumbs. If you append

/about/contact

to the url, you’ll see it successfully does that.

But now how to get it working on desktop localhost? I copy the code over but first problem is something like

A required html file in the public folder is missing

So I add index.html file to public folder which ends in

  <body>
    <div id="root"></div>
    <script type="module" src="/src/index.js"></script>
  </body>

Why is it not needed in Sandbox?

But the next error says

Failed to load module script: Expected a JavaScript module script but
the server responded with a MIME type of “text/html”. Strict MIME type
checking is enforced for module scripts per HTML spec.

So I replace type=”module” with type = “text/html” which gets rid of that error.

Now the next error is:

Uncaught Error: useLocation() may be used only in the context of a
component.

The useLocation hook is used only once in the code, and it is within a Router component. It’s in the BasicBreadcrumbs() function.

If I comment out that code and replace with a hardcoded pathnames array like this:

/*
  const location = useLocation();
  console.log("location=", location);
  const pathnames = location.pathname.split("/").filter((x) => x);
  console.log("pathnames=", pathnames);
*/
  const pathnames = ['about', 'contact'];

which is the same output from the console in the Sandbox, it still produces the same useLocation error.

What am I doing wrong? How do other people get their Sandbox code to work on desktop?

What is the simplest way to make JS generate the same, file-name-friendly datetime format that my C# is generating? [closed]

I currently have C# code that generates a file name containing a datetime pulled from an object property. I am happy with the formatting of this file name.

Elsewhere, I have JavaScript code that needs to find that file on the server, so it needs to be able to generate the same file name string based on the same object property.

I have been mostly successful, but not completely…

I have found that I have to manually add leading zeroes in the JavaScript version. It seems a bit tedious, but if it’s necessary, so be it.

However, I have also found that the JavaScript version is inconsistent: when I debug the code on my computer, it returns the local time, but when I deployed the code and someone else used the feature on a live site, the JavaScript returned the UTC time! How is it even possible for it to be inconsistent in that way?! [Note: Yes, this person is in the same time zone as me.]

Here is my C# code:

fileName += obj.ActualStartTime.Value.DateTime.ToString("yyyyMMdd_HH'h'mm'm'ss's'");

And here is my JS code:

let dto = obj.ActualStartTime;

let monthValue = addLeadingZeroIfNeeded((dto.getMonth() + 1).toString());
let dayValue = addLeadingZeroIfNeeded(dto.getDate().toString());
let hourValue = addLeadingZeroIfNeeded(dto.getHours());
let minValue = addLeadingZeroIfNeeded(dto.getMinutes());
let secValue = addLeadingZeroIfNeeded(dto.getSeconds());

let modifiedDto = dto.getFullYear().toString() + monthValue + dayValue
   + "_" + hourValue + "h" + minValue + "m" + secValue + "s";

fileName += modifiedDto;
function addLeadingZeroIfNeeded(numericString) {
    return ("0" + numericString).slice(-2);
}

Please let me know the simplest way to get the JavaScript code to generate a string that matches the C# string, ensuring the JavaScript always uses local time.

Note: The data comes to JavaScript by way of an ajax call to an API, so the ActualStartTime property of an object is received like this:
"ActualStartTime": "2025-03-20T12:12:07.4854532-04:00"

Wait for a loop to complete before fs.writeFile

I try to write a chapter syntax converter in nodejs (I’m beginner)

How to wait for first bloc to complete (output exist) before execute fs.writeFile.

Because this way, I have an unwanted “undefined” in my output.

"use strict";

const fs = require('fs');

try {
    var data = fs.readFileSync('./chap_source.txt', {encoding: 'utf8'});
    var index, name, chap_int, chap_string, output;
    data = data.trim();
    data = data.split("rn");
    for (let i=0; i<data.length; i++) {
        data[i] = data[i].split(/(?<=^.{8})/);
        index = data[i][0];
        name = data[i][1].slice(1);
        chap_int = i+1;
        chap_string = chap_int.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false });
        output += "CHAPTER" + chap_string + "=" + index + ".000nCHAPTER" + chap_string + "NAME=" + name + "n";
    }
}
catch (err) {
    console.log("Error: ", err.stack);
}

fs.writeFile('./chap_ok.txt', output, err => {
    if (err) { console.error(err); }
    else {  }
});

Can I handle failure when it does not find an element?

Basically I want to check for the existence of an specific element,
If it finds it, do someting, if it doesn’t find do something else.

try {
  cy.get('[role="alert"] span', { timeout: 3000 }).should('not.exist');
  return false;
} catch (error) {
  return true;
}

But it seems Cypress handles errors internally and it does not reach my return statements.
Is there a way that I can do this, and without overriding all error using Cypress.on(“fail”)?

I tried handling in using try/catch, with then, checking the element length..

return cy.get('[role="alert"] span', { timeout: 5000 }).then(($el) => {
  if ($el.length > 0) {
    cy.log('Element found');
    return true;
  } else {
    cy.log('Element not found');
    return false;
  }
});