JS / HTML – Creating new to hold twitch embed and assign twitch embed into it

Quick say, I am very very new to HTML and JS, I’m assuming there is a very simple solution that I am overlooking or misunderstanding.

I am trying to create a main container that will hold all my sub containers that will have the twitch embeds and a button alongside them.

The problem I am encountering is that it looks like there is only one container that the twitch embedded code looks for, which is “twitch-embed” and it seems that it must exist in the HTML before the HTML is loaded, otherwise the stream never loads and the rest of my code doesn’t load.

Is there a way to load the first while in the section of my code? Or am I misunderstanding something from the twitch API and/or how JS HTML works?

<body style="background-color:#271e27">

<input style="background-color:#362e37", "color:#000000" type="search" id="twitchName" placeholder="Enter twitch name">
<button type="button" onclick="addEmbed(document.getElementById('twitchName').value)">watch</button>
<p id="test_input"></p>

<!-- Add a placeholder for the Twitch embed -->
<div id="twitch-embed"></div>
<!-- Intended container to hold the multiple streams -->
<!-- <div id="twitch-container"></div> -->

<!-- Load the Twitch embed script -->
<script src="https://embed.twitch.tv/embed/v1.js"></script>

<script type="text/javascript">
  console.log("script initi");

  function addEmbed(channelName){
    console.log("starting function for " + channelName);
    var channelnameButtonID = channelName + "button"
    var channelnameStreamDivID = channelName + 'ID'

    console.log("creating button");
    var butt = document.createElement('BUTTON');
    butt.id=channelnameButtonID;

    console.log("creating div");
    var newTwitchEmbed = document.createElement('div');
    newTwitchEmbed.id = "twitch-embed";

    console.log("creating embed");
    var embed = new Twitch.Embed("twitch-embed", {
      width: 284,
      height: 160,
      channel: channelName,
      layout: "video",
      parent: ["embed.example.com", "othersite.example.com"]
    });

    console.log('testing channel name button id')
    console.log(channelnameButtonID);

    console.log("creating button listener");
    butt.addEventListener('click',() => {
      console.log('click');
      // embed.remove();
      document.getElementById(channelnameButtonID).remove();
    })
    // document.getElementById("channelnameStreamDivID").appendChild();
    // action already performed via new twitch embed?
    console.log("appending button");
    document.getElementById("twitch-container").appendChild(butt);
    console.log("button appended");

    console.log("creating embed listener");
    embed.addEventListener(Twitch.Embed.VIDEO_READY, () => {
      var player = embed.getPlayer();
      player.setQuality("160p");
      player.setVolume("0.01");
      player.play();
    });
  }
</script>

problem with the url on the server with js A+

Creating my web application, on behalf of the server, it tells me that there is an error on the part of mongoose, line 20 A+ /Being able to have a route with which the environment is compatible and that the route is free when class changes Take into account corrections and routes within class calls. . Has anyone had a problem with the routes to create the environment in Express?. I hope to solve the problem in order to make the url work in my project for my Harvard University, I would appreciate your help

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const path = require('path');
const TasasDeCambio = require('./server/models/TasasDeCambio');


const app = express();

app.use(bodyParser.urlencoded({ extended: true }))

app.use(bodyParser.json())

app.use(express.static(path.join(__dirname, 'public')));

mongoose.connect('mongodb://localhost:27017/tasasDeCambio', {
    useNewUrlParser: true
}).then(() => {
    console.log("Conexión exitosa a la base de datos");    
}).catch(err => {
    console.log('No se pudo conectar a la base de datos. Saliendo...', err);
    process.exit();
});

app.post('/tasasDeCambio', (req, res) => {

    const tasaDeCambio = new TasasDeCambio({
        moneda: req.body.moneda,
        tasa: req.body.tasa
    });

    tasaDeCambio.save()
    .then(data => {
        res.send(data);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Ocurrió un error al crear la tasa de cambio."
        });
    });
});

