How to detect change in dynamic objects property?

I have 5 dynamic objects out of those 5, I am referring to only 2 here:

  1. objCache.tab1.page1.status: when cache enable from tab
  2. objCache.page1.status: when cache enable from page

In my html and .ts file, I will use one of the above objects dynamically based on my cache level.

I am passing status as input parameter “receivedStatus” to my child component as below, where right side value (xyz…) will be either from object 1 or object 2 from above 2 dynamic objects based on cache level. I don’t want to use if or switch condition in html for dynamic objects.

<child-component [receivedStatus]="xyz..."></child-component>

As in above syntax the right hand side assigned value is dynamic, child component input parameter don’t detect value change event.

Is there any other way to track status change event only when status changed, I don’t want any function which repeatedly call in DOM, it should call only when dynamic object status value got changed.

Supabase Password reset by link

I am making a site for resetting password using supabase and flutter app. The user enters his email and presses send reset link

try {

              await supabase.auth.resetPasswordForEmail(
                email,
                redirectTo: 'https://snapchatpages.github.io/changepassword/' );

The issue is what I understand is that a #_token_hash is required, but supabse sends a =code? in the url which is not enough to verify and change user password. what do i need to do or change?

html file:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Reset Password</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 400px;
      margin: 50px auto;
      padding: 20px;
      text-align: center;
      border: 1px solid #ddd;
      border-radius: 8px;
    }

    input {
      width: 90%;
      padding: 10px;
      margin: 10px 0;
      font-size: 16px;
    }

    button {
      padding: 10px 20px;
      font-size: 16px;
      cursor: pointer;
    }

    .error-message {
      color: #d00;
      margin-top: 10px;
    }

    .success-message {
      color: #080;
      margin-top: 10px;
    }

    #loading-message {
      color: #555;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
  <h2>Reset Your Password</h2>

  <div id="loading-message">Loading, please wait...</div>

  <form id="password-form" style="display: none;">
    <input type="password" id="new-password" placeholder="New Password" required>
    <input type="password" id="confirm-password" placeholder="Confirm Password" required>
    <button type="submit" id="update-password-btn">Save New Password</button>
  </form>

  <div id="message"></div>

  <!-- Load Supabase -->
  <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
  <!-- Your custom script -->
  <script src="script.js"></script>
</body>
</html>

js file


// Supabase configuration
const supabaseUrl = 'my-actual-url';
const supabaseAnonKey = 'my-actual-annonkey';

const SupabaseLoad = supabase.createClient(supabaseUrl, supabaseAnonKey);

