Chat Render 4 times

Okay, so basically I am working with reactjs using vite and trying to make a chat App.

There are few files
FirebaseConfig, firebaseConetxt(my context)
App.jsx->mainPage.jsx->currentChat.jsx & sidebar.jsx

Its all wrapped in firebaseContextProvider.
When I send Message my currentChat variable which is defined inside firebaseContext.jsx rerender 4 times. I don’t want to rerender it’s again and again

Plz don’t confuse there is one currenChat.jsx file and currentChat array. I am uploading firebaseContextProvider as image file .

enter image description here
CurrentChat.jsx file is here

import React, { useState } from 'react';

import { MdPermMedia } from 'react-icons/md';

import { BsFillSendFill } from 'react-icons/bs';

import { useFirebaseContext } from '../../context/firebaseContext';



const CurrentChat = () => {

    // Using context and state from Firebase context

    const { userSelected, currentUser, createFriend, sendMessage, currentChat } = useFirebaseContext();

    const [input, setInput] = useState("");



    // Function to send a message

    const inputSender = async () => {

        await createFriend(input);

        await sendMessage(input);

    };

    



    // Render the component only if a user is selected

    if (userSelected) {

        return (

            <div className="relative bg-purple-300 h-full md:w-3/4 w-2/3 overflow-x-hidden">

                {/* Top Bar */}

                <div className="sticky w-full bg-purple-300 top-0">

                    <div className="w-full h-12 flex items-center justify-between px-2 py-2">

                        <div className="h-full flex items-center gap-2 cursor-pointer">

                            <img className="h-9 w-9 object-cover rounded rounded-full" src={userSelected.profileImage} alt="" />

                            <h2 className="text-xl">{userSelected.name}</h2>

                        </div>

                    </div>

                    <div className="h-[.3px] w-full bg-gray-400"></div>

                </div>



                {/* Chats */}

                <div className="h-full w-full p-2 mb-6 flex flex-col">

                    {/* Add your chat UI here */}

                    {currentChat && currentChat.map((message,index)=>(

                        <div key={index} className={`my-2 w-fit md:max-w-[60%] max-w-[90%] break-words p-2 rounded-xl bg-blue-500

                            ${message.sender == currentUser.uid ? 'rounded-tr-none self-end' : 'rounded-tl-none' }`}>

                            <p>{message.message}</p>

                        </div>

                    ))

                    }

                </div>



                {/* Input Bar */}

                <div className="md:w-3/4 w-2/3 fixed h-12 bottom-0 bg-red-400 flex items-center justify-center">

                    <div className="w-full h-10 my-2 mx-1 flex items-center justify-center gap-2">

                        <input className="h-full w-full outline-none rounded rounded-xl p-2 text-xl" type="text" onChange={(e) => setInput(e.target.value)} value={input} />

                        <input className="w-full hidden" id="fileSender" type="file" />

                        <label className="cursor-pointer text-2xl" htmlFor="fileSender">

                            <MdPermMedia />

                        </label>

                        <button onClick={inputSender} className="cursor-pointer text-xl">

                            <BsFillSendFill />

                        </button>

                    </div>

                </div>

            </div>

        );

    } else {

        // If no user is selected, render nothing

        return null;

    }

};


 export default CurrentChat;

Also my chat div show me from top so I have to scroll function if there any solution for that.

Problem using React useState in faq accodion application

There is a challenge on the frontend mentor website (FAQ accordion). I have solved the challenge using React. However, my code is not working properly.

Except for the first click on any question when page loads, I have to double-click each question to toggle it. I suspect something wrong in my code with useState.

I created a component that renders a list of questions/answers and displays them using the details HTML tag. I want to solve the problem using the details tag only.

Here is my code for the component:

import { Fragment, useState } from "react";
import minus from "./icon-minus.svg";
import plus from "./icon-plus.svg";