app.get('/tasasDeCambio', (req, res) => {
    TasasDeCambio.find()
    .then(tasasDeCambio => {
        res.send(tasasDeCambio);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Ocurrió un error al obtener las tasas de cambio."
        });
    });
});

app.put('/tasasDeCambio/:tasaId', (req, res) => {

    TasasDeCambio.findByIdAndUpdate(req.params.tasaId, {
        moneda: req.body.moneda,
        tasa: req.body.tasa
    }, {new: true})
    .then(tasaDeCambio => {
        if(!tasaDeCambio) {
            return res.status(404).send({
                message: "No se encontró una tasa de cambio con el id " + req.params.tasaId
            });
        }
        res.send(tasaDeCambio);
    }).catch(err => {
        if(err.kind === 'ObjectId') {
            return res.status(404).send({
                message: "No se encontró una tasa de cambio con el id " + req.params.tasaId
            });                
        }
        return res.status(500).send({
            message: "Ocurrió un error al actualizar la tasa de cambio con el id " + req.params.tasaId
        });
    });
});```

UserID: undefined while using Reddit Auth

I am creating a secret santa app for our reddit sub. However, I am getting an “UserID: undefined” error whenever I am clicking on the Authorize with Reddit button on my app.

Here’s the code for App.jsx:

import { useState, useEffect } from 'react';
import axios from 'axios';
import logo from './assets/santa.svg';

function App() {
  const [isRedditAuthorized, setRedditAuthorized] = useState(false);
  const [redditUsername, setRedditUsername] = useState('');

  const gradientTextStyle =
    'text-transparent bg-clip-text bg-gradient-to-r from-red-600 to-red-700 w-fit mx-auto';

  useEffect(() => {
    // Check if the user is already authorized (e.g., with a stored token)
    // If yes, update the state accordingly
    const accessToken = localStorage.getItem('redditAccessToken');
    if (accessToken) {
      setRedditAuthorized(true);
      // Fetch user info or do other necessary tasks with the token
      // ...
      // For now, set a dummy username
      setRedditUsername('exampleRedditUser');
    }
  }, []);

  const handleAuthorizeReddit = async () => {
    try {
      // Redirect to Reddit for authorization
      window.location.href = 'http://localhost:3001/auth/reddit';
    } catch (error) {
      console.error('Error during Reddit authorization:', error.message);
    }
  };

  const handleRedditUsernameChange = (e) => {
    setRedditUsername(e.target.value);
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-r from-green-900 via-green-700 to-green-900">
      <img
        src={logo}
        alt="Logo"
        className="absolute top-0 center-0 mt-4 ml-4"
        style={{ width: '150px', height: 'auto' }}
      />
      <div className="bg-white p-8 rounded-lg shadow-md max-w-md w-full text-center items-center outline outline-4 outline-offset-2 outline-red-800">
        <h1 className={gradientTextStyle + ' text-6xl font-bold mb-2 mt-8'}>Secret Santa</h1>
        <h2 className="text-2xl font-bold text-gray-600 mb-4">r/IndiaSocial</h2>

        <button
          onClick={handleAuthorizeReddit}
          className={`bg-red-700 text-white font-bold py-2 px-4 rounded mb-4 ${
            isRedditAuthorized && 'opacity-50 cursor-not-allowed'
          }`}
          disabled={isRedditAuthorized}
        >
          {isRedditAuthorized ? 'Reddit Authorized' : 'Authorize Reddit'}
        </button>

        <input
          type="text"
          placeholder="Reddit Username"
          className="border rounded w-full p-2 mb-4 mt-2"
          value={isRedditAuthorized ? redditUsername : ''}
          onChange={handleRedditUsernameChange}
          readOnly={isRedditAuthorized}
        />

        <textarea placeholder="About Yourself" className="border rounded w-full p-2 mb-4"></textarea>

        <button className="bg-green-500 text-white font-bold py-2 px-4 rounded">Submit!</button>
      </div>
    </div>
  );
}

export default App;

Here’s the code for server.cjs:

const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3001;
const REDDIT_CLIENT_ID = process.env.REDDIT_CLIENT_ID;
const REDDIT_CLIENT_SECRET = process.env.REDDIT_CLIENT_SECRET;
const REDDIT_REDIRECT_URI = process.env.REDDIT_REDIRECT_URI;

app.use(bodyParser.json());

// An object to store access tokens (replace this with a database in production)
const redditAccessTokens = {};

// Redirect to Reddit for authorization
app.get('/auth/reddit', (req, res) => {
  const redditAuthUrl = `https://www.reddit.com/api/v1/authorize?client_id=${REDDIT_CLIENT_ID}&response_type=code&state=random_state&redirect_uri=${REDDIT_REDIRECT_URI}&duration=permanent&scope=read`;
  res.redirect(redditAuthUrl);
});

