Next Js – can’t able to upload multiple images in cloudinary in next js

I want to create a uload products page in which I can upload multiple images using cloudinary
in next. Here I created a component for upload image

Image Upload component

"use client";

import { CldUploadWidget } from 'next-cloudinary';
import { useEffect, useState } from 'react';

import { Button } from '@/components/ui/button';
import Image from 'next/image';
import { ImagePlus, Trash } from 'lucide-react';

interface ImageUploadProps {
  disabled?: boolean;
  onChange: (value: string) => void;
  onRemove: (value: string) => void;
  value: string[];
}

const ImageUpload: React.FC<ImageUploadProps> = ({
  disabled,
  onChange,
  onRemove,
  value
}) => {
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  
  const onUpload = (result: any) => {
    onChange(result.info.secure_url);
  };
  

  if (!isMounted) {
    return null;
  }

  return ( 
    <div>
      <div className="mb-4 flex items-center gap-4">
        {value.map((url) => (
          <div key={url} className="relative w-[200px] h-[200px] rounded-md overflow-hidden">
            <div className="z-10 absolute top-2 right-2">
              <Button type="button" onClick={() => onRemove(url)} variant="destructive" size="sm">
                <Trash className="h-4 w-4" />
              </Button>
            </div>
            <Image
              fill
              sizes=''
              className="object-cover"
              alt="Image"
              src={url}
            />
          </div>
          
        ))
        }
      
      </div>
      <CldUploadWidget onSuccess={onUpload} uploadPreset="ox48luzl">
        {({ open }) => {
          const onClick = () => {
            open();
          };

          return (
            <Button 
              type="button" 
              disabled={disabled} 
              variant="secondary" 
              onClick={onClick}
            >
              <ImagePlus className="h-4 w-4 mr-2" />
              Upload an Image
            </Button>
          );
        }}
      </CldUploadWidget>
    </div>
  );
}
 
export default ImageUpload;

and

Product Form page

where I call my image upload

'use client'

import { Button } from "@/components/ui/button"
import { Heading } from "@/components/ui/heading"
import { Product, Image, Category } from "@prisma/client";
import { Trash } from "lucide-react"
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form";
import * as z from "zod"
import { AlertModal } from "@/components/modals/alert-model";
import axios from "axios";
import toast from "react-hot-toast";
import { Separator } from "@/components/ui/separator";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import ImageUpload from "@/components/ui/image-upload";


const formSchema = z.object({
  name: z.string().min(1),
  promocode: z.string().min(2),
  affiliateLink: z.string().min(1),
  description: z.string().min(1),
  images:z.object({url:z.string()}).array(),
  categoryId: z.string().min(1),
  price: z.coerce.number().min(1),
})

type ProductFormValues = z.infer<typeof formSchema>;