const Faq = ({ questionsObj }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  function handleClick(id) {
    if (selectedId !== id) {
      setSelectedId(id);
    }
    if (selectedId === id) {
      setIsOpen(!isOpen);
    }
  }

  return (
    <main>
      {questionsObj.map((question, index) => (
        <Fragment key={question.id}>
          <details
            onClick={(e) => handleClick(question.id)}
            open={selectedId === question.id ? isOpen : null}
          >
            <summary>
              <span>{question.question}</span>

              <img
                src={
                  isOpen === false && selectedId === question.id
                    ? `${minus}`
                    : `${plus}`
                }
                alt=""
              />
            </summary>
            <p className="animate__animated animate__flipInX">
              {question.answer}
            </p>
          </details>
          {index !== questionsObj.length - 1 ? <hr /> : null}
        </Fragment>
      ))}
    </main>
  );
};

export default Faq;

I also think my code is not good to solve simple problem like this accordion. I would appreciate if someone tell me where is the problem in my code.

Thanks

Vite v5 build preview: This localhost page can’t be found

I am building a React project to be published as an NPM package.

I’ve set up a React app via npm create vite@latest my-app -- --template react.

Here are the module settings and Vite script commands in package.json:

"name": "my-app",
"type": "module",
"files": [
  "dist"
],
"main": "./dist/my-app.umd.cjs",
"module": "./dist/my-app.js",
"exports": {
  ".": {
    "import": "./dist/my-app.js",
    "require": "./dist/my-app.umd.cjs"
  },
  "./dist/index.css": "./dist/style.css"
},
"scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },

When I run npm run dev, dev server starts and the app works as expected.

When I run npm run build the app bundles the files in the dist folder as expected.

The problem is, once I tried to preview the dist build by running npm run preview, it gives me an error “This localhost page can’t be found”.

Here are my settings in vite.config.js:

import { defineConfig } from "vite";
import { resolve } from "path";

export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, "src/main.jsx"),
      name: "my-app",
      fileName: "my-app",
    },
    rollupOptions: {
      external: ["react", "react-dom"],
      output: {
        globals: {
          react: "React",
          "react-dom": "ReactDOM",
        },
      },
    },
  },
});

And the src/main.jsx to render the app:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Since I’m using Vite library mode, I am wondering if there are any other settings I must use for build preview to work?

I’ve also published the library to NPM registry to test it and I can install it via npm i my-app and the app works as expected, so the build must be right. Its just that I cant access the build preview in the development mode.

Thanks a lot in advance!

How can we call Nextjs API from Nextjs Pages?

I want to load data on the home page for which I’ve written an API in nextjs project. I am able to call that api at client side using useEffect but I want to load the data at server side only so I was trying to call the api from getServerSideProps.
My question here is that is this possible? calling the api from getServerSideProps as I was getting error when I use fetch and deploy it.
and If I directly try to use the api function inside getServerSideProps then it says that the status

This is the code I am using
Code Image
This is the error I am getting
enter image description here

If I try to use statusCode instead of status then also it throws error
enter image description here

ELECTRON ERROR: shell_ipc_client.cc:139:Connect Can’t connect to socket

Im making an app with Electron, I have an input file tag in html

<input type="file" class="visually-hidden" id="upload-input" accept=".jpg, .jpeg, .png" multiple>

Whenever I click it, window opens for images selection, but at the same time on its click I see this error on the terminal even I am not using any google drive etc.



2024-02-19T17:40:26.537ZE [19184:ShellIpcClient] shell_ipc_client.cc:139:Connect Can't connect to socket at: \.PipeGoogleDriveFSPipe_Abdul Rafey_shell
2024-02-19T17:40:26.543ZE [19184:ShellIpcClient] shell_ipc_client.cc:622:operator() Failed to connect to the server: NOT_FOUND: Can't connect to socket at: \.PipeGoogleDriveFSPipe_Abdul Rafey_shell [type.googleapis.com/drive.ds.Status='UNAVAILABLE_RESOURCE']
=== Source Location Trace: ===
apps/drive/fs/ipc/shell_ipc_client.cc:140