// Callback route to handle Reddit's redirect
app.get('/auth/callback', async (req, res) => {
  const { code, state } = req.query;

  // Make a request to exchange the code for an access token
  const redditAccessTokenUrl = 'https://www.reddit.com/api/v1/access_token';
  const data = {
    grant_type: 'authorization_code', // Make sure this is set to 'authorization_code'
    code,
    redirect_uri: REDDIT_REDIRECT_URI,
  };

  try {
    const response = await axios.post(redditAccessTokenUrl, data, {
      auth: {
        username: REDDIT_CLIENT_ID,
        password: REDDIT_CLIENT_SECRET,
      },
    });
  
    // Log the entire response object to inspect its structure
    console.log('Reddit API Response:', response.data);
  
    // Extract user ID from the response (modify this based on the actual structure of the response)
    const userId = response.data.user_id;
  
    // Print userId to the console
    console.log('UserID:', userId);
  
    // Store the token in memory (replace this with a database in production)
    redditAccessTokens[userId] = response.data.access_token;
  
    // Send a script to close the popup and reload the original page
    res.send('<script>window.opener.location.reload(); window.close();</script>');
  
  } catch (error) {
    console.error('Error exchanging code for access token:', error.message);
    res.status(500).send('Error during authorization process');
  }
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

I am not sure what I am doing wrong since this is the first time I am working on React/Vite/TailwindCSS and Reddit Auth. Also, the app does go for Authorization, it takes the user to the page which asks them to Allow or Decline. However, on clicking on the Allow button it goes to a blank page and get stuck there. All I want is for Reddit Auth to work so that we can get the end-user’s username and account age.

Amazon S3 UNSIGNED-PAYLOAD for X-Amz-Content-Sha256 Error

I am using TypeScript and Next.js 14 and my s3 bucket is working perfectly in localhost but not in production. I did create a separate bucket with policy and IAM user for production as well. All the keys match up, but I am receiving an error of CORS and a 403 forbidden error as well in production.

Inside the payload for the errors I am receiving an UNSIGNED-PAYLOAD for the X-Amz-Content-Sha256.

The error is happening on the handleAudioUploadtoS3 function
Here is my client side code:


import Image from "next/image";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Montserrat } from "next/font/google";
import { cn } from "@/lib/utils";
import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { useProModal } from "@/hooks/use-pro-modal";
import { Download } from "lucide-react";
import { ImSpinner3 } from "react-icons/im";
import { getSignedURL } from "@/app/_actions/actions";
import { MAX_CHARACTERS } from "@/constants";
import { toast } from "react-hot-toast";

const montserrat = Montserrat({
  weight: "600",
  subsets: ["latin"],
});

export default function YourVoicesPage({
  params,
}: {
  params: { id: string; image: string; name: string; flag: string };
}) {
  const sourceElem = useRef(null);
  const router = useRouter();
  const proModal = useProModal();
  const [voice, setVoice] = useState("");
  const [response, setResponse] = useState<Blob | "">("");
  const [converting, setConverting] = useState(false);
  const [characterCount, setCharacterCount] = useState(0);

  // console.log("params", params);
  // using the params to get the correct name, image and flag
  const nameString = params.id[1].split("%26")[1];
  const name = nameString.split("%3D")[1];
  const imageString = params.id[1].split("%26")[0];
  const correctImagePath = imageString.startsWith("/")
    ? imageString
    : `/${imageString}`;
  console.log("image", correctImagePath);
  const flagString = params.id[2];
  const correctFlagPath = flagString.startsWith("/")
    ? flagString
    : `/${flagString}`;

  console.log("flag", correctFlagPath);

  // using the params to get the correct voiceID
  const voiceIDString = params.id[0];
  const voiceID = voiceIDString.replace("%26image%3D", "");

  const handleTextChange = (e: any) => {
    const newText = e.target.value;
    setCharacterCount(newText.length);
    setVoice(newText); // Update the state with the new text
  };

  const isGenerateDisabled = characterCount > MAX_CHARACTERS;

  // Upload and save Audio to S3 bucket & database
  const handleAudioUploadtoS3 = async (audioBlob: Blob) => {
    console.log("audioBlob", audioBlob);

    const signedURLResult = await getSignedURL({ name, correctImagePath, text:voice });
    console.log("signedURL", signedURLResult);
    if (!signedURLResult.success) {
      console.log("error", signedURLResult.error);
      return;
    }
    const url = signedURLResult.success.url;
    console.log("url", url);

    const response = await fetch(url, {
      method: "PUT",
      body: audioBlob,
      headers: {
        "Content-Type": "audio/mpeg",
      },
    });

    if(!response.ok) {
      console.log("error", response);
      return;
    }
    
    if(response.ok) {
       toast.success("Audio file saved to your dashboard");
    }

    console.log("response", response);

  };

  // Create the audio from the user's input text
  const handleVoiceInput = async () => {
    try {
      setConverting(true);
      const response = await fetch("/api/voice-creation", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          voiceID: voiceID,
          text: voice,
          characterCount: characterCount,
        }),
      });

      if (!response.ok) {
        if (response.status === 403) {
          setConverting(false);
          proModal.onOpen();
        } else {
          console.log("Unexpected response status:", response.status);
        }
        return; // Stop further processing
      }

      const blobResponse = await response.blob();
      setResponse(blobResponse);
    } catch (error: any) {
      console.log("error", error);
      if (error?.response?.status === 403) {
        proModal.onOpen();
      }
    } finally {
      setConverting(false);
      router.refresh();
    }
  };

  // console.log("voiceID", voiceID);
  return (
    <div className="flex w-full h-screen bg-slate-100">
      <div className="max-w-7xl mx-auto flex flex-col">
        <h1
          className={cn(
            "mt-10 font-bold text-center text-4xl mb-10",
            montserrat.className
          )}
        >
          Your Voices
        </h1>
        <div className="flex flex-col mb-8">
          <Image src={correctImagePath} alt="name" width={250} height={250} />
          <div className="flex flex-row gap-2 mx-auto mb-6 items-center">
            <h3 className="font-semibold text-2xl">{name}</h3>
            <Image src={correctFlagPath} alt="flag" width={50} height={50} />
          </div>
          <div className="flex flex-col gap-4">
            <Textarea
              className=""
              value={voice}
              onChange={handleTextChange}
              placeholder="Type your text here..."
            />
            <p className={voice.length > 200 ? "text-red-500" : ""}>
              {/* Character Count: {voice.length}/200 */}
              Character Count: {characterCount}
            </p>
            <Button disabled={isGenerateDisabled} onClick={handleVoiceInput}>
              Generate
              {converting && (
                <span className="animate-spin text-lg ml-3">
                  <ImSpinner3 />
                </span>
              )}
            </Button>
          </div>
        </div>
        {response && (
          <>
            <audio
              src={response ? URL.createObjectURL(response) : ""}
              controls
            />
            {/* <source ref={sourceElem} src={response} type="audio/mpeg" /> */}
            <div className="flex flex-row gap-6 items-center mt-10">
                 <a
              className="flex items-center gap-4"
              href={response ? URL.createObjectURL(response) : ""}
              download
            >
              {response ? (
                <div className="flex gap-6 items-center">
                  <Button className="flex gap-5">
                    <Download size={16} className="text-white" />{" "}
                    <p className="text-white">Download Audio File</p>
                  </Button>
                </div>
              ) : (
                ""
              )}
            </a> 
            <Button variant={'outline'}
              onClick={() => handleAudioUploadtoS3(response)}
            >
              Save to Your Dashboard
            </Button>
            </div>
         
           
          </>
        )}
      </div>
    </div>
  );
}