interface ProductFormProps {
  initialData: Product & {
    images: Image[]
  } | null;
  categories: Category[]
};
const ProductForm: React.FC<ProductFormProps> = ({
  initialData,
  categories
}) => {

  const params = useParams();
  const router = useRouter();

  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  const title = initialData ? 'Edit Product' : 'Create Product'
  const description = initialData ? 'Edit a Product' : 'Add a new Product';
  const toastMassege = initialData ? 'Product Update' : 'Product Created';
  const action = initialData ? 'Save Changes' : 'Create';

  const defaultValues  = initialData ? {
    ...initialData,
    price: parseFloat(String(initialData?.price)),
    promocode: initialData.promocode || "", 
  } : {
    name: '',
    images:[],
    price:0,
    description: '',
    catogoryId: '',
    promocode: '',
    affiliateLink: '',
  }

  const form = useForm<ProductFormValues>({
    resolver: zodResolver(formSchema),defaultValues
  })

  const onDelete = async () => {
    try {
      setLoading(true)
      await axios.delete(`/api/products/${params.productId}`)
      router.push('/products')
      toast.success('Product Deleted Successfully!')
    } catch (error: any) {
      toast.error('something wen wrong')
    }
    finally {
      setLoading(false)
    }
  }
  return (
    <>
      <AlertModal
        isOpen={open}
        onClose={() => setOpen(true)}
        onConfirm={onDelete}
        loading={loading}
      />
      <div className="flex item-center justify-between">
        <Heading title={title} description={description} />
        {initialData &&(
          <Button
          disabled={loading}
         variant="destructive"
         size="sm"
       >
         <Trash className="h-4 w-4" />
       </Button>
        )}
      </div>
      <Separator/>
      <Form {...form}>
          <form className="space-y-8 w-full">
          <FormField
            control={form.control}
            name="images"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Images</FormLabel>
                <FormControl>
                  <ImageUpload 
                    value={field.value.map((image)=>image.url)} 
                    disabled={loading} 
                    onChange={(url) => field.onChange([...field.value, { url }])}
                    onRemove={(url) => field.onChange([...field.value.filter((current) => current.url !== url)])}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          /> 
            <FormField 
            control={form.control} 
            name="name"
            render={({field})=>(
              <FormItem>
                <FormLabel>Product Name</FormLabel>
                <FormControl>
                  <Input disabled={loading} placeholder="Enter Product Name" {...field}/>
                </FormControl>
              </FormItem>
            )} />
          
          </form>
      </Form>
    </>
  )
}

export default ProductForm

In this code almost everything works fine but when try to upload multiple image in cloudinary widget only first or first uploaded image displays and stored in value

whanted to implement array of image urls uploaded and stored.

uploading files using multipart-from-data with next.js 14

I want to upload multiple images to Supabase and i am getting error with the passed data from client to server, i don’t want to use another extra package such as formidable to manage this.

I am trying to upload a file using react-images-uploading

 const processForm = async (data) => {
    const formData = new FormData();
    // images variable is provided by react-images-uploading which is array of file
    //data_url and the file blob.
    const image_urls = images.map((item) => {
      const fileType = item.data_url.split(";")[0].split("/")[1];
      return {
        data_url: item.data_url,
        filetype: fileType,
      };
    });

    formData.append("imageList", image_urls);
    const response = await axios.post(
      "/dashboard/studio/create/upload",
      formData
    );
    reset();
  };


 <form
          className="mt-12 py-12"
          onSubmit={handleSubmit(processForm)}
          encType="multipart/form-data"
        >

endpoint:

import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";

// I am confused here why imageList is passed as string 

export async function POST(req, res) {
  const response = await req.formData();

  function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(","),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }
  const imageList = response.get("imageList");
Issue is: typeof imageList is string where it should be the javascript Array.

I tried to parse the imageList but din’t work. Please help. thank you

Node.js v16.20.2 crashes beyond 16GB despite specifying –max-old-space-size=16384. Why?

I am in a linux vm were output of free -h is
total used free shared buff/cache available
Mem: 251G 126G 99G 69M 25G 123G
Swap: 111G 10G 101G

This machine is a shared machine, which means multiple user in my organization can access its memory and run its on process.

I am trying to run my application on this machine using node command as
node –max-old-space-size=16384 –expose_gc myapplication.js

Output of my top command at a random instant after starting my application is like this:
`
top – 22:07:27 up 112 days, 11:43, 44 users, load average: 6.06, 6.36, 5.25
Tasks: 906 total, 7 running, 874 sleeping, 18 stopped, 7 zombie
%Cpu(s): 23.2 us, 5.0 sy, 0.0 ni, 71.6 id, 0.0 wa, 0.0 hi, 0.1 si, 0.0 st
KiB Mem : 26329340+total, 893864 free, 25478662+used, 7612924 buff/cache
KiB Swap: 11724390+total, 10161080+free, 15633100 used. 7595188 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
183034 swapnil 20 0 11.3g 16.2g 9364 R 365.1 4.2 59:19.53 node
152575 person2 20 0 32.7g 1880 1140 R 199.3 0.0 42638:03 code
137793 person3 20 0 199.5g 184.4g 1984 R 99.7 73.5 53:09.58 custom_cmd`

