AJAX is not redirecting as expected

Im trying to develop a very basic webserver for self-learning with some basic functionalities.

i encountered a problem where im sending from the browser a POST request with the nessesery data:

POST /login/login_page.html HTTP/1.1
Host: 192.168.1.2:8888
Connection: keep-alive
Content-Length: 39
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36
Accept: */*
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Origin: http://192.168.1.2:8888
Referer: http://192.168.1.2:8888/login/login_page.html
Accept-Encoding: gzip, deflate
Accept-Language: he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7
Cookie: session=9NspKVEk13P+Nyjdzscv0A==

username=abc&password=123&action=signin

then i expect the server to respond with a 302 status code and send the location of the redirection, seem fine:

HTTP/1.1 302 Found
Content-Type: text/html
Server: MyCustomPythonServer/1.0
Strict-Transport-Security: max-age=10
Set-Cookie: session=aHj3PHTo+Npx8BuOnSyIqQ==; HttpOnly; Secure; SameSite=None
Location: http://192.168.1.2:8888/posts.html

As expected the browser recives the respones and sends a request for the wanted location:

GET /posts.html HTTP/1.1
Host: 192.168.1.2:8888
Connection: keep-alive
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36
Accept: */*
Referer: http://192.168.1.2:8888/login/login_page.html
Accept-Encoding: gzip, deflate
Accept-Language: he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7

The server recives it and handeling is as needed and responding with 200 and the page that needed to be loaded in the browser (i didnt add the entire body, instead i added 2 lines from it):

HTTP/1.1 200 OK
Content-Type: text/html
Server: MyCustomPythonServer/1.0
Strict-Transport-Security: max-age=10

<!DOCTYPE html>
<html lang="en">

This is my ajax code that sohuld handle the redirection:

$.ajax({
    type: "POST",
    url: url,
    data: form.serialize(),
    success: function (response, status, xhr) {
        // Check for a 302 redirect
        if (xhr.status === 302) {
            let redirectUrl = xhr.getResponseHeader('Location');
            if (redirectUrl) {
                window.location.href = redirectUrl;
            }
        }
        else {
            $("#message").html("<p style='color: green;'>Form submitted successfully!</p>");
        }
    },
    statusCode: {
        401: function () {
            $("#message").html("<p style='color: red;'>Unauthorized.<br>Please check your credentials.</p>");
        },
        409: function () {
            $("#message").html("<p style='color: orange;'>Username already exists.<br>Please choose a different username.</p>");
        },
        500: function () {
            $("#message").html("<p style='color: orange;'>Internal server error.</p>");
        }
    },
    error: function () {
        $("#message").html("<p style='color: red;'>An unknown error occurred.</p>");
    }
});

In case of a success signup it prints as expected -> ‘Form submitted successfully!’
In case of a failed signup (conflict) it prints as expected -> ‘Username already exists.’ with a 409 statuscode
in case of a success signin it prints -> ‘Form submitted successfully!’ and not to the redirection (in the else statement)
in case of a failed signin it prints -> ‘Unauthorized.’ with a 401 statuscode

im lost, i dont know where to dive to understand the issue in my case.

thanks for any help and for reading.

Trouble importing React components doing multiple import/exports – “Can’t find module”

I’m creating a POC UI library whereby I have say a component file and then also a file to demo the component in context. Think a standalone button, then a component with multiple different iterations of the button (size and colour etc).

I have created the two components in the same folder and then created an index to export them both from.

enter image description here

However, when I am attempting to import the “demo” component into the main app, it’s complaining about Cannot find module './components/form/button' or its corresponding type declarations.
I have checked the paths and they all seem to be correct, so I’m not entirely sure what is going on.

App.tsx

import ButtonDemo from './components/form/button/buttonDemo';

const App = () => (
  <>
    <ButtonDemo />
  </>
);

export default App;

It also seems that I am getting the same warning in the actual index.tsx for the main Button import…