Here is my server code:

"use server";

import { getServerSession } from "next-auth";
import { authOptions } from "@/utils/authOptions";
import {
  S3Client,
  PutObjectCommand,
  DeleteObjectCommand,
} from "@aws-sdk/client-s3";

import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import prismadb from "@/lib/prismadb";

const s3 = new S3Client({
  region: process.env.AWS_BUCKET_REGION!,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
});

export async function getSignedURL({
  name,
  correctImagePath,
  text
}: {
  name: string;
  correctImagePath: string;
  text: string
}) {
  // Get the user's session
  const session = await getServerSession(authOptions);
  if (!session) return { error: "Not authenticated" };
  console.log("testing out", name, correctImagePath);

  const timestamp = new Date().toISOString();
  const key = `users/${session.user.id}/audio/${timestamp}_audioFile.mp3`;

  const putObjctCommand = new PutObjectCommand({
    Bucket: process.env.AWS_BUCKET_NAME!,
    Key: key,
    Metadata: {
      userId: session.user.id,
      name: name,
      image: correctImagePath,
    },
  });

  const signedURL = await getSignedUrl(s3, putObjctCommand, {
    expiresIn: 60,
  });

  const newAudio = await prismadb.audioFile.create({
    data: {
      userId: session.user.id,
      url: signedURL.split("?")[0],
      fileName: `${timestamp}_audioFile.mp3`,
      image: correctImagePath,
      aiName: name,
      text: text
    },
  });

  console.log("newAudio", newAudio)

  return { success: { url: signedURL, audio: newAudio } };
}