Surprisingly, even though i specified –max-old-space-size=16384 (~ 16GB) my node application crashes and shows OOM beyond 16GB like this
<— Last few GCs —>
[3492:0x45d8910] 2304647 ms: Scavenge 16224.8 (16989.1) -> 16222.2 (16994.8) MB, 276.3 / 0.0 ms (average mu = 0.582, current mu = 0.602) task [3492:0x45d8910] 2305511 ms: Scavenge 16229.5 (16995.1) -> 16227.2 (17000.6) MB, 270.5 / 0.0 ms (average mu = 0.582, current mu = 0.602) task [3492:0x45d8910] 2306587 ms: Scavenge 16235.9 (17000.6) -> 16233.7 (17000.8) MB, 354.7 / 0.0 ms (average mu = 0.582, current mu = 0.602) task

From the output of top command you can see my PID swapnil is using only very less % of MEM but still somehow node gives OOM beyond 16gb, I am struggling for 2 weeks but just cannot figure out why is it crashing even after specifying the max-old-space-size=16384?

Is it related to node version (v16.20.2) that I am using where it is expandable only to 16 gb is it something like that?

For the community info I ran a test.js file to check my max heap size limit
temp.js
`const maxHeapSz = require(‘v8’).getHeapStatistics().heap_size_limit;
const maxHeapSz_GB = (maxHeapSz / 1024 ** 3).toFixed(1);

console.log(‘————————–‘);
console.log(${maxHeapSz_GB}GB);`

Command run:
node --max_old_space_size=655360000 src/cmd/temp.js ; node --max-old-space-size=4096 src/cmd/temp.js ; node --max-old-space-size=2048 src/cmd/temp.js ; node --max-old-space-size=1024 src/cmd/temp.js ; node --max-old-space-size=512 src/cmd/temp.js
Here deliberately i set the flag to 655360000 value to see how far heap can expand and result is even more surprising

Output:
Output is

640000.0GB

4.0GB

2.0GB

1.0GB

0.5GB

Please help like why node is crashing beyond 16gb even though system has resources?

I tried setting the max-old-space-size flag to 16384 but still my application crashes and throws OOM beyond 16 gb, please see my top command output as well and my free -h output.

Why isn’t my jQuery connecting and why doesn’t my forms data save to my javascript object?

I am trying to recreate account creation through javascript objects while also starting practice in jQuery. However, I am having a few issues.

First, I can’t seem to get jQuery to connect. I have tried a few of the recommended methods on the website like downloading through terminal using npm and importing it from other sites that host it. But I keep getting this error “account.js:5 Uncaught ReferenceError: $ is not defined”

My second issue is I can’t seem to get my form submission data to run through my formSubmit and accountCreation function. I know it’s not running because none of the values are popping up in the console log when formSubmit runs. I am really confused on where all the values are going.

I understand I haven’t been asking questions right the past few times and they haven’t been well received. I am trying to get it right this time. If I need to adjust my question in anyway please let me know. I also understand I will need a database to actually save data at all times but I am just trying to learn objects and constructors right now and thought this would be a good way to practice it. Any tips help, thank you.

var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);

$(".terms").css("color", "red");

const accountList = [];

function formSubmit(){
    user = document.getElementsByName("user").innerText;
    email = document.getElementsByName("email").innerText;
    pass = document.getElementsByName("pass").innerText;
    conPass = document.getElementsByName("conPass").innerText;
    console.log(user + " " + email + " " + pass + " " + conPass);
    accountList.push(accountCreation(user, email, pass, conPass));
}