For example, my actual component code uses default exports such as
buttonDemo.tsx

export default () => <div>Hello world</div>

I am then exporting these within the index as:
index.tsx

export {default as Button} from './button';
export {default as ButtonDemo} from './buttonDemo';

Again, these are the correct filepaths.

typoerroe tags.map is not a function

app.post("/api/v1/content", middleware, async (req:Request, res:Response) => {
    const {link,type,tags =[]}:ContentRequestBody =req.body;

    try{
        //@ts-ignore
        const userId = req.userId;

        const tagIds = await Promise.all(
            tags.map(async (tag: string) => {
                // Find or create the tag. If it doesn't exist, create it.
                //@ts-ignore
                const [tagRecord] = await tagsModel.findOrCreate({
                    where: { tag: tag },  // Look for the tag by name
                    defaults: { tag: tag } // If not found, create it with the tag name
                });

                return tagRecord.id; // Return the tag's ID (not name)
            })
        );
        await contentModel.create({
            link,
            type,
            //@ts-ignore
            userId,
            tags:tagIds,
        });
        return res.status(201).json({ message: 'Content created successfully' });
    }catch (error) {
        console.error('Error creating content:', error);
        return res.status(500).json({ error: 'An error occurred while creating content' });
    }

})

using ts express mongooes get isssue get map is not a function i want That user give us tag for storing the information and if the tag is saved in our database they can use it if does not user use it but that tag will store in our takeaways so future customers can use the same tag but I’m getting the issue on tagged map and I do not know what’s the issue I Google not but not getting the result please if anyone can help me

I am expected that my issue get resolved get to know what is the issue what that I make and how can I not repeat it A good description so I cannot do the same issue later

How to change the colors of a Google Sheets chart using an object?

I have some shooting data that looks like the below.

table of shooting data

To understand how many of each shot type we are taking over the course of the season, I used a bar chart using the data from column B.

bar chart displaying counts of each shot type

I want to customize the colors of each bar (shot type) with a specific color such as:

colors = {
  "Shot Type 1": "red",
  "Shot Type 2": "blue",
  ...
}

I have found some answers using Google Scripts (which is fine to use) but they rely on passing the mapping in as a array, which is dictated by the ordering of data. I’d prefer not to rely on that, and rather just rely on the colors object to specify the colors. Additionally to note, there are 9 total shot types and associated colors, and some of those might not have been taken yet, which is another reason why relying on an array to pass in colors would not work I don’t believe.

Can someone assist using Google Sheets native functionality or a Script?

Send JavaScript console.logs from one device to another with VScode Live Server Extension

I’ve got a question. I have a Windows 10 laptop, that is the host of a Visual Studio Code Live server; and a Windows 11 laptop that is a client. Because ‘localhost’ and ‘127.0.0.1’ only work on the host device, I had to use the IP of Win 10 host laptop.

My main question is how to send every console.log() on that guest Windows 11 laptop to the one that hosts the server? Is it possible?

Please note that the console.logs aren’t directly at <script> file, but upon guests’ interaction (In my situation when they submit a form, meaning they have specific information provided). That means it’s not sent in the same time on both computers, like when the content loaded, but rather on their own time.

Does anybody know an answer?

Problem with Infinite scroll and remembering the last position

as you can see in Pinterest or other websites, when you scroll for 2 or 3 pages and you decide to click on a image or product, you will be navigated to another page, then when you press the back button, you will be also navigated to the last page you were, but also to the last position or image or product you have clicked.

i have a shopping website on next.js app router. also i am implementing the infinite scroll. the problem is when i click on a product and then i press back button it will navigate me to the top of the page and also it will not show the products which were fetched, it will try to fetch all of them again. like this is my first time i am visiting the page.

this is my page.js file

import  LoadMore from "@/app/components/loadMore";
import MenuFooter from "@/app/components/menuFooter";