export async function deleteAudio({ audioId }: { audioId: string }) {
  // Get the user's session
  console.log("testing out", audioId);
  const session = await getServerSession(authOptions);
  if (!session) return { error: "Not authenticated" };

  const audio = await prismadb.audioFile.findUnique({
    where: { id: audioId },
  });

  console.log("audio", audio);

  if (!audio) return { error: "Audio file not found" };

  if (audio.userId !== session.user.id) {
    return { error: "You do not have permission to delete this audio file" };
  }

  // delete from s3
  const deleteObjctCommand = new DeleteObjectCommand({
    Bucket: process.env.AWS_BUCKET_NAME!,
    Key: `users/${session.user.id}/audio/${audio.fileName}`,
  });

  await s3.send(deleteObjctCommand);

  await prismadb.audioFile.delete({
    where: { id: audioId },
  });

  return { success: "Audio file deleted" };
}

If you think you need more information to help me solve this that would be appreciated.

Is there any method to animate an image flipping in css when clicked on it?

i am making an interactive website related to grid style in html and css and i am unsure as to how to make an image animate.
like when the user clicks on the displayed image it should zoom in and then do a flipping animation and redirects to another page opening the full image

i tried using CSS but its not working correctly and i need it for a project I am working on. so I will be needing some assistance

First Javascript for display of div after click, and hiding of div on second click works, but identical script for a different div does not [closed]

I’ve been trying to make a div hidden until a “link” is clicked, then hidden again when the link is clicked another time. This works for the first div in my document, but not the second. My Javascript abilities are weak, and I can’t really tell what’s wrong… Is this just not possible? Any help is appreciated!