document.addEventListener('DOMContentLoaded', () => {
    const newPasswordInput = document.getElementById('new-password');
    const confirmPasswordInput = document.getElementById('confirm-password');
    const updateButton = document.getElementById('update-password-btn');
    const messageDiv = document.getElementById('message');
    const passwordForm = document.getElementById('password-form');
    const loadingMessage = document.getElementById('loading-message');

    // Function to display messages to the user
    function showMessage(text, isError) {
        messageDiv.textContent = text;
        messageDiv.className = isError ? 'error-message' : 'success-message';
    }

    // --- FIXED: Handle Supabase recovery code from query param ---
    const queryParams = new URLSearchParams(window.location.search);
    const code = queryParams.get('code');
    const emailParam = queryParams.get('email');
    const email = emailParam ? decodeURIComponent(emailParam) : null;

    if (code && email) {
        SupabaseLoad.auth.verifyOtp({
            type: 'recovery',
            token: code,
            email: email
        }).then(({ data, error }) => {
            if (error) {
                console.error('Error verifying recovery code:', error);
                showMessage('Invalid or expired reset link.', true);
            } else {
                console.log('Session set via recovery code:', data);
                window.history.replaceState({}, document.title, window.location.pathname);
            }
        });
    } else {
        loadingMessage.style.display = 'none';
        showMessage('Missing code or email in the reset link.', true);
    }

    // --- Rely on Supabase's automatic session restoration OR the manual set session ---
    SupabaseLoad.auth.onAuthStateChange((event, session) => {
        console.log('Auth state changed:', event);
        if (session) {
            // A session was found. The user is authenticated.
            console.log('Session restored from recovery code:', session);
            loadingMessage.style.display = 'none'; // Hide the loading message
            passwordForm.style.display = 'block'; // Show the password form
            showMessage('Session established. Please enter your new password.', false);
        } else if (event === 'SIGNED_OUT') {
            // User signed out, hide the form
            loadingMessage.style.display = 'none';
            passwordForm.style.display = 'none';
            showMessage('Your session has expired or you have signed out. Please use a valid password reset link.', true);
        } else if (event === 'INITIAL_SESSION') {
            // This event fires on page load if no session is found.
            loadingMessage.style.display = 'none';
            passwordForm.style.display = 'none';
            showMessage('No session found. Please use the complete link from your password reset email.', true);
        }
    });

    // --- Handle form submission ---
    if (updateButton) {
        updateButton.addEventListener('click', async (e) => {
            e.preventDefault();

            const newPassword = newPasswordInput.value;
            const confirmPassword = confirmPasswordInput.value;

            if (newPassword.length < 6) {
                showMessage('Password must be at least 6 characters long.', true);
                return;
            }

            if (newPassword !== confirmPassword) {
                showMessage('Passwords do not match.', true);
                return;
            }

            try {
                const { data, error } = await SupabaseLoad.auth.updateUser({ password: newPassword });

                if (error) {
                    console.error('Password update error:', error);
                    showMessage(`Password update failed: ${error.message}`, true);
                } else {
                    console.log('Password updated successfully:', data);
                    showMessage('Your password has been updated successfully! You can now close this page.', false);
                    if (updateButton) updateButton.disabled = true;
                }
            } catch (err) {
                console.error('An unexpected error occurred:', err);
                showMessage('An unexpected error occurred. Please try again.', true);
            }
        });
    }
});

Is there a way to refresh all =AI() functions in a Google Sheet using Apps Script, without manually clicking the “Generate and insert” button?

does anyone know if there’s a way or workaround to refresh all =AI() functions in a Google Sheet using Apps Script, without manually clicking the “Generate and insert” button each time?

I have a sheet with many =AI() calls, and I’d like to automate the refresh—ideally by adding a button that triggers a script to refresh all AI outputs at once. I tried using SpreadsheetApp.flush() in Apps Script, but it didn’t work. Has anyone found a reliable trick or workaround to achieve this?

Here is the code I used ChatGPT to write but it didn’t work

function refreshAIinUseCaseLog() {
  const ss   = SpreadsheetApp.getActive();
  const sheet = ss.getSheetByName('Use Cases Log');
  if (!sheet) { SpreadsheetApp.getUi().alert('Sheet not found'); return; }

  const START_ROW = 2;
  const COLS = [11, 12];   // K = 11, L = 12
  const last = sheet.getLastRow();

  COLS.forEach(col => {
    const rng = sheet.getRange(START_ROW, col, last - START_ROW + 1, 1);
    const formulas = rng.getFormulas();

    for (let r = 0; r < formulas.length; r++) {
      const f = formulas[r][0];
      if (f && f.startsWith('=AI(')) {
        const cell = sheet.getRange(START_ROW + r, col);
        cell.setFormula('');            // 1) clear
        Utilities.sleep(150);           // small delay
        cell.setFormula(f);             // 2) re-apply
      }
    }
  });

  SpreadsheetApp.flush();               // forces Sheets to recalc now
  SpreadsheetApp.getUi().alert('AI cells re-queued for refresh.nGive Gemini a few seconds to fill them.');
}

Supabase Reset Password Site

I want to make an html and js files to create a reset password with supabase. I uploaded the index.html and script.js and css file to github and added the github url page to supaabse and inside my app, when the user enters their email and press send reset link, a link is sent to them vis email and when pressed it opens the correct site. So its fine. The issue is that i get error: Uncaught ReferenceError: Supabase is not defined. I tried with Gemini to fix it but it still persists. I just want a simple working code that gets the job done. Thank you