2024-02-19T17:40:26.545ZE [15996:ShellIpcClient] shell_ipc_client.cc:139:Connect Can't connect to socket at: \.PipeGoogleDriveFSPipe_Abdul Rafey_shell
2024-02-19T17:40:26.545ZE [15996:ShellIpcClient] shell_ipc_client.cc:622:operator() Failed to connect to the server: NOT_FOUND: Can't connect to socket at: \.PipeGoogleDriveFSPipe_Abdul Rafey_shell [type.googleapis.com/drive.ds.Status='UNAVAILABLE_RESOURCE']
=== Source Location Trace: ===
apps/drive/fs/ipc/shell_ipc_client.cc:140

2024-02-19T17:40:26.548ZE [3636:ShellIpcClient] shell_ipc_client.cc:139:Connect Can't connect to socket at: \.PipeGoogleDriveFSPipe_Abdul Rafey_shell
2024-02-19T17:40:26.548ZE [3636:ShellIpcClient] shell_ipc_client.cc:622:operator() Failed to connect to the server: NOT_FOUND: Can't connect to socket at: \.PipeGoogleDriveFSPipe_Abdul Rafey_shell [type.googleapis.com/drive.ds.Status='UNAVAILABLE_RESOURCE']
=== Source Location Trace: ===
apps/drive/fs/ipc/shell_ipc_client.cc:140

Everything in my app is working fine, but still i don’t know why I’m getting this error.
I need help!!

Chrome/ium incorrectly reporting OnPointerDown events for touch input

I’ll skip the story of how I got here, but I’m trying to show the coordinates of touch or click events in the browser window as a sort of diagnostic/demo thing.

The basic code is this:

    document.addEventListener('pointerdown', (event) => {
        var x = 0;
        var y = 0;
        if (event.pointerType === "mouse")
        {
            x = event.clientX;
            y = event.clientY;
        }
        else if (event.pointerType === "touch")
        {
            x = event.touches[0].clientX;
            y = event.touches[0].clientY;
        }
        //else if (event.pointerType === "pen") {}
        document.getElementById("demo").innerHTML = "x = " + x + ", y = " + y + "<br>" + event.pointerType;
        console.log(event);
    });

Now, this is pretty simple and pulled right from the most obvious examples found on google (MDN / W3C / etc.)

All I’m doing in the document is filling the screen with a table of cells to make a grid so that we can easily show where clicks happened:

    $('table').on('click', 'td', function()
    {
        $(this).addClass("active"); // Add colour to show cell got clicked
    });

This just changes the colour of the table cell where the click happened, to give visual feedback.

On Firefox it works as expected – when you click a table cell it changes colour and the “demo” div gets populated with X and Y coordinates and a source name, although it’s worth saying Firefox reports the event as “mouse”.

In Chromium, the cells still react to the click & change colour but the event listener throws an error. Chromium gives me the following errors in the console:

Uncaught TypeError: Cannot read properties of undefined (reading '0')
    at HTMLDocument.<anonymous> (tt.html:123:23)

Which looks to me like the event/callback is happening but Chromium is not getting or perhaps not passing on the correct event type to the code?

To summarise:

| Reports...  | Firefox | Chromium |
|-------------|---------|----------|
| Mouse click | 'mouse' | 'mouse'  |
| Touch       | 'mouse' | Error    |

Anyone seen this or got any idea what I’m doing wrong here?

Google Appscript split text till last untill not get blank

we have the following app script but now we want that it will check the B3,C3 and D3 and after that B4,C4 and D4 and do this until not go to blank cell

appscript code is

function work() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var dataB = sheet.getRange("B2").getValue().toString().split("/");
  var dataC = sheet.getRange("C2").getValue().toString().split("/");
  var dataD = sheet.getRange("D2").getValue().toString().split("/");
  
  for (var i = 0; i < dataB.length; i++) {
    sheet.getRange(i + 2, 6).setValue(dataB[i]);
  }
  
  for (var j = 0; j < dataC.length; j++) {
    sheet.getRange(j + 2, 7).setValue(dataC[j]);
  }
  
  for (var k = 0; k < dataD.length; k++) {
    if (dataD[k]) {
      sheet.getRange(k + 2, 8).setValue(dataD[k]);
    }
  }
}

Using AJAX to open URL isn’t being called