This is my main css

<h2 style="margin-bottom: -2px;">Rules of Exponents</h2>
<img id="o" src="d.png" width="300px" height="8px" style="margin-top: 10px;">
<br><br>
 <a id="b" href="#">Definition of Base</a>
 <div id="mainFrameTwo" style="text-align: center; display:none;"><p style="position: absolute;     top: 76px; left: 450px;">▼</p><p>The base of an exponent is a number which is raised to a certain power, The base represents the number or variable that is multiplied by itself,</p>  <h3>An example: </h3><p>3<sup>8</sup></p></div>
<div id="mainFrameOne" style="margin: 0px;">
<br><br>
<a id="c" href="#">Definition of Exponent</a>
<div id="mainFrameFour" style="text-align: center; display: none;"><p style="position:    absolute; top: 76px; left: 450px;">▼</p><p>huehuiehueh</p></div>
<div id="mainFrameThree">
<br><br>
<a href="#">Power of Zero</a>
<br><br>
<a href="#">Negative Exponents</a>
<br><br>
<a href="#">Multiplying Powers</a>
<br><br>
<a href="#pow">Power to a Power</a> 
<br><br>
<a href="#">Power of a Product</a>
<br><br>
<a href="#">Diving Powers</a>
<br><br>
<a href="#">Power of a quotient</a>
</div>
</div>

This is my Javascript

<script>
const element = document.getElementById("b");

let isDivOnLeft = true;
element.addEventListener('click', function (event) { 
 isDivOnLeft = !isDivOnLeft
 if (isDivOnLeft) {
 myFunctionb()
 } else {
 myFunction()
 }
 });


 function myFunction() { 
document.getElementById("mainFrameOne").style.display="none"; 
document.getElementById("mainFrameTwo").style.display="block";
}

function myFunctionb() { 
document.getElementById("mainFrameOne").style.display="block"; 
document.getElementById("mainFrameTwo").style.display="none";
}
</script>
<script>
const element = document.getElementById("c");

let isDivReal = true;
element.addEventListener('click', function (event) { 
isDivReal = !isDivReal 
if (isDivReal) {
myFunctiond()
} else {
myFunctionc()
}
});


function myFunctionc() { 
document.getElementById("mainFrameThree").style.display="none"; 
document.getElementById("mainFrameFour").style.display="block";
}

function myFunctiond() { 
document.getElementById("mainFrameThree").style.display="block"; 
document.getElementById("mainFrameFour").style.display="none";
}
</script>

Cannot make two objects in same time in Javascript. One object hides another one

I want to create a symbol using javascript. It needs to create circle and rectangle. I created circle and rectangle. But when rectangle make under the circle, then circle not display. How fix this issue?

var circle = document.getElementById('canvas1');
var ctx = circle.getContext('2d');
ctx.beginPath();
ctx.arc(300, 300, 50, 0, 2 * Math.PI);
ctx.stroke();

//create gradient
var grd = ctx.createRadialGradient(300, 300, 50, 300, 300, 5);

var fillColor = 'black';
ctx.fillStyle = fillColor;
ctx.fill();

var rect = document.getElementById('canvas2');
var ctx2 = rect.getContext('2d');
ctx2.beginPath();
ctx2.rect(200, 10, 200, 40);
ctx2.stroke();

var grd2 = ctx2.createLinearGradient(0, 0, 100, 100);
grd2.addColorStop(0, "black");
grd2.addColorStop(1, "white");

ctx2.fillStyle = grd2;
ctx2.fill();
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="canvas1" width="800" height="250"></canvas>
  <canvas id="canvas2" width="800" height="300"></canvas>

  <script src="index.js"></script>
</body>

</html>

How to call display image from local JSON using React

