Property ‘id’ does not exist on type ‘BlogDetailProps’

I’m trying to create a blog. Here i need to create a page from the database. But it tells me that the Id property does not exist, although it is detected.

Here’s the error with the ID

where: {
      id: params.id,
    }

Here is the whole file

import prisma from '@/lib/db';
import { FC } from 'react'

interface BlogDetailProps {
  params: {
    id: string,
  }
}

const BlogDetail: FC<BlogDetailProps> = async( params ) => {

  const post = await prisma.post.findFirst({
    where: {
      id: params.id,
    },
    include: {
      author: true,
    },
  });

  return (
    <div className='max-w-4xl mx-auto py-8'>
        <img src={post?.image} alt={post?.title} />
        <h2>{post?.title}</h2>
        <p>Written by: {post?.author?.name}</p>
        <div className='mt-4'>{post?.content}</div>
    </div>
  )
}

export default BlogDetail```

React useState for Updating Array of Component

I am currently facing difficulties in updating my Component Array. My current code is as following:

import React from 'react';
import ReactDOM from 'react-dom';

const Item = ({ value }) => {
  return (
        <div className="col">
            <div className="card" style={{width: "30rem"}}>
              <img src="https://cdn.shopify.com/s/files/1/0617/1623/4396/files/Untitled_design_1.png?v=1707233721"
                  className="card-img-top" alt="..."/>
              <div className="card-body">
                <h5 class="card-title">{value.title}</h5>
                <p className="card-text">{value.description}</p>
                <a href="#" class="btn btn-primary">Redeem Voucher</a>
              </div>
            </div>
        </div>
    )
}

function RewardContent(props){
    const reward_content = [{"id":"STORE25K","title":"25K OFF","image":"#","description":"Redeem this discount voucher to get 25.000 off.", "eligibility":"Newcomers","point_deduction":25000},
{"id":"STORE50K","title":"50K OFF","image":"#","description":"Redeem this discount voucher to get 50.000 off.", "eligibility":"Newcomers", "point_deduction":45000},
{"id":"STORE100K","title":"100K OFF","image":"#","description":"Redeem this discount voucher to get 100.000 off.", "eligibility":"Newcomers","point_deduction":90000},
{"id":"STORE150K","title":"150K OFF","image":"#","description":"Redeem this discount voucher to get 150.000 off.", "eligibility":"Newcomers","point_deduction":135000}];
    
    const [columns, setColumns] = React.useState([]);

    React.useEffect(() => {
        reward_content.map((reward, idx) => {
            setColumns([...columns, <Item key={idx} value={reward} />]);
        });
    }, [])

I am updating my array with useState inside useEffect. But somehow everytime I print and render my array, I always find out that my array still empty. I know from here that I cannot use array push for updating my array, so I use array spread instead. But, somehow it is still not working.

Please can someone spot my mistakes ? Thank You

Is it necessary to use try/catch when testing callbacks with Jest?

I am running a set of tests with Jest 29.7.0 and Node.js 20.10.0, and need to test some callback functions.

The Callbacks section of the Jest documentation explains how to test callback code and gives the following example:

test('the data is peanut butter', done => {
  function callback(error, data) {
    if (error) {
      done(error);
      return;
    }
    try {
      expect(data).toBe('peanut butter');
      done();
    } catch (error) {
      done(error);
    }
  }

  fetchData(callback);
});

The following explanation of this code states that the expect function must be executed inside a try block, otherwise the done callback is never called in case of the verification failure, and the test will fail with a timeout instead of the actual verification error.

But if I modify this test and remove the try/catch, I still see the correct error message if expect fails the test.

import { fetchData } from "./testutils";

test('the data is peanut butter', done => {
    function callback(error, data) {
        if (error) {
            done(error);
            return;
        }

        expect(data).toBe('peanut butter');
        done();
    }
  
    fetchData(callback);
});

This is my fetchData function:

export function fetchData(callback) {
    callback(undefined, 'strawberry jam');
}

And the correct error message (no timeout here):

  ● the data is peanut butter
                                                                                                                                                                                                                                                                                                                                       
    expect(received).toBe(expected) // Object.is equality

    Expected: "peanut butter"
    Received: "strawberry jam"

       8 |         }
       9 |
    > 10 |         expect(data).toBe('peanut butter');
         |                      ^
      11 |         done();
      12 |     }
      13 |

If I google this topic, I see both kinds of examples – with try/catch and without it. Is this documentation entry misleading/outdated? Or are there nuances not covered in the document and I should expect my tests without try/catch to misbehave in some situations?

react.development.js and Uncaught ReferenceError: useState is not defined

I am trying to get some React code to work. I need to work with react.development.js and not React on the server side. I am trying to solve a different issue and I wanted to use useState for that, but this fails.

The start of my page has:

  <head>
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

and much of React works. But when I try to use useState, e.g. in:

        const ReminderSet = () => {
            console.log( "Reminderset Rendering");
            const [reminders, setReminders] = useState(defaultReminder);

I get an error in the console, e.g. in Firefox:

Uncaught ReferenceError: useState is not defined

image wont be displayed when i reference it in JSON.(React web app project)

Ive tried to display the image from my image folder but it doenst work. Ive tried to display an image from the internet and it works just fine. what could be the problem? Ive even put the image in the same folder as the json but it doesnt help.

CardBox.js

import React from 'react';
import '../styles_sections/style_CardBox.css';

function CardBox({ data }) {
    return (
        <div className="card-box-container">
            {data.map((item, index) => (
                <div className="card" key={index}>
                    <img src={item.imageSrc} alt={item.title} className="card-image" />
                    <h2 className="card-title">{item.title}</h2>
                    <p className="card-text">{item.text}</p>
                    <button className="card-button">{item.buttonText}</button>
                </div>
            ))}
        </div>
    );
}

export default CardBox;

Path: react-projectsrcsectionsCardBox.js

path of the image i want to use: react-projectsrcimagesimages-CardBoxgym.png

cardDataHome.json
[
    {
      "imageSrc": "../../images/images-CardBox/dumbell.png",
      "title": "Home Title 1",
      "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
      "buttonText": "Button 1"
    },
    {
      "imageSrc": "path/to/home-image2.jpg",
      "title": "Home Title 2",
      "text": "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
      "buttonText": "Button 2"
    },
    {
      "imageSrc": "path/to/home-image3.jpg",
      "title": "Home Title 3",
      "text": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      "buttonText": "Button 3"
    }
  ]

Path: react-projectsrcdatadata-CardBoxcardDataHome.json

How to add an event listener to elements (or children)

I’m using a Syncfusion plugin to render a PDF in a React project. But I need an onMouseEnter event on each page (which renders as canvasses)… but it is not available currently as part of the plugin.

Short of modifying the plugin or using a patch to modify the plugin, is there a way I can attach an event listener on all canvas elements (or all children) of a specific div?

I know React does not always like event listeners (since it messes with the Virtual DOM or something), so is there any smart way to do it, or should I just bite the bullet and try to modify the package?

preserve phase when using getByteTimeDomainData

I’m trying to draw an oscilloscope style visualization using this guide : https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData

I would like to preserve the phase of the wave from one frame to another (otherwise the wave “shifts” progressively from one side of the canvas to the other).

I’m basically alterring the code like that:

    let last = analyser.context.currentTime;
    const waveArrayDuration = analyser.fftSize / analyser.context.sampleRate;
    const waveArrayStepDuration = 1 / analyser.context.sampleRate;
   
    function draw() {
        // [...]

        const now = analyser.context.currentTime;
        analyser.getByteTimeDomainData(dataOscilloscopeArray);
        let elapsed = now - last;
        last = now;

        const shift = Math.round((waveArrayDuration - (elapsed % waveArrayDuration)) / waveArrayStepDuration);

        for (let x = 0; i < bufferLength; i++) {
            const i = (shift + x) % bufferLength;
            const v = dataArray[i] / 128.0;
            const y = (v * HEIGHT) / 2;

the gist of it being this line:

const shift = Math.round((waveArrayDuration - (elapsed % waveArrayDuration)) / waveArrayStepDuration);

which I determined using the following assumptions:

  1. each item in the array is spaced from the next one by the sample rate (1 / sampleRate)
  2. the whole array is this duration times the fftSize
  3. shift is trying to be the start of the array so that the phase does not vary from one frame to another

Here’s how it looks like:

shift doesn't work

Obviously this is not right. I figured out a hackish way to guess the phase which looks better (code for this is irrelevant to the question ; but result is similar to what I’m trying to achieve):

working shift

But I’d rather determine the start of the array using timings instead. Are my assumptions about getByteTimeDomainData correct? Is there a standard way to achieve this (basically what an analog oscilloscope does I assume).

[webpack.cache.PackFileCacheStrategy]Serializing big strings(101kiB)impacts deserialization performance(consider using Buffer instead&decode when n

something wrong with my mongoDB connection or clerkid or webpack. its not fetching userids and also showing // This is a native JavaScript error (e.g., TypeError, RangeError)
17 | console.error(error.message);

18 | throw new Error(Error: ${error.message});
| ^
19 | } else if (typeof error === “string”) {
20 | // This is a string error message
21 | console.error(error); please let me know how to solve this

i want to resolve this problem its related to mongodb connection in atlas and clerkif and webhooks

Web Crypto API decryption failing with RSA-OAEP

I have generated private key as following:

openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

openssl rsa -pubout -in private_key.pem -out public_key.pem

openssl pkcs8 -topk8 -inform PEM -outform PEM -in private_key.pem -out private_key_pkcs8.pem -nocrypt

The private key is embedded in the code snippet. Then I ecrypted a plaintext like the following:

echo -n "abcdef" | openssl rsautl -encrypt -pubin -inkey public_key.pem | openssl base64 > enc_simple.txt

This is also embedded in the code snippet. If I do the following:

base64 -d enc_simple.txt > enc_simple.bin
openssl rsautl -decrypt -inkey private_key_pkcs8.pem -in enc_simple.bin -out decrypted_simple.txt

I get back “abcdef”. SO with openssl everything is working. Then I want to recreate this entire scenario using Web Crypto API but the decryption is failing. Importing the private key is ok but the rest fails with OperationError with no error message. It is extremely obscure and hard to debug.

I have also ran:

od -An -vtu1 enc_simple.bin

to see the Uint8Array values and compare them with what I get from str2ab from the codesnippet. They match!

So I am stuck with no error message. I am trying to understand why the decryption is failing.

const ecryptedData = `gLiN3BLWTxbwpE5bwcFiB7Y/nK0H4iz9lK0sehMIJtoAPibDPZ8EYp8EnzsGFlKC
+GXse6Ka5YC7UKYn7xUvfBbCDSY7RJ/J9oAzpCEHvCnFOmrsvUtNEhP4w3LTaKL/
qKmjQZaPlZNWCmrzrW3g2A6DUCqLx5EQwCcwME2WjYVhuMZfZOKqtp+uukJMUf3h
cC9J8QkPCk1NZogCad29b7q7JLN1uWEQzOUgB6BqJfAp8kL92dftOy2gpWoGYraI
YPU3Tmp12txMyUY0yKsr4c2dOzxwWUW+ZssVkc6ZGqFVufADziZDp2sfFaz8yBuI
qek7S0KXd6A7qWBYBrzzyw==`;
const privKeyPEM=`-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJiQlvlYbTqi/W
bLa7nzaF4Wz+ypQa01HD+UMHX25Uv3n6P69ucKs/OOdWbcenknAmSBK/VzgIsjlm
vak3y1LoYImMhm8R26Arv8Fv7jwQkbBxVnOn6yfTL2h1SRK+zFzWumfbl2vp7POG
s7CRQaK0HFPKroVlYHlinTlYXSlFqdaknH2ip1J2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p0jynhiM3qzA7zZv0JissfdO9RbBGJHBczvtl+
J0/0kuv0OVbqgTfpBMBTZIsAuAzJ8+F2+AD8IDqT9uxQkcYVt0tRSc2w1VuioxZH
TyhiPoycPFcdADpS6MEPLi11c3NgqEf0IgFVZ0CBAoGBAMybGC+IImSDpZzLaSpz
KAD6Vyto7eK4pENH8bPcM2Hpy7aMGJkr6Q/NT34p/vSfFG2gm8ueILhvqQ8yB6h6
gtfHOEu7CC/8WL4Y/WehrpD+fTTSOd/C+JZJbXjHjJ55NX1JzgeCPWJP2QOyXE85
VLq+2V8bhsQxi4JylnH6suLB
-----END PRIVATE KEY-----`
const
    atob = (window || self)?.atob,
    subtle = (window || self).crypto.subtle,
    trimWs = (s) => s.replace(/s*/g,""),
    trimHeader = (s) => s.replace(/-----(?:BEGIN|END) PRIVATE KEY-----/gi, "");
async function importPrivateKey (pemkey) {
    const binaryKey = atob(trimWs(trimHeader(pemkey)));
    const keyBuffer = new Uint8Array(binaryKey.length);
    for (let i = 0; i < binaryKey.length; i++) {
        keyBuffer[i] = binaryKey.charCodeAt(i);
    }
    return await subtle.importKey(
        "pkcs8",
        keyBuffer,
        { name: "RSA-OAEP", hash: "SHA-256"},
        false,
        ["decrypt"]
    );
}
async function decryptData (privateKey, encryptedData) {
      const decrypted = await subtle.decrypt(
          { name: "RSA-OAEP", hash: "SHA-256"},
          privateKey,
         str2ab(atob(trimWs(encryptedData)))
      );
      return (new TextDecoder('utf-8')).decode(decrypted);
}
function str2ab (binaryStr) {
    const len = binaryStr.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryStr.charCodeAt(i); // Accurately map each char to a byte
    }
    return bytes; // Convert to ArrayBuffer
};


(async () => {
  try {
    const privKey = await importPrivateKey(privKeyPEM);
    console.log(privKey);
    const decrypted = await decryptData(privKey, ecryptedData);
  } catch (err) {
    console.error("Err:", err, "Err.massage:", err.message);
  }
})()

Discarding of media-queries OR updating them to the correct sizes

Hello dear community of @StackOverflow,

The media queries of the site are situationed around 992px, i need them however to be at 1375px.
I have worked out all the changed classes with the 1375px version.

Issue: When adding the new changed queries at 1375px the old one have an effect which makes everything a bit more complex.

Question: How to change the media queries in a way that the 992px ones gets updated to 1375px OR how to disable the previous media-queries of 992px, so that the new ones at 1375px have an full effect without worries ?

Conditional Validation in Express-Validator

I am trying to write a conditional validation using express-validator that would validate franchiseId based on the input of another field. I have three validations for the field, out of which two work as expected but the third is not. Could anyone please help me out with this?

I have the following two properties:
allFranchises:boolean
franchiseId:uuid

I want to write a rule which checks the following:

if (franchiseId is present)
    franchiseId should be UUID

if (allFranchise === true)
    franchiseId should be null
else 
    franshieId should NOT be null

I have the following rule written using express-validator

body("franchiseId")
        .optional({ nullable: true }).default(null)
        .if(franchiseId => !!franchiseId).isUUID().withMessage("FranchiseId must be a UUID.").bail()
        .if(body("allFranchises").equals("true")).isEmpty().withMessage("FranchiseId must be null if allFranchises is true.").bail()
        .if(body("allFranchises").equals("false")).notEmpty().withMessage("FranchiseId cannot be null if allFranchises is false.").bail(),
  • The first rule works as expected, passing non-UUID spits out error
  • Second rule works; allFranchises = true and franchiseId = <some-uuid> spits out error
  • Third NEVER works; allFranchises = false and franchiseId = null (or '') just passes

What am I doing wrong here? Why do the first two conditions work as expected and not the third one?

How to trim the innerHTML string upto a specific element inside it?

I want to find out how we can get the innerHTML string upto a specific element inside the element.

Example :

<div id="common-name">
        <p id="P1">This is a paragraph 1.</p>
        <p id="P2" >This is a paragraph 2 .</p>
        <p id="P3">This is a paragraph 3.</p>
</div>

Say we want it upto the element with id: P2 , so output as a string would be like :

<div id="common-name"><p id="P1">This is a paragraph 1.</p>

(Also if any implementation exists can it be done if the elements didn’t have the ID, rather the ref as a object in JavaScript.

I tried getting the innerHTML content as a string but have no idea how to get the rest of the text after the element, so that i could subtract it from the original string to have the same output.

Network request failed anyone who could share his experience

I have this formdata of different data representation one is QOS and the other is DP the QOS has some data with images and the DP do not have images,I’m able to submit the QOS data with images successfully but the DP when picked and the inputs were given I received network request failed which I do not know why… could it be that I have to specific length index 0 for the images so has to bypass. I do not understand, anyone who understand this kindly assist thank you… react native and drf

Creating DOM element – Uncaught TypeError: Cannot read properties of null (reading ‘appendChild’)

Im trying to dynamically append a div element into HTML DOM from JS script, like:

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

    <style>
        .chart-container {
            position: relative;
            height: 40vh;
            width: 80vw;
        }
    </style>

    <script defer>
        var divContainer = document.createElement('div');
        divContainer.className = 'chart-container';
        document.body.appendChild(divContainer);

        ... REST OF THE SCRIPT
    </script>
</head>
<body>
    <h1>Metrics Information:</h1>
</body>
</html>

But for some reason this results only in:

Uncaught TypeError: Cannot read properties of null (reading 'appendChild')