export default async function Home() {
  return (
   <main>
      <LoadMore />
      <MenuFooter></MenuFooter>
   </main>
  );
}

this is my loadMore.js file which is responsible for infinitescroll

"use client";

import { useEffect, useState } from "react";
import { useInView } from "react-intersection-observer";
import Spiner from "./ui/spiner";
import { getAllProducts } from "@/actions/productAction";
import Products from "./products";

export default function LoadMore() {
  const [products, setProducts] = useState([]);
  const [page, setPage] = useState(1);
  const [key, setKey] = useState(2)
  const { ref, inView } = useInView();

  const loadMoreProducts = async () => {
    const nextPage = (page) + 1;
    const newProducts = (await getAllProducts(nextPage)) ?? [];
    setProducts((prevProducts) => [...prevProducts, ...newProducts.items]);
    setPage(newProducts.pageNum);
    setKey(newProducts.pageNum)
  };
  
  useEffect(() => {
    if (inView) {
        loadMoreProducts();
    }
  }, [inView]);

  return (
    <>
      <Products items={products} page={key}/>
      <div
        className="flex justify-center items-center p-4 col-span-1 sm:col-span-2 md:col-span-3"
        ref={ref}
      >
        <Spiner />
      </div>

    </>
  );
}

this is my products.js which is only showing the products

'use client'
import Link from "next/link"
import Image from "next/image"
import { useRouter } from "next/navigation"
import { setRecently } from "@/actions/productAction"
import { convertDigitIn } from "@/helpers/formatter"
import Masonry from 'react-masonry-css';



export default function Products({items, page}){
  const router = useRouter()
    const breakpointColumnsObj = {
        default: 4, // For large screens
        1100: 3,    // Medium screens
        768: 2,     // Tablets
        500: 2,     // Mobile
      };

    return(
        <Masonry
        breakpointCols={breakpointColumnsObj}
        className="flex w-auto"
        columnClassName="grid-column"
      >
        {items.map(item => (
          <div key={item.id} className="p-1">
          <Link
            href={`/shop/product/${item.barCode}/${item.nam_model}`}
          >
                <Image
                src={``}
                className="w-full h-auto object-cover rounded-2xl"
                width={0}
                height={0}
                sizes="100vw"
                onError={(e) => {
                    e.target.id = "/images/10043.webp";
                    e.target.srcset = "/images/10043.webp";
                }}
                />
            </Link>
          </div>
        ))}
      </Masonry>
    )
}

i have tried to get the first and second page (each page is 12 products) and pass it to products without loadmore component, in the page.js file
and the result was really nice, i could turn back to my last clicked or last posotion, but with the loadmore (and i actually need the infinite scroll) i cant achieve that, i think the problem is with the logic of infinite scroll

How to dynamically highlight cricket stadiums on a map and display nearby attractions using JavaScript?

I am building a website that features the top cricket grounds in India along with nearby tourist attractions and hotels. I want to create an interactive map where:

Users can see the locations of the cricket stadiums marked.
Clicking on a stadium displays nearby attractions and accommodations in a side panel.
I am using HTML, CSS, and JavaScript for this project. Could someone guide me on:

The best way to integrate a map (e.g., Google Maps API, Leaflet.js)?
How to dynamically load and display information when a stadium is clicked?
Any code snippets, tutorials, or examples would be greatly appreciated. Thank you!

What I am trying:
I am developing a website to showcase India’s top cricket stadiums, nearby attractions, and accommodations. I want to use a map to:

Display markers for all cricket stadiums.
Show a list of nearby tourist spots and hotels when a stadium marker is clicked.
Currently, I am using [mention any library or framework you’re experimenting with, e.g., Google Maps API or Leaflet.js]. I’ve managed to:

Embed a map and place static markers for the stadiums.
However, I’m stuck on dynamically updating the nearby attractions and accommodations when clicking on a marker. My dataset is in JSON format, and I’m not sure how to integrate it with the map.