I created a React demo project for learning purposes. But I am stuck.
I have added the image in the JSON file and I have called the image in the blog page but there is a problem with the image path. please check the below screenshot and please review my code to placode page URL please review. https://playcode.io/dhavalpatel

Blog page : https://prnt.sc/WwIxG6cntBeF

Blog page Code blog.js

{data.map((user) => {
    return(
        <div className="artical--wrap" key={user.id}>
            <div className="blog-content">
                <img src={user.imgpath} />
                <h2>{user.title}</h2>
            </div>
       </div>
   )
})}

Json file code screenshort
https://prnt.sc/K27wu7y_fINV

Unable to bind object as a value for Select component (Ant Design) in react js

I have an issue while selecting the object as value for Select component (Ant Design).

This is what I’m trying to do

import React, { useEffect, useState } from "react";
//Other imports

export const NewInvoice = () => {
    const [selectedCustomer, setSelectedCustomer] = useState(null);
    const [customers, setCustomers] = useState([]);
    
    // other fields


    useEffect(() => {
        if (checkAuthentication(getToken())) {
            fetchCustomers().then((data) => {
                setCustomers(data);
            });
        }
        //eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const customerNameHelper = (customer) => {
        return `${customer?.customerNumber ?? ""} - ${customer?.name ?? "Unkown"}, ${customer?.addressDto?.city ?? "Unknown"}`;
    };

    const getCustomerAsOptions = (customers) => {
        return customers.map((item) => ({
            label: customerNameHelper(item),
            value: item, // item = {id, name, customerNumber, ...}
        }));
    };
    
    return (
        // other components
        {customers.length > 0 && (
            <Select
                style={{
                    width: 380,
                }}
                className="customerSelectionDropdown"
                value={customerNameHelper(selectedCustomer)}
                onChange={(value) => {
                    setSelectedCustomer(value);
                }}
                placeholder="Select Customer"
                options={getCustomerAsOptions(customers)}
                dropdownStyle={dropDownStyles}
                showSearch
                allowClear
            />
        )}
    );
};

Whenever I try to select the option it is saying Objects are not valid as a React child (found: object with keys {id, name, customerNumber, email, phone, pendingAmount, createdDate, addressDto, totalPurchaseAmount}). If you meant to render a collection of children, use an array instead.

Is there any solution to address this issue? Thank you in advance for your assistance.

Stl-Format File Search Engine Not Preforming Searches Correctly

New to programming, with the help of chat gpt created a html, css, and js search engine that uses Thingiverse API to search for STL-Format files based on characters.

Problem is that at least from what I can see, it’s pulling a ceartian number of random files off of thingiverse and then filtering those files based on the characters someone searched. From what I can see, the ammount of files is based on const maxResultsPerPage = 100;. 90% of the time this leads to searches with no results (very bad)

I can change that number so it searches more files yet then it becomes very, very slow. There are millions of files on Thingiverse so I need to find a way for it to preform searches effectively so it can find related files better.

Here’s my code:



<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>STL Search</title>
</head>
<body>

  <h1>STL Search</h1>

  <div id="searchContainer">
    <label for="searchInput">Enter characters:</label>
    <input type="text" id="searchInput" oninput="handleSearchInput()">
    <button onclick="performSearch()">Search</button>
  </div>

  <div id="searchResults"></div>

  <script>
    let debounceTimer;
    const cache = {};

    function debounce(func, delay) {
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => {
        func();
      }, delay);
    }

    function handleSearchInput() {
      debounce(performSearch, 300); // Adjust the delay as needed (e.g., 300ms)
    }

    async function performSearch() {
      const characters = document.getElementById('searchInput').value;
      const searchResultsContainer = document.getElementById('searchResults');

      if (cache[characters]) {
        displaySearchResults(cache[characters]);
        return;
      }

      try {
        searchResultsContainer.innerHTML = '<p>Loading...</p>'; 
        const apiKey = 'API key goes here'; 
        const maxResultsPerPage = 100;
        const apiUrl = `https://api.thingiverse.com/search?q=${characters}&type=things&access_token=${apiKey}&per_page=${maxResultsPerPage}`;
        const response = await fetch(apiUrl);
        const data = await response.json();

        const filteredResults = data.hits.filter(result => result.name.toLowerCase().indexOf(characters.toLowerCase()) !== -1);

        searchResultsContainer.innerHTML = '';
        cache[characters] = filteredResults; 
        displaySearchResults(filteredResults);
      } catch (error) {
        console.error('Error fetching data:', error);
        searchResultsContainer.innerHTML = '<p>Error fetching data</p>'; 
      }
    }

    function displaySearchResults(results) {
      const resultsContainer = document.getElementById('searchResults');
      resultsContainer.innerHTML = '';

      if (results.length === 0) {
        resultsContainer.innerHTML = '<p>No results found</p>';
      } else {
        results.forEach(result => {
          const resultElement = document.createElement('div');
          resultElement.classList.add('result');
          resultElement.innerHTML = `
            <a href="${result.public_url}" target="_blank">
              <img src="${result.thumbnail}" alt="${result.name}">
              <p>${result.name}</p>
            </a>
          `;
          resultsContainer.appendChild(resultElement);
        });
      }
    }
  </script>