function accountCreation(user, email, pass, conPass){
    this.username = user;
    this.email1 = email;
    this.password = pass;
    this.confirmPass = conPass;
    console.log(username + " " + email1 + " " + password + " " + confirmPass);
}
#form {
    background-color: rgb(30, 10, 80, 0.7);
    border-radius: 20px;
    border: 3px solid white;
    margin: 10% auto;
    width: 40vw;
    height: 55vh;
    position: relative;
    z-index: 5;
}

#box {
    font-size: 30px;
    color: white;
    border: none;
}

.signUpTitle {
    padding-top: 30px;
    padding-left: 110px;
    color: white;
    font-size: 40px;
    font-weight: 300;
    margin: auto;
    font-family: monospace;
}

.all {
    padding-top: 25px;
    display: inline-block;
    width: 350px;
    text-align: right;
    vertical-align: 10px;
    font-family: monospace;
}

.textbox {
    width: 210px;
    height: 30px;
    vertical-align: 15px;
    padding-left: 10px;
    font-size: 15px;
    border-radius: 10px;
}

#terms {
    border: none;
    padding-left: 250px;
}

.check:hover {
    cursor: pointer;
}

.terms {
    color: white;
    font-size: 15px;
    font-family: system-ui;
    position: relative;
    top: -1px;
}

#submit {
    border: none;
    padding-top: 5px;
    padding-left: 240px;
}

.submit {
    width: 200px;
    height: 50px;
    font-size: 25px;
    font-family: sans-serif;
    color: white;
    border-radius: 30px;
    background-color: rgb(80, 20, 200);
    border: 1px solid white;
}

.submit:hover {
    background-color: rgb(80, 25, 190);
    cursor: pointer;
}

#signUp {
    padding-top: 10px;
    padding-left: 195px;
    color: white;
    font-family: monospace;
    font-size: 15px;
    border: none;
}

.signUp {
    text-decoration: none;
    color: white;
}
        <main>
            <form id="form">
                <fieldset id="box">
                    <h1 class="signUpTitle">Universal Sign Up</h1>
                    <label for="user" class="user all">Username: </label>
                    <input required type="text" class="userBox textbox" name="user" maxlength="16" minlength="5"></br>
                    <label for="email" class="email all">Email: </label>
                    <input required type="email" class="emailBox textbox" name="email"></br>
                    <label for="pass" class="pass all">Password: </label>
                    <input required type="password" class="passBox textbox" name="pass" maxlength="20" minlength="8"></br>
                    <label for="conPass" class="conPass all" >Confirm password: </label>
                    <input required type="password" class="conPassBox textbox" name="conPass" maxlength="20" minlength="8"></br>
                </fieldset>
                <fieldset id="terms">
                    <input type="checkbox" class="check">
                    <label for="terms" class="terms">Terms and Conditions</label></br>
                </fieldset>
                <fieldset id="submit">
                    <input type="submit" class="submit" onsubmit="formSubmit()">
                </fieldset>
                <fieldset id="signUp">
                    Already have an account? 
                    <a href="login.html" class="signUp">Sign in</a>
                </fieldset>
            </form>
            <script src="../src/account.js"></script>
        </main>

Outlook Add-In – Problem importing/executing function from different module

I am developing an Outlook add-in using JavaScript. I am using the Yeoman generator and have modified the manifest.xml, taskpane.html, taskpane.js, commands.js, and command.html files.

My run function (inside taskpane.js) works correctly from taskpane.html, but if I call it from commands.js it doesn’t work. It gets blocked showing “Quick Copy with headings is working on your request of Perform an action”.

The add-in has a taskpane and a direct command button. The command button executes the action function from the commands.js file. There is probably a small mistake there, but it is my first task in JavaScript and I can’t see it.

In the console, I can see: “empty chain passed to getElementById()”.

Relevant code:

manifest.xml:

<Action xsi:type="ExecuteFunction">
  <FunctionName>action</FunctionName>
</Action>

taskpane.js:

export async function run() {
  // ... (function code)
}

commands.js:

import { run } from "../taskpane/taskpane";