What I am expecting:
I would like to achieve the following:

When a user clicks a stadium marker, a side panel or popup should display information about nearby attractions and hotels, fetched dynamically from my JSON dataset.
Smooth transitions or animations between marker clicks and panel updates.
Suggestions for improving performance if I am dealing with multiple markers and datasets.
An example implementation or any step-by-step guidance would be really helpful.

I’m working on a Calendar on js, and I’m stuck with updating the month’s data. It somehow adding new data to previous one instead

First I tried to make one with InnerHTML and it worked just fine, but I have to add Listeners and InnerHTML is not an option now, so I switched to appendChild, and dates update, when you go to the next month collapsed, also I need to update content without destroying it, coz this calendar will be used for booking dates and time

const monthYearElement = document.getElementById('monthYear');
const datesElement = document.getElementById('dates');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');

let currentDate = new Date();


const updateCalendar = () => {
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth();

    const firstDay = new Date(currentYear, currentMonth, 0);
    const lastDay = new Date(currentYear, currentMonth + 1, 0);
    const totalDays = lastDay.getDate();
    const firstDayIndex = firstDay.getDay();
    const lastDayIndex = lastDay.getDay();

    const monthYearString = currentDate.toLocaleString('ru-RU', {month: 'long', year: 'numeric'});
    monthYearElement.textContent = monthYearString;

for (let i = firstDayIndex; i > 0; i--) {
        const prevDate = new Date(currentYear, currentMonth, 0 - i + 1);
        let day = document.createElement('div');
        day.classList.add('date');
        day.classList.add('inactive');
        day.textContent = `${prevDate.getDate()}`;
        datesElement.appendChild(day)
    }

    for (let i = 1; i <= totalDays; i++) {
        const date = new Date(currentYear, currentMonth, i);
        let day = document.createElement('div');
        day.classList.add('date');
            if(date === currentDate){
                day.classList.add('today');
            }
        day.textContent = `${i}`;
        datesElement.appendChild(day)

    }

    for (let i = 1; i <= 7 - lastDayIndex; i++) {
        const nextDate = new Date(currentYear, currentMonth + 1, i);
        let day = document.createElement('div');
        day.classList.add('date');
        day.classList.add('inactive');
        day.textContent = `${nextDate.getDate()}`;
        datesElement.appendChild(day)
    }

    let days = document.querySelectorAll('.date');
    let week;
    for (let i = 0; i < days.length; i++) {
      if (i%7 === 0) {
        week = document.createElement('div');
        week.className = "week";
        datesElement.appendChild(week);
      }
      week.appendChild(days[i]);
    }
}
updateCalendar();




**prevBtn.addEventListener('click', () => {
    currentDate.setMonth(currentDate.getMonth() - 1);
    updateCalendar();
})

nextBtn.addEventListener('click', () => {
    currentDate.setMonth(currentDate.getMonth() + 1);
    updateCalendar();
})
**

Also current date class is not working anymore, it literally do nothing with ‘no code problem’ alerts