My page is doing a few things. It takes data, passes it to back4app.com to my Parse server to save the data in a class called Registration, then sends everything over to Square to make an order, customer, and invoice. A lot of this is in CloudCode on my server, and it all works. Everything saves, the invoice is made by Square and even emailed. What I’d like for it to do as well is to take the public_url provided by Square and open a webpage so when the invoice is created, it will open it automatically. In my code for the HTML I have:

function createSquareInvoice(accessToken, invoiceDetails, orderID, userName, userEmail, congregation, phoneNumber, roomselectedItems) {
    var parameters = {
        accessToken: accessToken,
        invoiceDetails: invoiceDetails,
        orderID: orderID,
        name2: userName,
        email2: userEmail
    };

    // Use AJAX to call the Parse Cloud function to create the Square invoice
   $.ajax({
     
        url: 'https://parseapi.back4app.com/functions/createSquareInvoice',
        type: 'POST',
        headers: {
            'X-Parse-Application-Id': 'APPID',
            'X-Parse-REST-API-Key': 'RESTKEY',
            'Content-Type': 'application/json'
        },

        data: JSON.stringify(parameters),
        success: function (result) {
            console.log("Invoice created successfully: " + result);
            var invoiceDict = result.invoice;
            var invoiceURL = invoiceDict.public_url;
           alert("Invoice URL: " + invoiceURL);

            // Log the invoice URL
            console.log("Invoice URL:", invoiceURL);

            // Navigate the current window to the invoice URL
            window.location.href = invoiceURL;
        },
        error: function (xhr, status, error) {
        console.error("Error creating invoice:", xhr.responseText); // `xhr.responseText` should contain the error message

        // Handle HTTP errors
        var errorMsg = xhr.responseJSON ? xhr.responseJSON.error : xhr.responseText;
        alert("Failed to create invoice: " + errorMsg);
        console.error(xhr.status, status, errorMsg);
    }
    });
}

However, the console, essentially shows me NOTHING. Everything is created fine, but in console I get:

Refused to get unsafe header "access-control-expose-headers"
a.onreadystatechange @ parse.min.js:14
XMLHttpRequest.send (async)
r @ parse.min.js:14
ajax @ parse.min.js:14
(anonymous) @ parse.min.js:14
Promise.then (async)
request @ parse.min.js:14
run @ parse.min.js:14
r.run @ parse.min.js:14
finalizeAndPay @ EYCTest.html:259
onclick @ EYCTest.html:102

Then success in console for creation of the invoice.

The relevant function in my CloudCode is:

Parse.Cloud.define("createSquareInvoice", async (request) => {
    const { totalAmount, currency, title } = request.params.invoiceDetails;
    const { orderID, name2, email2 } = request.params; // Retrieve the order ID, name, and email from the request

    try {
        // Create the customer in Square
        const customerID = await createSquareCustomer(name2, email2); // Pass name and email to the function
        console.log("Customer created in Square with ID:", customerID);

        // Generate a new idempotency key for this request
        const idempotencyKey = generateUUID();

        // Create the payment request object
        const paymentRequest = {
            request_type: "BALANCE",
            due_date: "2024-03-13",
            tipping_enabled: false,
            automatic_payment_source: "NONE"
        };

        // Create the primary recipient object with the generated customer ID
        const primaryRecipient = {
            customer_id: customerID
        };

        // Construct the invoice object
        const invoice = {
            order_id: orderID,
            payment_requests: [paymentRequest],
            primary_recipient: primaryRecipient,
            title: title,
            description: "Invoice for EYC 2024 Registration",
            delivery_method: "EMAIL",
            sale_or_service_date: "2023-12-11",
            accepted_payment_methods: {
                card: true,
                bank_account: true
            }
        };

        // Use Parse.Cloud.httpRequest to make a request to the Square API
        const response = await Parse.Cloud.httpRequest({
            method: 'POST',
            url: 'https://connect.squareupsandbox.com/v2/invoices',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ACCESSTOKEN', // Replace with your Square Access Token
                'Idempotency-Key': idempotencyKey,
              'Access-Control-Expose-Headers': 'InvoiceID'   // Add the idempotency key to the request headers
            },
            body: { invoice } // Wrap the invoice object in a 'invoice' property
        });

        // Parse the invoice ID from the response
        const invoiceID = JSON.parse(response.text).invoice.id;

        // Use Parse.Cloud.httpRequest to make a request to publish the invoice
        const publishResponse = await Parse.Cloud.httpRequest({
            method: 'POST',
            url: `https://connect.squareupsandbox.com/v2/invoices/${invoiceID}/publish`,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ACCESSTOKEN', // Replace with your Square Access Token
                'Idempotency-Key': idempotencyKey,
                'Access-Control-Expose-Headers': 'InvoiceID'  // Add the idempotency key to the request headers
            },
            body: {
                version: 0
            }
        });

        // Parse and return the response
        return JSON.parse(publishResponse.text);
    } catch (error) {
        throw new Error(`Error creating invoice: ${error.message}`);
    }
});