function action(event) {
  // ... (function code)
  run();
}

I have reviewed Microsoft’s documentation on developing Outlook add-ins.
I have searched Stack Overflow and other forums, but I have not found a solution to my specific problem.
I have tried different ways of calling the run function from commands.js, but none have worked.
Question:
What am I doing wrong? How can I make the run function execute correctly when the Outlook add-in button is clicked?.

JavaScript Control reaching unreachable statement

This code makes the text grow and shrink periodically. This works as expected. However, I cannot understand how the control reaches the last statement, since the function has infinite recursion going on.

let body = document.body;
let txt = document.createElement("span");

txt.setAttribute("id", "textgrowing");
txt.textContent = "This is a growing text";

let txt_sz = 10; // Start with a font size of 10px
let growing = true;

function changeTextSize() {
  if (growing) {
    if (txt_sz < 50) {
      txt_sz += 1;
      txt.style.fontSize = txt_sz + "px";
    } else {
      growing = false;
    }
  } else {
    if (txt_sz > 10) {
      txt_sz -= 1;
      txt.style.fontSize = txt_sz + "px";
    } else {
      growing = true;
    }
  }

  setTimeout(changeTextSize, 250); // Call changeTextSize again after 250ms
}

changeTextSize();

body.appendChild(txt);

Array and id interaction [closed]

How to Modify an HTML element with it’s own id and change it to display the elements of an array instead.

Do we need to use any loop?
any hint please?

well, first i tried to use this

document.getElementById(foodElement).innerHTML = {favoriteFoods}

to change the content of the id elements
in this scenario the id is the foodElement

Admin side and user side website pages protection in next js 14

I am using nextjs 14 – and i want to create website like property app where there will be admin dashboard & user side so how can i protect admin side and user side and how will be my folder structure

I know that there we can use middleware but how can i do that i want detail kindly

I tried to have two layout like one for auth , one for dashboard and one for user side now want to that if user is login then he had access to all pages related to user side and when admin is login he has the access to go to all pages of admin dashboard

but if no one is login then cant go to all pages but straightly goes to login page but i am unable to do it

Can not read context value in another component using react hook

AuthContext.js

import React, { createContext, useContext, useState } from "react";

export const AuthContext = createContext();

export const useAuth = () => useContext(AuthContext)

export default function AuthProvider({ children }) {

    const [number, setNumber] = useState(0)
    
    setInterval( () => setNumber(number+1), 10000 )

    const valueToBeShared = {number}


     return (
        <AuthContext.Provider value={ valueToBeShared }>
            {children}

        </AuthContext.Provider>
     );
};

FooterComponent.jsx

import { useContext } from "react";
import { AuthContext } from "./AuthContext";

function FooterComponent() {
     const authContext = useContext(AuthContext)

      console.log(`Footer component - ${authContext.number}`);

      return (
         <div>
           Your Footer
         </div>
     )
   }

   export default FooterComponent

TypeError: Cannot read properties of undefined (reading ‘number’)
at FooterComponent (:64:49)
at renderWithHooks (:12163:28)
at mountIndeterminateComponent (:15575:23)
at beginWork (:16592:24)
at beginWork$1 (:20001:24)
at performUnitOfWork (:19458:22)
at workLoopSync (:19392:15)
at renderRootSync (:19370:17)
at recoverFromConcurrentError (:18968:30)

Unable to read number in FooterComponent

1. Added React.createContext();

2. Checked createContext(number);

Highcharts Linechart drawing lines in wrong order

The project Frontend is in angularjs and we are using the highcharts lib for charts.
I have line charts that stopped working correctly after updating from highcharts 5 to highcharts 7. I don’t think this is a bug in the highcharts lib itself. when i try to reproduce this behaviour in a small example, i can’t. So i assume that some default value or some property changed, that has this side effect.

Point Data:

1. x: 1,  y: 21.5
2. x: 12, y: 21.5
3. x: 12, y: 20
4. x: 24, y: 24