for (let i = 1; i <= totalDays; i++) {
        const date = new Date(currentYear, currentMonth, i);
        let day = document.createElement('div');
        **day.classList.add('date');
            if(date === currentDate){
                day.classList.add('today');
            }**
        day.textContent = `${i}`;
        datesElement.appendChild(day)

So What I need is:

  1. to show new data with each month(not to add one to another) – update calendar with PrevBtn NextBtn functions, but without destroying content
  2. add ‘today’ class to currentDate div

javascript

Combining the module pattern with prototype assignment

I know there have been a lot of questions about module patterns, prototypical inheritance, ES6 classes, etc with excellent answers. This is not about discussing different patterns or the bad sides of ES6 classes.

My question, to which I couldn’t find a clear answer in the existing questions, is about the difference and pros and cons of two specific approaches.

I like the flexibility that comes with the module pattern and I fully understand the pitfalls, limitations and downsides of relying on the prototype chain (whether or not using the class keyword or traditional function with prototype). However, I want (and sometimes need) the objects that I create to be “identifiable” through instanceof.

I’m aware of two approaches that combine module pattern (and ability to do object composition) while tying the object’s prototype to the function that created it.

Method 1: Like module pattern, but we manually set the prototype of the object returned

function Bar() {
  let privateVar = 1;
  const someMethod = () => {
    // do something
  };

  return Object.setPrototypeOf({ someMethod }, Bar.prototype);
}
const b = new Bar() // can omit new as well
console.log(b, b instanceof Bar); // gets a nice "Bar" name in the console + instanceof true

Method 2: Wrapper class and assigning all methods in the constructor

class Foo {
  constructor() {
    let privateVar = 1
    this.someMethod = () => {
      // do something
    }
  }
}
const f = new Foo() // must call with new
console.log(f, f instanceof Foo); // same as Method 1

Question

Are there any downsides to either approach, is one clearly better or worse. Or are they both bad in the sense that they are violating the expectation that the class or constructor function can be “extended” and one would expect to find the properties/methods on the prototype?

How to place dropdown menu in free jqgrid top toolbar

Bootstrap 5 dropdown menu is placed to free jqgrid toolbar using

$("#list").jqGrid({
  toppager: true,

  colModel: [
    { name: "name", label: "Client", width: 53 },
    {
      name: "invdate",
      label: "Date",
      width: 75,
      align: "center",
      sorttype: "date",
      formatter: "date",
      formatoptions: { newformat: "d-M-Y" },
    },
    { name: "amount", label: "Amount", width: 65, template: "number" },
    { name: "tax", label: "Tax", width: 41, template: "number" },
    { name: "total", label: "Total", width: 51, template: "number" },
    {
      name: "closed",
      label: "Closed",
      width: 59,
      template: "booleanCheckbox",
      firstsortorder: "desc",
    },
    {
      name: "ship_via",
      label: "Shipped via",
      width: 87,
      align: "center",
      formatter: "select",
      formatoptions: { value: "FE:FedEx;TN:TNT;DH:DHL", defaultValue: "DH" },
    },
  ],
  data: [
    { id: "10", invdate: "2015-10-01", name: "test", amount: "" },
    {
      id: "20",
      invdate: "2015-09-01",
      name: "test2",
      amount: "300.00",
      tax: "20.00",
      closed: false,
      ship_via: "FE",
      total: "320.00",
    },
  ],
  guiStyle: "bootstrap4",
  iconSet: "fontAwesome",
  idPrefix: "gb1_",
})

document.querySelector("#list_toppager > div").insertAdjacentHTML(
  "afterend",
  `<div class='dropdown'><button class="btn btn-secondary dropdown-toggle" type="button"
      data-bs-toggle="dropdown" aria-expanded="false">
        Dropdown button
      </button>
      <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Action</a></li>
        <li><a class="dropdown-item" href="#">Another action</a></li>
        <li><a class="dropdown-item" href="#">Something else here</a></li>
      </ul>
    </div>`
)

https://jsfiddle.net/gvna6myp/2/

Clicking in dropdown buttons does not show menu:

enter image description here

It looks like dropdown menu is clipped so that it is not visible outside toolbar div. How to make dropdown menu visible ?

replacing the eval function

Im making a Calculator project, I have made a function which gets the user input inside the input tag and A eval() function that will calculate it and prints it on output tab.
But I want to replace eval(), and want the same funcationality under the input tab.

-> here is my js code-

const userInput= document.getElementById('input');
const userOutput= document.getElementById('output');
const clearbtn= document.getElementById('clear');
const calBtn=document.getElementById('calcBtn')
//selecting all the input btns at all
const btns= document.querySelectorAll('input[type="button"]');

function calc(){
    //looping through each btns
    btns.forEach(button =>{
        button.addEventListener('click',()=>{

            let btnDataType= button.dataset.type;
            if(btnDataType==='number'|| btnDataType==='operator'){
                //appending the value;
                userInput.value+= button.value;
            } 

        })
    })

    //it will clear the input display
    clearbtn.addEventListener('click',()=>{
        userInput.value='';
        userOutput.value='';
    })

    calBtn.addEventListener('click',()=>{
        try{
            console.log("Input value:", userInput.value);
            userOutput.value= eval(userInput.value);
        }
        catch(e){
            userOutput.value='Invalid selection';
        }
        
    });
}
calc();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="style.css" rel="stylesheet">

</head>
<body >
    <!-- header section -->
   <header>
        <nav>
            <a href="">Logo</a>
            <button>contribute here</button>
        </nav>
   </header>

   <!-- main -->
    <main>
        <section>
            <!-- calculator wrapper div -->
            <div>
                <!-- input and output screens -->
                <div>
                    <input type="text" placeholder="Type to Calculate" id="input">
                    <input type="text" placeholder="Output" readonly id="output">
                    <button id="clear">Clear</button>
                </div>

                <!-- wrapper that contains number btns , operators -->
                 <div>

                    <!-- numbers -->
                    <div>
                        <input type="button" value="0" id="0"  data-type="number">
                        <input type="button" value="1" id="1" data-type="number">
                        <input type="button" value="2" id="2" data-type="number">
                        <input type="button" value="3" id="3" data-type="number">
                        <input type="button" value="4" id="4" data-type="number">
                        <input type="button" value="5" id="5" data-type="number"> 
                        <input type="button" value="6" id="6" data-type="number">
                        <input type="button" value="7" id="7" data-type="number">
                        <input type="button" value="8" id="8" data-type="number">
                        <input type="button" value="9" id="9" data-type="number">
                    </div>

                     <!-- operators btns -->

                    <div>
                        <input type="button" value="+" id="+" data-type="operator">
                        <input type="button" value="-" id="-" data-type="operator">
                        <input type="button" value="*" id="*" data-type="operator">
                        <input type="button" value="/" id="/" data-type="operator">
                        <input type="button" value="%" id="%" data-type="operator">
                        <button id="calcBtn">Calculate</button>
                    </div>

                 </div>
            </div>
        </section>
    </main>





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

strong text

i kinnda stuck in logic building , any suggestion will help me.

How to get the value from a proxy object in Vue js

I am trying to return a value from a proxy object but it return undefined.

This is my code

<script setup>
const props = defineProps({status:Object});
    
function getColor(items){
    const currentStatus = props.status;

    const output = currentStatus.filter((item)=>{
            if(items.status === item.status){
                return item
            }
    })

    return output.color;
}

</script>

<template>
    <div class="p-5">
         <v-data-table
             :search="search"
             :headers="headers"
             :items="transactions">
             <template v-slot:[`item.status`]="{item}">
                 <v-chip :color="getColor(item)" variant="elevated" label>{{ item.status }}</v-chip>
             </template>
         </v-data-table>
    </div>
</template> 

this is the snap image of the data am getting after the filter

enter image description here

I hope someone will point out what missing here.

thanks

Determine the specific dynamically-added inline script element that caused an Uncaught Error (via `window.addEventListener(‘error’, …)`)

I’m building a dev tool that captures uncaught errors with window.addEventListener('error', ...) and provides more information about the error. I’d like to be able determine if the error came from a dynamically added inline script, and if so, show the line of code that caused the error (and perhaps a few surrounding lines).

I can get event.error.stack which looks like this in Chrome (but varies by browser):

TypeError: foo is not iterable
    at fn (<anonymous>:3:16)

The <anonymous> bit is what Chrome uses for a dynamically-added inline script, but of course there can be multiple dynamically-added inline scripts on the page.

I’m wondering if there is any reliable way to determine the script which caused an uncaught error. I’d hoped that ErrorEvent.srcElement or something like that would point to the script element that caused the error, but there’s no property available for what I want to achieve as far as I can see. (And I guess one problem is that the script element may have since been removed from the page.)

To be clear, I don’t actually need a reference to the element itself – I just need a reference to the full script text.

Example Code:

<script>
  window.addEventListener("error", function(e) {
    console.error("window error handler:", e);
    console.log(e.error.stack);
  });
</script>

<script>
  let scriptEl = document.createElement("script");
  scriptEl.textContent = `function fn() { 
  let foo = {};
  for(let a of foo) {
    console.log(a);
  }
}`;
  document.head.append(scriptEl);

  setTimeout(() => {
    fn();
  }, 10)
</script>

Extra Context:

  • Since this is a dev tool, I don’t control the actual code within the inserted script. I just “inject” this uncaught error event handler.
  • That said, I can actually make small edits to the contents of script tags that are added to the page. But the edits would have to be very “light-weight”, since they wouldn’t be allowed to change the ‘userland’ code in any significant way.
  • I can also add code before the userland code – e.g. to overwrite .append and .appendChild prototypes so I can monitor scripts that are added to the page.
  • Note that it’s easy to catch SyntaxErrors, since they occur immediately after the script is inserted. But runtime errors can occur at any time.

Attempted Solution:

  • One hacky/unreliable approach might be to parse the line number from the stack, and then search the dynamically added inline scripts for variable names that were mentioned in the error message at the relevant line number. If there is only one script tag with that variable name at that line, then that might isolate the relevant script. But there are obviously a lot of ways that could go wrong, especially since we’re parsing error stacks, which IIUC don’t have any TC39 spec backing them.

(Note: I don’t think this question has a satisfying solution/answer, but I figure there’s a chance I missed something, and it also may become possible in the future, so it may be useful to have a question to track the possibility of this.)

Warning: TypeError: Cannot read property ‘Type’ of undefined

Im am writing this code in react native with expo but the problem is when I click the button its giving me an error Warning: TypeError: Cannot read property ‘Type’ of undefined

here is the button:

<TouchableOpacity style={[styles.menuItem, styles.activeMenu]} onPress={handleCameraScanIn}>
            <Icon name="chart-line" size={20} color="#fff" />
            <Text style={styles.menuText}>Live Overview</Text>
          </TouchableOpacity>

here is my CameraScanIn.js

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Camera } from 'expo-camera';