wrong calculations in a simple summing loop JavaScript

I’ve asked this question before and your answers worked!
text
But now it doesn’t lol.

I’ve managed to optimize my code from around 1000 lines to 100 lines and something is wrong.

I have problems with reseting tot variable each time to 0. So 1 + 2 is 3, but my result is 4, and with each iteration it gets more wrong.

let myInputField = document.querySelectorAll(".text");

myInputField.forEach((el) => {
  el.addEventListener("input", () => {
    let tot = 0; // Resets tot to 0 on each input event
    for (let i = 0; i < myInputField.length; i++) {
      if (parseInt(myInputField[i].value))
        tot += parseInt(myInputField[i].value);
    }
    document.querySelector(".bonusResult").value = tot;
  });
});
<p class="score"><input type="text" class="text"></p>
<p class="score"><input type="text" class="text"></p>
<p class="score"><input type="text" class="text"></p>
<p class="score"><input type="text" class="total" id="suma"></p>

It is identical as in previous topic from the link above but this time the calculations are wrong, home come?

DOM diff algorithm with HTML streaming?

Does anybody know if the DOM diff algorithm can be applied in Depth-first search (DFS) instead of Breadth-first search (BFS)? I’ve been trying for days to get the DOM diff algorithm to work with streaming HTML, but I’m having troubles (different approach than React). Does anyone know of an open-source example?

For now I did this helper to get the Nodes from streaming:

const START_CHUNK_SELECTOR = "S-C";
const START_CHUNK_COMMENT = `<!--${START_CHUNK_SELECTOR}-->`;
const decoder = new TextDecoder();
const parser = new DOMParser();

/**
 * Create a generator that extracts nodes from a stream of HTML.
 *
 * This is useful to work with the RPC response stream and
 * transform the HTML into a stream of nodes to use in the
 * diffing algorithm.
 */
export default async function* parseHTMLStream(
  streamReader: ReadableStreamDefaultReader<Uint8Array>,
  ignoreNodeTypes: Set<number> = new Set(),
  text = "",
): AsyncGenerator<Node> {
  const { done, value } = await streamReader.read();

  if (done) return;

  // Append the new chunk to the text with a marker.
  // This marker is necessary because without it, we
  // can't know where the new chunk starts and ends.
  text = `${text.replace(START_CHUNK_COMMENT, "")}${START_CHUNK_COMMENT}${decoder.decode(value)}`;

  // Find the start chunk node
  function startChunk() {
    return document
    .createTreeWalker(
      parser.parseFromString(text, "text/html"),
      128, /* NodeFilter.SHOW_COMMENT */
      {
          acceptNode:  (node) =>  node.textContent === START_CHUNK_SELECTOR 
            ? 1 /* NodeFilter.FILTER_ACCEPT */
            : 2 /* NodeFilter.FILTER_REJECT */
      }
    )
    .nextNode();
  }

  // Iterate over the chunk nodes
  for (
    let node = getNextNode(startChunk());
    node;
    node = getNextNode(node)
  ) {
    if(!ignoreNodeTypes.has(node.nodeType)) yield node;
  }

  // Continue reading the stream
  yield* await parseHTMLStream(streamReader, ignoreNodeTypes, text);
}