Index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
</head>
<body>
    <div class="container">
        <div class="app-bar">
            <h1>Set New Password</h1>
        </div>
        <div class="content">
            <div class="input-group">
                <input type="password" id="newPassword" placeholder="New Password">
                <span class="icon">&#128274;</span> </div>
            <div class="input-group">
                <input type="password" id="confirmPassword" placeholder="Confirm Password">
                <span class="icon">&#128274;</span> </div>
            <div class="button-container">
                <button id="savePasswordBtn" class="custom-button">
                    Save Password
                </button>
                <div id="loadingIndicator" class="loading-spinner" style="display: none;"></div>
            </div>
            <div id="message" class="message"></div>
        </div>
    </div>

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

style.css

    font-family: sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    margin: 0;
    background-color: #f0f2f5;
}

.container {
    background-color: #ffffff;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    max-width: 400px;
    width: 90%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.app-bar {
    background-color: #2c92ff; /* Corresponds to your Flutter primary color */
    color: white;
    padding: 20px;
    text-align: center;
    font-weight: bold;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.app-bar h1 {
    margin: 0;
    font-size: 24px;
}

.content {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 16px; /* Spacing between input fields and button */
}

.input-group {
    position: relative;
    width: 100%;
}

.input-group input {
    width: calc(100% - 40px); /* Adjust for icon */
    padding: 15px 15px 15px 45px; /* Left padding for icon */
    border: none;
    border-radius: 10px;
    background-color: #e0e0e0; /* Corresponds to Colors.grey[200] */
    font-size: 16px;
    box-sizing: border-box; /* Include padding in width */
}

.input-group input::placeholder {
    color: #888;
}

.input-group .icon {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: #666;
}

.button-container {
    margin-top: 20px; /* Spacing above the button */
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 58px; /* To prevent layout shift when loading spinner appears */
}

.custom-button {
    width: 100%;
    padding: 16px 0;
    background-color: #2c92ff; /* Your button background color */
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 20px;
    font-weight: bold;
    cursor: pointer;
    box-shadow: 0 5px 0 #0067d6; /* Your button shadow color */
    transition: all 0.05s ease;
    box-sizing: border-box;
}

.custom-button:active {
    transform: translateY(2px);
    box-shadow: 0 3px 0 #0067d6; /* Smaller shadow when pressed */
}

.loading-spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #2c92ff;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.message {
    margin-top: 10px;
    padding: 10px;
    border-radius: 5px;
    text-align: center;
    font-weight: bold;
    display: none; /* Initially hidden */
}

.message.error {
    background-color: #ffe0e0;
    color: #d32f2f;
}

.message.success {
    background-color: #e8f5e9;
    color: #388e3c;
}

script.js


// Initialize Supabase client
// ENSURE these URL and ANON KEY are correct for YOUR Supabase project.
const supabaseUrl = 'i have my actual project url here';
const supabaseAnonKey = 'i have my actual annon key here';

// This event listener ensures that the DOM is fully loaded and parsed
// before any of your JavaScript code that interacts with it is executed.
document.addEventListener('DOMContentLoaded', () => {
    // This line will now only execute AFTER the Supabase CDN script has loaded and defined 'Supabase'.
    const supabase = Supabase.createClient(supabaseUrl, supabaseAnonKey);

    // Get references to all HTML elements
    const newPasswordInput = document.getElementById('newPassword');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    const savePasswordBtn = document.getElementById('savePasswordBtn');
    const loadingIndicator = document.getElementById('loadingIndicator');
    const messageDisplay = document.getElementById('message');

    // Helper function to show messages
    function showMessage(message, isError = true) {
        messageDisplay.textContent = message;
        messageDisplay.className = 'message'; // Reset classes
        if (isError) {
            messageDisplay.classList.add('error');
        } else {
            messageDisplay.classList.add('success');
        }
        messageDisplay.style.display = 'block'; // Make sure it's visible
    }

    // Function to handle password reset
    async function handleResetPassword() {
        const newPassword = newPasswordInput.value;
        const confirmPassword = confirmPasswordInput.value;

        // Clear previous messages
        messageDisplay.style.display = 'none';
        messageDisplay.textContent = '';

        // Basic validation
        if (!newPassword || !confirmPassword) {
            showMessage('Please fill in both password fields.', true);
            return;
        }

        if (newPassword !== confirmPassword) {
            showMessage('Passwords do not match.', true);
            return;
        }

        if (newPassword.length < 6) {
            showMessage('Password must be at least 6 characters long.', true);
            return;
        }

        // Show loading indicator and hide button
        savePasswordBtn.style.display = 'none';
        loadingIndicator.style.display = 'block';

        try {
            // The `updateUser` method automatically uses the access_token from the URL.
            const { data, error } = await supabase.auth.updateUser({
                password: newPassword
            });

            if (error) {
                console.error('Supabase update error:', error); // Log full error for debugging
                showMessage(`Error updating password: ${error.message}`, true);
            } else if (data.user) {
                showMessage('Password updated successfully! You can now log in.', false);
                console.log('Password updated successfully for user:', data.user); // Log success
                // Optionally, redirect to a login page after success
                // setTimeout(() => {
                //     window.location.href = '/login.html'; // Adjust to your login page path
                // }, 3000);
            } else {
                // This is a fallback for an unexpected API response
                showMessage('Failed to update password. Please try again.', true);
                console.warn('Supabase update failed, but no specific error and no user data.', data);
            }
        } catch (e) {
            console.error('An unexpected error occurred:', e); // Catch any other unexpected errors
            showMessage(`An unexpected error occurred: ${e.message}`, true);
        } finally {
            // Hide loading indicator, show button
            savePasswordBtn.style.display = 'block';
            loadingIndicator.style.display = 'none';
            // Clear password fields for security
            newPasswordInput.value = '';
            confirmPasswordInput.value = '';
        }
    }

    // Attach event listener to the button
    savePasswordBtn.addEventListener('click', handleResetPassword);

    // Initial check for hash fragment (access token) when page loads.
    const urlParams = new URLSearchParams(window.location.hash.substring(1));
    const accessToken = urlParams.get('access_token');
    const refreshToken = urlParams.get('refresh_token');

    if (accessToken && refreshToken) {
        console.log('Access token and refresh token found in URL hash. Supabase will use this to update the user.');
    } else {
        console.warn('No access_token or refresh_token found in URL hash. Please use the link from your password reset email to access this page.');
        // Optionally show a message to guide the user
        // showMessage('Please use the link from your password reset email to set a new password.', true);
    }
});

Bootstrap dropup in a React card component causes auto-scroll to previously opened dropup

I’m working on a React project where I have a reusable card component that appears multiple times on a single page. Each card has a Bootstrap dropup used to select the file that the user wishes to download (SVG or PNG).

The Problem:

When I open a dropup in one card (say, card #1), it works fine.

But when I scroll down and open the dropup in a different card (say, card #20), the page automatically scrolls back up to card #1.

Similarly, if I open the dropup in card #10, it scrolls to card #20. Then card #40 scrolls to card #10. It seems to scroll to whichever card had the previous open dropup.

What I suspect:

When I open any dropup, the previous one closes, which results in re-rendering of the previous component, hence the focus is shifted to that component. (I could be dead wrong here, I’m still a beginner)

Here’s the code for my dropup:

<div className="dropup dropup-center">
  <button
    className="card-btn-custom dropdown-toggle"
    type="button"
    data-bs-toggle="dropdown"
    aria-expanded="false"
    title="Download"
  >
    <i className="bi bi-download"></i>
  </button>
  <ul className="dropdown-menu">
    <li>
      <button
        className="dropdown-item text-center"
        onClick={() => handleDownload("svg")}
      >Download SVG</button>
    </li>
    <li>
      <button
        className="dropdown-item text-center"
        onClick={() => handleDownload("png")}
      >Download PNG</button>
    </li>
  </ul>
</div>

How to extract JSONB array values from a Supabase Postgres table and insert them into another table in React Native?

I’m working on a React Native app with Supabase as my backend.

My products table has a style_tags column in JSONB array format, for example:

[
  { "tag": "streetwear", "weight": 0.8 },
  { "tag": "summer", "weight": 0.5 }
]

I want to extract each object in the array, and insert its tag field into the style_tags column of another table called user_style_tags_scores, and its weight field into that table’s score column.

What’s the way to fetch the JSONB array and insert each tag-weight pair into another table in Supabase?

I tried fetching the data using:

const { data: productData } = await supabase
  .from('products')
  .select('style_tags')
  .eq('id', id);

but I’m not sure how to loop through the JSONB array and then insert each of its elements into the user_style_tags_scores with the right columns (style_tags and scores)

How to implement drag-and-drop functionality in MultiGrid from react-virtualized?

I’m using the MultiGrid component from the react-virtualized package to render a complex, scrollable table/grid layout that supports fixed columns and rows. It works great for performance, but I now need to add drag-and-drop support for rearranging/moving certain rows or cells (e.g., activities within categories in a Gantt chart-like structure).

My Use Case:

  • I’m rendering nested rows such as: Category → Sub-category → Activities and also Category → Activities

  • Each row has a unique key like: category_157_activity_539

  • I want to drag and reorder activities within their parent container
    (either a category or sub-category) also order categories and sub-categories

  • I want to drag and move any item into applicable context. ex: moving activities from a category into another category.

  • Bellow is a screenshot from the app that shows the structure
    a screenshot from the app that shows the structure of the gantt chart

Challenges:

  • Since MultiGrid renders rows and columns virtually, standard drag-and-drop libraries like react-dnd or react-beautiful-dnd don’t seem to work out of the box.
  • Each cell is rendered independently via a cellRenderer, and DOM elements are frequently unmounted/remounted.
  • I can’t easily get the DOM structure of rows or cells to attach drag handles or drop zones.

Questions:

  1. Is there a recommended way to add drag-and-drop support to a MultiGrid-based layout?
  2. Has anyone successfully integrated react-beautiful-dnd or dnd-kit with react-virtualized?
  3. Should I switch to another virtualized grid solution (like react-window + react-virtual) that works better with DnD?

Any tips, workarounds, or code examples would be greatly appreciated!

Sending form to backend through post method but req.body is undefines

I am using fetch post method to post form data to backend but what i am getting on req.body is undefined

I think body parser is not working perfectly

const onsubmit = async (data) =>{
    let r = await fetch('http://localhost:3000/' , {method: "POST" , body: JSON.stringify(data)})
    let form = await r.text()
   }
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';

const app = express()
const port = 3000;
app.use(cors());
app.use(bodyParser.json());

app.get('/' , (req , res)=>{
    res.send("hello world")
})

app.post('/' , (req , res)=>{
  console.log(req.body)
  res.send("data recived!")
})

app.listen(port , () => {
  console.log("Server running");
});

what i am getting in the body is this
body: undefined

PHP inside Javascript is called only once, how to fix it? [duplicate]

I created the following code to call some php code (here write to file) when a button is pressed, but the code is getting called only once, when the page is refreshed (the file is only written once, not getting written when button clicked). Can someone help me?

<! doctype html >
<html>
<head>
<meta charset="UTF-8" />

</head>
<body>


<button id="submit" style='width:200px'> Submit </button>


<script>

var add = document.getElementById("submit");
add.addEventListener("click", function(){
    console.log("clicked");
    callphp();
});


function callphp(){

    "<?php
        $myfile = fopen("ctest.txt", "a") or die("Unable to open file!");
    
        $txt = "testn";
        fwrite($myfile, $txt);
        fclose($myfile);
    ?>";

    console.log("test");

}     


callphp();
callphp();

</script>

</body>

</html>

Is that a good idea to make an e-card like this, which loops 1000 times to create canvas-like texture in the 2d canvas? [closed]

Is it a good practice to create a for loop to create canvas-like texture within 2d canvas, which loops at least 1000 times. I was thinking of converting this into an e-card. Do you think it would be practical to make this into a greeting which can be sent using further JavaScript. Please, advise. Here’s my code, with the output:

let canvas, ctx, h, w;

function init() {
  canvas = document.getElementById("digiCanvas");
  canvas.style.background = "olive";
  ctx = canvas.getContext("2d");
  w = canvas.width;
  h = canvas.height;

  for (let i = 0; i < 1000; i++) {
    var x = Math.random() * w,
      y = Math.random() * h,
      width = Math.random() * w,
      height = Math.random() * h;

    ctx.strokeStyle = "#4d6e45";
    ctx.strokeRect(x, y, width, height);
    ctx.strokeStyle = "#e6e200";
    ctx.strokeRect(x, y, width, height);

    var x = Math.random() * w,
      y = Math.random() * h,
      width = Math.random() * w,
      height = Math.random() * h;

    ctx.strokeStyle = "#4d6e45";
    ctx.strokeRect(x, y, width, height);
    ctx.strokeStyle = "gold";
  }

  const img = document.createElement("img");

  img.src = "https://i.ibb.co/spMXMkg5/Pngtree-watercolor-of-pink-hibiscus-flowers-13017491.png";
  const pat = ctx.createPattern(img, "no-repeat");

  ctx.rect(6, 6, 297, 297);
  ctx.fillStyle = pat;
  ctx.fill();
  ctx.fillStyle = "gold";
  ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
  ctx.fillRect(18, 320, 272, 28);
  ctx.fillStyle = "navy";
  ctx.font = "21px Papyrus";
  ctx.fillText(" ݁ .᪥.Hibiscus rosa-sinensis .᪥. ݁", 18, 339);
}
html {
  display: flex;
  justify-content: center;
  align-items: center;
}

html>* body {
  background: #eedc82;
}

canvas {
  border: 1px dashed #c94484;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Canvas</title>
</head>

<body onload=init();>
  <canvas id="digiCanvas" width="306" height =360>
  Your browser does not support the canvas tag.</canvas>
</body>

</html>

I could achieve the desired canvasized texture, do you think is it a good idea to turn it into an e-card?

MediaSource reinitialization issue in audio buffer

I am providing the binary data and on frontend it is making it as a buffer and passing it to the MediaSoruce.addEventListerer

it is getting the data, but it is not appending it as I cannot hear to the audio when run again. On the 1st try it is working fine but the 2nd time when I run, it does not give any type of audio but it is getting the data.

private reinitializeMediaSource(): void {
    if (!this.audioPlayer) return;
    if (this.mediaSource) {
      URL.revokeObjectURL(this.audioPlayer.nativeElement.src);
    }
    this.mediaSource = new MediaSource();
    this.audioPlayer.nativeElement.src = URL.createObjectURL(this.mediaSource);

    this.mediaSource.addEventListener('sourceopen', () => {
      try {
        this.sourceBuffer = this.mediaSource!.addSourceBuffer('audio/webm; codecs=opus');
        this.sourceBufferReady = true;
        this.sourceBuffer.addEventListener('updateend', () => this.feedAudioQueue());
        this.feedAudioQueue();
      } catch (error) {
        console.error('Error adding SourceBuffer:', error);
      }
    });
  }

why does this happen (JavaScript help)? [duplicate]

i’m trying to swap variables after an array destruction but when i use the code

let [a,n] = restaurant.starterMenu
console.log(a)
console.log(n)
let c = [n,a]
// [a,n] = c

let v = {
  names : ['apple','orange','tomato'],

}

let [m,d] = v.names 
[m,d] = [d,m]

it shows me
script.js:62 Uncaught ReferenceError: Cannot access ‘m’ before initialization
but when using the semicolon even just at the end of the line before swapping like that it works properly

let [a,n] = restaurant.starterMenu
console.log(a)
console.log(n)
let c = [n,a]
// [a,n] = c

let v = {
  names : ['apple','orange','tomato'],

}

let [m,d] = v.names ;
[m,d] = [d,m]

what could be the potential error?

Why is “groupBy” a static method and not on the Array Prototype?

The MDN docs state:

Note: In some versions of some browsers, this method was implemented as the method Array.prototype.group(). Due to web compatibility issues, it is now implemented as a static method.

However, similar issues arose with flat (see SmooshGate) but this was resolved by renaming the term to flatten. Why didn’t TC39 take the same approach with groupBy and find a non-conflicting name?

aws ec2 cors err when trying to connnect frontend(vercel ) backend ec2?


const allowedOrigins = [ 

  // "http://localhost:3000",
  "https://neuera.in", 
  "https://www.neuera.in", 
];

const corsOptions = {
  origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
    // Allow requests with no origin (mobile apps, Postman, server-to-server)
    if (!origin) {
      console.log("✅ No origin header - allowing request");
      return callback(null, true);
    }

    if (allowedOrigins.includes(origin)) {
      console.log(`✅ CORS allowed for origin: ${origin}`);
      callback(null, true);
    } else {
      console.warn(`❌ CORS blocked origin: ${origin}`);
      callback(new Error(`CORS policy violation: Origin ${origin} not allowed`));
    }
  },
  credentials: true,
  optionsSuccessStatus: 200,
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: [
    'Origin',
    'X-Requested-With',
    'Content-Type',
    'Accept',
    'Authorization',
    'Cache-Control',
    'X-API-Key',
    'Access-Control-Allow-Headers',
    'Access-Control-Allow-Origin'
  ],
  // Explicitly set headers for debugging
  preflightContinue: false
};

// Apply CORS BEFORE other middleware
app.use(cors(corsOptions));

// Security headers (configure after CORS)
app.use(helmet({
  crossOriginResourcePolicy: { policy: "cross-origin" },
  // Disable some helmet defaults that might interfere
  contentSecurityPolicy: false,
  crossOriginEmbedderPolicy: false
}));

frontend:-rtqk

export const api = createApi({
  baseQuery: customBaseQuery,
  reducerPath: "api",
  tagTypes: ["Projects", "Tasks", "Users", "Teams"],
  endpoints: (build) => ({
    getAuthUser: build.query({
      queryFn: async (_, _queryApi, _extraoptions, fetchWithBQ) => {
        try {
          const user = await getCurrentUser();
          const session = await fetchAuthSession();
          if (!session) {
            // Format errors according to RTK Query expectations
            return {
              error: {
                status: 401,
                data: 'No session found'
              } as FetchBaseQueryError,
            };
          }
          const { userSub } = session;
          // const { accessToken } = session.tokens ?? {};

          const userDetailsResponse = await fetchWithBQ(`users/${userSub}`);
          const userDetails = userDetailsResponse.data as User;
          if (userDetailsResponse.error) {
            return { error: userDetailsResponse.error };
          }


          return { data: { user, userSub, userDetails } };
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : "Could not fetch user data";
          return {
            error: {
              status: 'CUSTOM_ERROR',
              data: errorMessage
            } as FetchBaseQueryError,
          };
        }
      },
    }),

im trying to host my frontend on vercel(nextjs) and backend(node+ex) on aws ec2 but im keept getting this cors err , i have done this but none if this works any idea , i have created api.neuera.in for api calls but still nothing working,
Do I need to add something to the EC2 instance like a proxy or Nginx rule, even though i hvae nginx setup on ec2?
i want to connnect my frontend and backend?

Change tooltip type when moving between grids in chart

I have a graph with multiple y-axes/x-axes, and currently, ECharts does not allow for different tooltip types between grids. I have three y-axes/grids within one graph, and for the first two, I would like to have a tooltip set as trigger: 'axis', and for the third one, trigger: 'item'.

I wanted to implement a solution following this example where I would dynamicly change tootlip trigger caching mouse move event. The problem with this solution is that mouseup or mousemove are only triggered when the mouse touches the object in the graph (line or dot), but I would like the solution where the event would already trigger when the mouse moves to the third graph area or goes back to the area of the second graph/grid. I didn’t find any other suitable mouse event that would cover that.

Is there any solution to change the tooltip trigger when going between different graph areas/grids in the charts?