Result:
enter image description here

The points are in this order. points 2 and 3 have the same x value and for some reason that is a problem for highcharts. I know this because i made a dirty fix that checks the point x values and detects a step like this and increases the 2nd x value to 12.000001 for example, which then results on the wanted drawing behaviour.

Point Data:

1. x: 1,         y: 21.5
2. x: 12,        y: 21.5
3. x: 12.000001, y: 20
4. x: 24,        y: 24

Result:
enter image description here

I check the documentation for an option that could fix it, but i couldn’t find anything.
As i don’t wanna keep this dirty fix, i hope someone can help me to resolve this.

AWS cognito sdk, AdminCreateUserCommand takes 1.579s to create the user, someone know how to improve the response time?

This is the code of the function, this is my pre-sign up lambda triggered when someone is sign-in with external provider like google. The big problem it’s understand why cognito needs so much time to create a user!

const cognitoIdentityProviderClient = new CognitoIdentityProviderClient({
  region: process.env.AWS_REGION
});
const createUser = async ({
  userPoolId,
  email,

}) => {
  const adminCreateUserCommand = new AdminCreateUserCommand({
    UserPoolId: userPoolId,
    MessageAction: 'SUPPRESS',
    Username: email,
    UserAttributes: [
      {
        Name: 'email',
        Value: email
      },
      {
        Name: 'email_verified',
        Value: 'TRUE'
      },
    ],
  });

  const { User } = await cognitoIdentityProviderClient.send(adminCreateUserCommand);
  return User;
};

I’m expecting to create a new user in max 500ms.

Chrome extensions: execute script on current tab after receiving response from the api call (manifest v3)

After clicking on a button on a default_popup html file, I want to execute API endpoint and inject (execute) a script with the API response to the current tab.

Executing a script without waiting for API response worked fine:

document.getElementById('myBtn').addEventListener('click', function() {
    
    chrome.tabs.query({ active: true, currentWindow: true}, function(activeTabs) {
        chrome.scripting
            .executeScript({
                target : {tabId : activeTabs[0].id},
                func : foo,
        })
        .then(() => finally());

        
    });
});

But when I want to the the same, just after the api response is fetched:

document.getElementById('myBtn').addEventListener('click', async function() {

    const response = await fetch("http://localhost:8888/get-data");
    const content = await response.json();

    chrome.tabs.query({ active: true, currentWindow: true}, function(activeTabs) {
        chrome.scripting
            .executeScript({
                target : {tabId : activeTabs[0].id},
                func : foo(content),
        })
        .then(() => afterPopulatingForm());

        
    });
});

The script is not executed inside a current tab, but inside the popup itself, so waiting for response somehow messes up the chrome’s injecting logic. What am I doing wrong?

How can I properly implement code splitting with SSR on Vite

I am trying to implement support for SSR in my framework and want to switch the documentation to SSR.

It’s running on Vercel with Vite as bundler.

I’m using code splitting features of Vite by lazy loading my routes in order to create seperate chunks for each page.

This is working fine for a CSR build where you would expect loading indicators as the client fetches data.

If you directly navigate to a lazily loaded route and serverside rendering already serves the prerendered page then lazy loaded components will suspend during hydration..

That’s because the component react-router renders suspends while it’s fetching the import.

That’s ok, however I don’t want the page to suspend because that’s causing layout shifts and flickering.

I think I have a few approaches:

  1. Somehow don’t use React.lazy for this route if it’s SSR.
  2. Somehow inline the code needed for that route if it’s server rendered
  3. Use startTransition to keep the server rendered HTML until the client side component has been loaded and hydrated.

I’m not sure what’s the best approach. I hoped the future flag for react-router to use transitions would solve this but somehow it didn’t

I’m wondering how to properly implement code splitting when doing SSR and partial hydration?

I also documented my findings here, in case someone is trying to do the same.