export default function CameraScan() {
  const [hasPermission, setHasPermission] = useState(null);
  const [cameraRef, setCameraRef] = useState(null);

  // Request camera permissions on mount
  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <Text>Requesting camera permission...</Text>;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <View style={styles.container}>
      <Camera style={styles.camera} ref={(ref) => setCameraRef(ref)} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  camera: {
    flex: 1,
    width: '100%',
  },
});

here is my package.json

{
  "name": "camerascanner",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@expo/metro-runtime": "~4.0.0",
    "@react-navigation/native": "^7.0.3",
    "@react-navigation/stack": "^7.0.3",
    "axios": "^1.7.7",
    "expo": "^52.0.7",
    "expo-camera": "~16.0.5",
    "expo-image-manipulator": "^13.0.5",
    "firebase": "^11.0.2",
    "react-dom": "18.3.1",
    "react-native-paper": "^5.12.5",
    "react-native-safe-area-context": "^4.14.0",
    "react-native-screens": "^4.1.0",
    "react-native-vector-icons": "^10.2.0",
    "react-native-web": "~0.19.13",
    "react-navigation": "^4.4.4",
    "react-navigation-stack": "^2.10.4"
  },
  "devDependencies": {
    "@babel/core": "^7.24.0"
  }
}

How can I solve this? so that when I clicked the button it will not show me that error I keep on struggling over this. It will be a nice if someone can help me with this thank you.