/**
 * Get the next node in the tree.
 * It uses depth-first search in order to work with the streamed HTML.
 */
export function getNextNode(
  node: Node | null,
  deeperDone?: Boolean,
): Node | null {
  if (!node) return null;
  if (node.childNodes.length && !deeperDone) return node.firstChild;
  return node.nextSibling ?? getNextNode(node.parentNode, true);
}

Then I can use the stream nodes directly with:

const reader = res.body.getReader();

for await (const node of parseHTMLStream(reader)) {
  console.log(node);
}

But then you lose context of whether it was child, slibing and which real dom it has to compare with without creating bugs by updating only the DOM nodes that have changed. I have come to think that if React and all the examples are in Breadth-first that it is not that you can’t implement the DOM diff algorithm with Depth-first. Is this so? And if not, does anyone have an example of how it would be implemented?

Cypress JavaScript only able to push the last item even I use the BeforeEach() and AfterEach()

I am currently learning the Cypress and I would like to sort the array data that get from different website but I failed to push the array to my array list when I try with any cy. function, the before and after each function are working fine.

describe('Compare iPhone 15 Pro between eBay and Apple Store', () => {
    let productDetails = [];

    beforeEach(() => {
        // Load the existing productDetails array from localStorage if it exists
        const storedProductDetails = localStorage.getItem('productDetails');
        if (storedProductDetails) {
            productDetails = JSON.parse(storedProductDetails);
        }
    });

    afterEach(() => {
        // Store the productDetails array back into localStorage
        localStorage.setItem('productDetails', JSON.stringify(productDetails));
    });

    it('Visit eBay and gets the product details', () => {
        // Visit eBay and get product details
        // ...
        productDetails.push({ website: 'eBay', product: 'iPhone 15 Pro 256GB', price: itemPrice, link: linkValue });
    });

    it('Visit Apple store and gets the product details', () => {
        // Visit Apple store and get product details
        // ...
        productDetails.push({ website: 'Apple Store', product: 'iPhone 15 Pro 256GB', price: itemPrice, link: linkValue });
    });

    it('Print the product details array', () => {
        // Log the product details array
        for (let i = 0; i < productDetails.length; i++) {
            cy.log('Product Details: ' + JSON.stringify(productDetails[i]));
        }
    });
});

when I add my cy. function inside then I am not able to push the data into the array, I only able to push the last item to the array. Below is my code:

describe('Compare iPhone 15 Pro between eBay and Apple Store', () => {
    let productDetails = [];

    beforeEach(() => {
        // Load the existing productDetails array from localStorage if it exists
        const storedProductDetails = localStorage.getItem('productDetails');
        if (storedProductDetails) {
            productDetails = JSON.parse(storedProductDetails);
        }
    });

    afterEach(() => {
        // Store the productDetails array back into localStorage
        localStorage.setItem('productDetails', JSON.stringify(productDetails));
    });

    it('Visit eBay and gets the product details', () => {
        // Visit eBay and get product details
        // ...
        cy.visit('https://www.ebay.com.my/');
    
        // Search for iPhone 15 Pro 256GB
        cy.get('input.gh-tb[name="_nkw"]').type('iphone 15 pro 256gb new'); // class & attribute
        cy.get('input#gh-btn').click();
    
        cy.get('.srp-results.srp-list.clearfix').within(() => {
            cy.get('li').first().should('be.visible');
        });
    
        cy.get('li#item405343ae00 span.s-item__price span.ITALIC').invoke('text').then((price) => {
            const itemPrice = price;
            cy.log('Price: ', itemPrice);

            cy.url().then(url => {
                cy.log('Current URL:', url);
                const linkValue = url;
                productDetails.push({ website: 'eBay', product: 'iPhone 15 Pro 256GB', price: itemPrice, link: linkValue });
                localStorage.setItem('productDetails', JSON.stringify(productDetails));
                cy.log('Product Details eBay: ', productDetails);
            });
        });
        //productDetails.push({ website: 'eBay', product: 'iPhone 15 Pro 256GB', price: 'itemPrice', link: 'linkValue' });
    });

    it('Visit Apple store and gets the product details', () => {
        // Visit Apple store and get product details
        // ...
        cy.visit('https://www.apple.com/my/');
        cy.get('#globalnav-menubutton-link-search').click();

        cy.get('.globalnav-searchfield-input').type('iphone 15 pro 256gb new').type('{enter}');
        cy.get('[data-analytics-title="iPhone 15 Pro and iPhone 15 Pro Max - Apple (MY)"]').click();

        cy.title().should('eq','iPhone 15 Pro and iPhone 15 Pro Max - Apple (MY)');

        cy.contains(/Buy/i);
        cy.get('.welcome__lockup-cta.show').click();

        cy.contains(/Buy iPhone 15 Pro/i);

        cy.get('.rc-dimension-selector-group.form-selector-group .rc-dimension-selector-row.form-selector').first().click();

        cy.get('.colornav-items').within(() => {
            cy.get('li').first().click();
        });

        cy.get('.form-selector-title:contains("256")').click();

        cy.contains(/iPhone 15 Pro/i);
        cy.wait(2000);
        cy.get('.rc-prices-fullprice[data-autom="full-price"]').first().invoke('text').then((price) => {
            const itemPrice = price;
            cy.log('Price: ', itemPrice);

            cy.url().then(url => {
                cy.log('Current URL:', url);
                const linkValue = url;
                productDetails.push({website: 'Apple Store', product: 'iPhone 15 Pro 256GB', price: itemPrice, link: linkValue});
                localStorage.setItem('productDetails', JSON.stringify(productDetails));
                cy.log('Product Details: ', productDetails);
            });
        });
        //productDetails.push({ website: 'Apple Store', product: 'iPhone 15 Pro 256GB', price: 'itemPrice', link: 'linkValue' });
    });

    it('Print the product details array', () => {
        // Log the product details array
        for (let i = 0; i < productDetails.length; i++) {
            cy.log('Product Details: ' + JSON.stringify(productDetails[i]));
        }
    });
});

Log from Cypress

I am expecting the result as above.

Enable/disable one formControl on the basis of another

I want to enable disable one formControl on the basis of another, how to achieve that?

I have tried using .enable() and .disable functions on my formControls by default and is not working. Would like some suggestions on how to proceed, below are the specifics

const numberOfQuestionsRequired = this.securityQuestionSetup.get('numberOfQuestionsRequiredToSetupProfile')?.value;

if (numberOfQuestionsRequired != null && numberOfQuestionsRequired !== '') {
  const controlsToDisable = ['numberOfCharToSaveAnswer', 'questionsRequiredForVerification', 'incorrectAttemptsBeforeAccountLockout'];

  controlsToDisable.forEach(controlName => {
    this.securityQuestionSetup.get(controlName)?.disable();
  });
} else {
  const controlsToEnable = ['numberOfCharToSaveAnswer', 'questionsRequiredForVerification', 'incorrectAttemptsBeforeAccountLockout'];

  controlsToEnable.forEach(controlName => {
    this.securityQuestionSetup.get(controlName)?.enable();
  });
}

and then called this method in ngOnInit()

Average JavaScript Array Json

i have a problem.
I have data that I retrieve that is present in an array. I stringified it to create a JSON object.

My goal is to retrieve the responses that have the same id and average the climbs, descents and occupations to display them in a table.

I do not know if my method is good and if I should not remain in a painting?

`

    "responses": [{
            "response_id": 1,
            "occupation": 10,
            "noShow": false,
            "montee": 10,
            "descente": 0,
        }, {
            "response_id": 2
            "occupation": 10,
            "noShow": false,
            "montee": 10,
            "descente": 0
        }, {
            "response_id": 1,
            "occupation": 10,
            "noShow": false,
            "montee": 10,
            "descente": 0
        }, {
            "response_id": 2,
            "occupation": 10,
            "noShow": false,
            "montee": 10,
            "descente": 0
        }
    ],
    "date": "2024-02-18T23:00:00.000Z",
    "type": "type"
}

]`

I tried this