</body>
</html>


Pagnation and getting help from Chat GPT

ExtJS grid rowexpander content cannot be selected and copied

I am using ExtJS 6.2.0, I implemented a panel which uses Ext.grid.Panel populated with some data, actually some logging messages. And when double click each row of the grid, the grid rowexpander will display more info of this logging message.

The code is like:

grid = new Ext.grid.Panel({
    ...
    plugins: [{
       ptype: 'rowexpander',
       rowBodyTpl: new Ext.XTemplate(
           '<div class="allow-text-selection" style="background-color:#ffffff;">',
           '<font color="gray">',
           '<pre>{[this.formatMessage(values.log_extra)]}</pre>',
           '</font>',
           '</div>',
           {
               formatMessage: function (message) {
               let decodedMessage = JSON.parse(message);
               return JSON.stringify(decodedMessage, null, 4);
           }
        }
     )
   }],
   ...
});

But when I try to select the data in this rowexpander content (rendered in the form of rowBodyTpl), it just cannot be selected.

ps: And, the grid cell cannot be selected by default, but after I added following config, it works.

viewConfig: {
    enableTextSelection: true,
    getRowClass: function () {
         return this.enableTextSelection ? 'x-selectable' : '';
    }
},

I also add a CSS class “allow-text-selection” to the template, but it still not works.

.allow-text-selection {
    -webkit-user-select: text !important;
    -moz-user-select: text !important;
    -ms-user-select: text !important;
    user-select: text !important;
}

So, my question is how to work around to make the rowexpander content seletable so that I can let users select and copy conveniently.

Thanks for your help.

toString and valueOf Execution order make me confused

the object f string conversion, but not call the prototype chain toString method

function fn(){}

fn.prototype.toString = function(){
    console.log("toString call");
    return {};
}
fn.prototype.valueOf = function(){
    console.log("valueOf call");
    return 100;
}

let f = new fn();
console.log("before "+f+" after"); 

// I hope:toString call --> valueOf call --> 'before 100 after'
// Result: valueOf call --> 'before 100 after'

Uncaught (in promise) RangeError: Maximum call stack size exceeded webpack riquire consumes error with React

I’m currently having this issue with my React app where when you get to the first page it appears blank. The problem started when I made some changes related to apollo client, since I’m using to fetch some data used in the app, the thing is that the changes that I made are not even giving a clue about why the stack would exceed its limit, and even more weird is that when you refresh several times the error disappears. Any clue about how to solve this?
[First time you open the app] (https://i.stack.imgur.com/Bv2gc.png)
[After several times the error disappears] (https://i.stack.imgur.com/er1xw.png)

I’ve been reading about some errors related to the webpack but none of them are similar to this one. Help please.