let filtered = responses.map(value => value.stop).filter(stop => stop.stop.montee =! null)
filtered.filter((r, c) => r + c.montee, 0) / filteredData.length;)

but it’s not working and i think it will not be good for what i want..

NestJs entity non existing column

In nestjs is it possible to add a non existing column in entity? I need this entry because I have a select with like

"attributes": [
                {
                    "AttributeId": 8913,
                    "InnerAttribute": {
                        "value": "201820019"

I want to put the value outside of innerAttribute I want my result to look like

"attributes": [
                {
                    "AttributeId": 8913,
                    "value": "201820019"

My attribute is looking like

record.attributes = this.Attributes;

and this.billerAttributes is Attributes: Attributes[];

I was thinking if it is possible to add

@Column()
value: number | null;

in entity Attributes but I always get error: QueryFailedError: Error: Invalid column name 'value'.

What is a much better approach for this scenario?

Why isn’t my button changing from “1” to “X”?

I am developing a small tic tac toe project to further my knowledge in javascript. If someone could take a look and figure out why my button text is not changing from 1 to X that would be greatly appreciated. The console says it can not set properties of null. I am still new and don’t really understand what that means yet. I would assume it can’t change the property because it can’t detect anything.

function changeX(buttonType){
    document.querySelector(buttonType).value = "X";
}
body {
    margin: 0;
}

#header {
    background-color: black;
    color: white;
    font-size: 40px;
    height: 50px;
    text-align: center;
}

.container1 {
    margin: 200px auto;
    justify-content: center;
    display: flex;
    flex-wrap: wrap;
    width: 450px;
}

.but1 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: none;
    border-left: none;
    border-right: 1px solid black;
    border-bottom: 1px solid black;
}

.but1:hover {
    background-color: rgb(245, 245, 245);
}

.but2 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: none;
    border-left: 1px solid black;
    border-right: 1px solid black;
    border-bottom: 1px solid black;
}

.but2:hover {
    background-color: rgb(245, 245, 245);
}

.but3 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: none;
    border-left: 1px solid black;
    border-right: none;
    border-bottom: 1px solid black;
}

.but3:hover {
    background-color: rgb(245, 245, 245);
}

.but4 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: 1px solid black;
    border-left: none;
    border-right: 1px solid black;
    border-bottom: 1px solid black;
}

.but4:hover {
    background-color: rgb(245, 245, 245);
}

.but5 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: 1px solid black;
    border-left: 1px solid black;
    border-right: 1px solid black;
    border-bottom: 1px solid black;
}

.but5:hover {
    background-color: rgb(245, 245, 245);
}

.but6 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: 1px solid black;
    border-left: 1px solid black;
    border-right: none;
    border-bottom: 1px solid black;
}

.but6:hover {
    background-color: rgb(245, 245, 245);
}

.but7 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: 1px solid black;
    border-left: none;
    border-right: 1px solid black;
    border-bottom: none;
}

.but7:hover {
    background-color: rgb(245, 245, 245);
}

.but8 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: 1px solid black;
    border-left: 1px solid black;
    border-right: 1px solid black;
    border-bottom: none;
}

.but8:hover {
    background-color: rgb(245, 245, 245);
}

.but9 {
    font-size: 40px;
    height: 150px;
    width: 150px;
    background-color: transparent;
    border-top: 1px solid black;
    border-left: 1px solid black;
    border-right: none;
    border-bottom: none;
}

.but9:hover {
    background-color: rgb(245, 245, 245);
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Tic Tac Toe Project</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <section>
            <header id="header">
                Tic Tac Toe
            </header>
        </section>
        <section>
            <div class="container1">
                <button type="button" class="but1" onclick="changeX('.but1')">1</button>
                <button type="button" class="but2">2</button>
                <button type="button" class="but3">3</button>
                <button type="button" class="but4">4</button>
                <button type="button" class="but5">5</button>
                <button type="button" class="but6">6</button>
                <button type="button" class="but7">7</button>
                <button type="button" class="but8">8</button>
                <button type="button" class="but9">9</button>
            </div>
        </section>
        <script src="board.js"></script>
    </body>
</html>