Confirmation dialog box after beforeunload event not showing up

I have a custom component in React. Whenever user makes any changes I am storing it and then attaching an event listener on beforeunload event. I have this callback function attached to the event.

  function handleUnload(event: Event) {
    event.preventDefault();
    console.log('RAN unload');
    return 'You have unsaved changes on this page. Sure you want to leave?';
  }

But whenever I refresh or press browser back button, the confirmation box with text “Do you want to leave site” doesn’t appear. As per MDN docs, as I’m calling preventDefault on event, it should show up but it isn’t. I can see the console log statement every time I refresh or leave the site.

Unable to know why is it happening.

How to make an incognito browser with HTML

I would like to make an incognito browser with HTML CSS and JS, but I don’t know how to show pages with <title> “incognito”, does anyone know how to do this? Thank you.

I tried using iframes, but im constantly getting the error “refused to connect”, and i don’t know how to do it in another way.

Trying to set an svg as a background image on a div in React

I am importing the SVG in my component like –

import Confetti from './Confetti.svg';

type ConfettiWrapperProps = {
  children: React.ReactNode;
};

export const ConfettiWrapper = (props: ConfettiWrapperProps) => {
  const { children } = props;

  return (
    <div
      style={{
        backgroundImage: `url(${Confetti})`,
      }}
    >
      {children}
    </div>
  );
};

Webpack config –

{
          test: /.svg$/,
          use: {
            loader: 'svg-url-loader',
          },
},

For some reason, I can’t see the background-image attribute on my div at all.

Passing in Confetti as src in an img tag works. I am clueless here.

ActionController::RoutingError (No route matches [PUT] “/”):

`hey , am trying to implement a reset a password functionality in my app. But am really puzzled up with how am gonna pass this error. 
 am using ruby as my  back end with devise gem and react at the front end. the problem is , when i make a put request with axios , the password is updated and it can be used for login which is right, but when i look at the console their is an error.

Started PUT "/" for ::1 at 2023-03-14 22:28:05 +0300
  
ActionController::RoutingError (No route matches [PUT] "/"):
and when a look at the web console, this is the message which is thrown
message
: 
"Request failed with status code 404" `

`below is my front end react`
```
import axios from 'axios';
import { useNavigate, useSearchParams } from 'react-router-dom';
import setAxiosHeaders from '../components/reusables/AxiosHeaders'

const ResetPassword = () => {
    const form = useRef();
    const navigate = useNavigate();
    const [params] = useSearchParams();
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [password_confirmation, setPassword_connfirmation] = useState('');

    const onFinish = (values) => {
        setLoading(true);
        const session = { "user": { ...values, reset_password_token: params.get("reset_password_token") } }
        const path = "/users/password"
        setAxiosHeaders();
        axios.put(path, session)
            .then((response) => {
                console.log(response.data)
                setLoading(false);
                setTimeout(() => {
                    navigate("/");
                    window.location.reload();
                }, 2000);
                message.success("your password has been updated succesfully")
            })
            .catch((error) => {
                console.log(error);
                message.error("un able to reset your password")
                setLoading(false);
            })
    }
`i have edited for simplicity , and below are my routes`

Rails.application.routes.draw do
namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :homes do
resources :payments, shallow: true
end
get ‘users/check_user’
get ‘main/index’
get ‘main/search’
devise_scope :user do
post ‘users/forgot_password’, to: ‘passwords#create’
end
end
end
root ‘homes#index’
devise_for :users
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)

match ‘*unmatched_route’, via: :all, to: ‘homes#index’, constraints: lambda { |request|
request.path.exclude? ‘rails/active_storage’
}
end


Mdx content & frontmatter data in next.js

I use next-mdx-remote plugin have a function that outputs articles from mdx, located in a separate file. Below is the code of my file [slug].js and my service function for generating articles. The problem is that the content of the article is displayed as expected, but everything about frontmatter.title and, for example, frontmatter.description is not. I have tried many options, but either the output of my data from frontmatter does not work, or the output of the content of the article. How to make both work?

//  /lib/getAllData
import fs from 'fs';
import matter from 'gray-matter';

export function getAllPosts() {
    const files = fs.readdirSync('./posts');
    const posts = files
      .map((fileName) => {
        const slug = fileName.replace(/.mdx$/, '');
        const { frontmatter } = getPostBySlug(slug);
        return {
          slug,
          ...frontmatter,
        };
      })

    return posts;
  }

export function getPostBySlug(slug) {
    const fileName = fs.readFileSync(`posts/${slug}.mdx`, 'utf-8');
    const { data: frontmatter, content } = matter(fileName);
    return {
      frontmatter,
      content,
    };
  }



    //   pages/blog/[slug].js
    
    import { getAllPosts, getPostBySlug } from "@/lib/getAllData";
    import Head from 'next/head'
    import { serialize } from 'next-mdx-remote/serialize';
    import { MDXRemote } from 'next-mdx-remote';
    
    
    export async function getStaticPaths() {
        const posts = getAllPosts();
    
        return {
          paths: posts.map((post) => {
            return {
              params: {
                slug: post.slug,
              },
            };
          }),
          fallback: false,
        };
      }
    
      export async function getStaticProps({ params: { slug } }) {
        const post = getPostBySlug(slug);
        const mdxSource = await serialize(post.content);
        return {
          props: {
            //post,
            frontmatter: post,
            content: mdxSource
          }
        };
      }
    
    
      export default function PostPage({ frontmatter, content }) {
        return (
            <>
                <Head>
                    <title>Next.js | Tech Radar</title>
                    <meta
                        property="og:image"
                        content={`http://localhost:3000/api/og?title=${frontmatter.title}&description=${frontmatter.description}`}
                    />
                </Head>
    
                <section className='px-6'>
                    <div className='max-w-4xl mx-auto py-12'>
                    <div className='prose mx-auto'>
                        <h1>{frontmatter.title}</h1>
                        {/* <div>{content}</div> */}
                    <MDXRemote {...content}  />
                    </div>
                    </div>
                </section>
          </>
        );
      }




This synaptic algorithm doesn’t work as expected

I am trying to make a predictive algorithm to help with pricing a vehicle based on the history of sales from a dealership. The historical sales are represented in JSON like the following:

"<DOCUMENT_ID>": {
      "company_id": "...",
      "data": {
        "vehicle": {
          "v_acv": 37000,
          "v_days": 38,
          "v_final_acv": 38332,
          "v_final_carg_h": 44650,
          "v_final_mmr": 39200,
          "v_initial_carg_h": 44625,
          "v_initial_mmr": 38500,
          "v_miles": 11482,
          "v_sell_price": 43981,
          "v_source": "USED TRADE",
          "v_start_price": 43981,
          "v_vehicle": "2021 TOYOTA RAV4 TRD OFF ROAD",
        }
      },
      // ...
    }

I have formatted this into an array using the following code for Synaptic:

const vehicleTitleMap = new Map()
const sourceMap = new Map()

let dataSet = []

Object.keys(data).forEach((key) => {
  let vehicle = data[key].data.vehicle

  let title
  if (vehicleTitleMap.has(vehicle.v_title)) {
    title = vehicleTitleMap.get(vehicle.v_title)
  } else {
    title = vehicleTitleMap.size
    vehicleTitleMap.set(vehicle.v_title, title)
  }

  let source
  if (sourceMap.has(vehicle.v_source)) {
    source = sourceMap.get(vehicle.v_source)
  } else {
    source = sourceMap.size
    sourceMap.set(vehicle.v_source, source)
  }

  dataSet.push({
    input: [
      parseInt(vehicle.v_acv),
      parseInt(vehicle.v_final_acv),
      parseInt(vehicle.v_miles),
      parseInt(vehicle.v_days),
      parseInt(vehicle.v_initial_mmr),
      parseInt(vehicle.v_final_mmr),
      parseInt(vehicle.v_initial_carg_h),
      parseInt(vehicle.v_final_carg_h),
      parseInt(vehicle.v_start_price),
      title,
      source,
      parseInt(vehicle.v_sell_price)
    ],
    output: [parseInt(vehicle.v_sell_price)]
  })
  
  dataSet = dataSet.filter(doc => {
    return doc.input.every(item => !isNaN(item)) && doc.output.every(item => !isNaN(item))
  })
})

Then, the actual code for the Synaptic model:

const network = new synaptic.Architect.Perceptron(12, 4, 1)
const trainer = new synaptic.Trainer(network)
trainer.train(dataSet)
const output = network.activate([
  14500, 17100, 72453,
      4, 16650, 16650,
  21701, 23262, 20991,
      0,     3, 20991
])
console.log(output) // Should be 20991

I have run this code and made a few alterations to get to the current state, but as the output from the model, I always get [ 1 ]. Why is this?

JavaScript/HTML text based game not working (when its done it will be kinda like battleship)

<!doctype HTMl>
<html>
<head>
  <style>
html, body, head{
font-family:monospace, monospace;
background-color: #d5e3e8;
}
main{
background-color:#f5f5f5;
padding:20px;
width:90%;
margin:auto;
}
.artificialcanvas{
  background-color:black;
  height:500px;
  width:60%;
  margin:auto;
  margin-top:10px;
  margin-bottom:10px;
  color:white;
}
.bottom{
  left:0;
  width:250px;
  color:red;
}
.select:hover{
  color:red;
  text-decoration:underline;
}
.select:active{
  color:crimson;
  text-decoration:none;
}
.price{
  color:yellow;
  text-decoration:italic;
  font-size:10px;
}
  </style>
  <script>
  var money = 164000;
    function select(num,cost){
      if money >= cost{
      document.getElementById(num).innerHTML = "Purchased";
      money -= cost;
      document.getElementById("cur").innerHTML = money+" Rbl";
      }
    }
  </script>
  </head>
<body id="body" onLoad="storage()">
  <main style="padding:20px; margin-top:5px;" id="par">
      <p style="font-size:30px;margin:auto;width:120px;text-align:center;">Katyusha</p>
    <div class="artificialcanvas">
      <br>
      <div id="cur">167,000 Rbl</div>
      <div class="bottom" style="margin-left:5px">
        <p>Vehicles:</p>
        <div style="margin-left:5px;color:blue;">
        <div id="1" class="select" onClick="select(1,163000)">ZIS-5/BM-8 <span class="price">(163,000 Rbl)</span></div>
        <div id="2" class="select" onClick="select(2,168000)">ZIS-5/BM-8-36 <span class="price">(168,000 Rbl)</span></div>
        <div id="3" class="select" onClick="select(3,171000)">ZIS-6/BM-8-48 <span class="price">(171,000 Rbl)</span></div>
        <div id="4" class="select" onClick="select(4,175000)">ZIS-7/BM-13N <span class="price">(175,000 Rbl)</span></div>
        <div id="5" class="select" onClick="select(5,180000)">ZIS-12/BM-31-12 <span class="price">(180,000 Rbl)</span></div>
        <div id="6" class="select" onClick="select(6,185000)">ZIL-157/BM-13 <span class="price">(185,000)</span></div>
        <div id="7" class="select" onClick="select(7,190000)">ZIL-151/BM-13 <span class="price">(190,000 Rbl)</span></div>
        <div id="8" class="select" onClick="select(8,193000)">ZIL-157/BM-13 <span class="price">(193,000 Rbl)</span></div>
        </div>
        <p>Rockets:</p>
        <div style="margin-left:5px;color:blue;">
        <div>M-8 <span class="price">(4,000 Rbl)</span></div>
        <div>M-13 <span class="price">(4,500 Rbl)</span></div>
        <div>M-13DD <span class="price">(5,000 Rbl)</span></div>
        <div>M-31 <span class="price">(5,300 Rbl)</span></div>
        <div>M-31UK <span class="price">(5,300 Rbl)</span></div>
        <div>M-30 <span class="price">(5,600 Rbl)</span></div>
        </div>
      </div>
      <div style="right:0;">
        hello
      </div>
    </div>
  </main>
  </body>
</html>

It definitely has to do with the javascript because the HTML is fine when I get rid of the javascript variable.⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀

Problem with HTML and CSS, responsive menu that leaves an empty area

I have a problem with my code that I put below. Basically I want my site to be responsive and therefore I want a special menu on small screens. My large screen display is working and my small screen menu is also working but it leaves a blank area at the top of the page and I can’t find where it comes from. I just want my whole screen to go black and not have the top area stay on top of the previous one.

Here a screen before press the button :

before

And here a screen after :

after

And here this is my actual code :

HTML part :

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

<head>

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

    <link rel="stylesheet" href="../../asset/css/Home_Page.css"/>

    <title>P B</title>

</head>

<body>

    <nav>

        <div class="logo">
            <img src="../../asset/img/Logo.png" alt="Logo Image">
        </div>

        <div class="hamburger">
            <div class="line1"></div>
            <div class="line2"></div>
            <div class="line3"></div>
        </div>

        <ul class="nav-links">
            <li><a href="">Nos Produits</a></li>
            <li><a href="">Notre Histoire</a></li>
            <li><a href="">&nbsp; &nbsp; Galerie &nbsp; &nbsp;</a></li>
            <li><a href="">&nbsp; &nbsp; Salons &nbsp; &nbsp; </a></li>
            <li><a href="">&nbsp; &nbsp; Contact &nbsp; &nbsp; </a></li>
        </ul>

    </nav>


    <script src="../../asset/js/Menubtn.js"></script>

</body>
</html>

CSS Part :

/*****************************

             Font 

*****************************/

@font-face {
  font-family: 'RomanAntique';
  src: url("../../asset/font/RomanAntique.ttf") format("truetype");
  font-weight: 500;
  font-style: normal;
  font-display: swap;
}

/*****************************

     Default Background 

*****************************/

/* > 1000px */
body {
  background-image: url("../../asset/img/BackGroundTest.jpg");
  background-size : 100% !important;
}

/* < 1000px */
@media screen and (max-width: 800px) {
  body {
    background-image: url("../../asset/img/BackGroundTestPhone.jpg") !important;
    background-size : 100% !important;
  }
}

/*****************************

     Default Properties 

*****************************/

body {
  margin: 0;
  margin-top: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  font-family: 'RomanAntique';
  overflow-x: hidden;
  overflow-y: hidden;
}

nav{
    width: 100%;   
    display: flex;
    position: fixed;
    z-index: 10;
}


/*Styling logo*/
.logo{
    padding:1vh 1vw;
    text-align: center;
}

.logo img {
    height: 5rem;
    width: 5rem;
}

/*Styling Links*/
.nav-links{
    display: flex;
    list-style: none; 
    width: 88vw;
    padding: 0 0.7vw;
    justify-content: space-evenly;
    align-items: center;
    text-transform: uppercase;
}

.nav-links li a{
    color: #FFFFFF;
    text-decoration: none;
    margin: 0 0.7vw;
}

.nav-links li {
    position: relative;
}

.nav-links li a::before {
    content: "";
    display: block;
    height: 3px;
    width: 0%;
    background-color: #FFFFFF;
    position: absolute;
    transition: all ease-in-out 250ms;
    margin: 15% 0 0 10%;
}

.nav-links li a:hover::before{
    width: 80%;
}



/*Styling Hamburger Icon*/
.hamburger div{
    width: 30px;
    height:3px;
    background: #FFFFFF;
    margin: 5px;
    transition: all 0.3s ease;
}
.hamburger{
    display: none;
}

/*Stying for small screens*/
@media screen and (max-width: 800px){
    body {
      margin: 0;
      padding: 0;
    }
    nav{
        position: fixed;
        z-index: 9999;
    }
    .hamburger{
        display:block;
        position: absolute;
        cursor: pointer;
        right: 5%;
        top: 50%;
        transform: translate(-5%, -50%);
        z-index: 999999;
        transition: all 0.7s ease;
    }
    .nav-links{
        position: fixed;
        background: #000000;
        height: 100vh;
        width: 100%;
        flex-direction: column;
        clip-path: circle(50px at 90% -20%);
        -webkit-clip-path: circle(50px at 90% -10%);
        transition: all 1s ease-out;
        pointer-events: none;
    }
    .nav-links.open{
        clip-path: circle(1500px at 100% -10%);
        -webkit-clip-path: circle(1500px at 100% -10%);
        pointer-events: all;
    }
    .nav-links li{
        opacity: 0;
    }
    .nav-links li:nth-child(1){
        transition: all 0.5s ease 0.2s;
    }
    .nav-links li:nth-child(2){
        transition: all 0.5s ease 0.4s;
    }
    .nav-links li:nth-child(3){
        transition: all 0.5s ease 0.6s;
    }
    .nav-links li:nth-child(4){
        transition: all 0.5s ease 0.8s;
    }
    .nav-links li:nth-child(5){
        transition: all 0.5s ease 1.0s;
    }

    li.fade{
        opacity: 1;
    }
}



/*Animating Hamburger Icon on Click*/
.toggle .line1{
    transform: rotate(-45deg) translate(-5px,6px);
}
.toggle .line2{
    transition: all 0.7s ease;
    width:0;
}
.toggle .line3{
    transform: rotate(45deg) translate(-5px,-6px);
}

JavaScript Part :

const hamburger = document.querySelector(".hamburger");
const navLinks = document.querySelector(".nav-links");
const links = document.querySelectorAll(".nav-links li");

hamburger.addEventListener('click', ()=>{

    navLinks.classList.toggle("open");

    links.forEach(link => {
        link.classList.toggle("fade");
    });

    hamburger.classList.toggle("toggle");

});

Thx in advance for your help

As shown in the images, my problem is with the area at the top when the menu is activated, as it should be black like the rest, but I don’t understand why it remains in its current state.

How to display two values in two inputs?

I have two inputs, I have a minimum value and a maximum value.

My problem is that I would like that inside each input there are values…

For example:

For the input minimum value I must display .00

and for the maximum value I must display 9999999999999.99.

Below, here is an image illustration. I absolutely want the same result, please.

enter image description here

template

<form #formulaire="ngForm" (ngSubmit)="getOverviewTotalAmount()">
<div class=" row mb-4 align-items-end ">
   <div class="col-12 col-sm-6 col-md-4 ">
      <div class="mb-2 ">
         <!-- Minimum value  -->
         <h5>Minimum value</h5>
         <input type="number" class="form-control form-max-width" [(ngModel)]="model.valoMin" name="valoMin" required />
      </div>
   </div>
   <div class="col-12 col-sm-6 col-md-4 ">
      <div class="mb-2 ">
         <!-- Maximum value -->
         <h5>Maximum value</h5>
         <input type="number" class="form-control form-max-width" [(ngModel)]="model.valoMax" name="valoMax" required />
      </div>
   </div>
   <div class="col-12 col-md-4 ">
      <div class="mb-2 ">
         <button type="submit " class="btn btn-success btn_green_arg ">
            <!-- Search -->
            Search
         </button>
      </div>
   </div>
</div>
</form>

class

export class Amount {
  amount: string;
  valoMin: number | null; 
  valoMax: number | null; 

  constructor() {
    this.amount = '';
    this.valoMax = null; 
    this.valoMin = null; 
  }

  validateMinMax(): boolean {
    return this.valoMin == null || this.valoMax == null || this.valoMin <= this.valoMax;
  }
}

composent

export class OverviewTotalAmountComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject<void>();
  currentAgency: any;
  overviewTotalAmountResponse: OverviewTotalAmountResponse;

  model: Amount = new Amount();
  valoMin: number;
  valoMax: number;

  constructor(
    private service: OverviewTotalAmountService,
    private store: Store,
    private router: Router
    ) {}

    ngOnInit(): void {
      this.currentAgency = this.store.selectSnapshot(AgencyState.currentAgency);
      if (this.currentAgency) {
        this.getOverviewTotalAmount();
      }
    }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  getOverviewTotalAmount(): void {
    this.service
      .getOverviewTotalAmount(this.model)
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe((res) => {
        if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
          this.overviewTotalAmountResponse = res as OverviewTotalAmountResponse;
          this.valoMin = this.model.valoMin !== null ? this.model.valoMin : 0;
          this.valoMax = this.model.valoMax !== null ? this.model.valoMax : 0;
        }
      });
  }

  
  
}

I thank you in advance for your help and the time devoted to my problem, because I am really stuck.

Javascript import-export from the other file ruin the entire file

So i want to build a website. there is a data file which i am trying to store datas. Example

export let enyenigirisimler = {
    data:[
        {
            girisimlogo:"martı.png",
            girisimisim:"martı",
            girisimözellik:"Teknoloji,Ulaşım",
            girisimkonum:"İstanbul Kadıköy"
        }
    ]
};

the i import the enyenigirisimler to the main js file like this

import { enyenigirisimler} from "./data";

after that i use the “enyenigirisimler”. i can access the datas in the variable but when i run the website i cannot find what i did with “enyenigirisimler”.

Then i try to put datas in the main js file and do not work. when i delete the “import” line it works. Then i found out that this “import” line ruin the entire js file. i cannot use anything i build on the main js file. example i write the droddown menu but when i put “import” line nothing works properly. so it ruins entire file. NOTE i am not using es6. pure javascript only

How to add functionality to a Leaflet.TimeDimension LineString on a click event?

I put GPS tracks on a leaflet map. To better show the movement I use the plugin Leaflet.TimeDimension to add time dimension controls. Quite simular to this example.

I want to add functionality on a click event to the Layer.
e.g.: timedLayer = L.timeDimension.layer.geoJson(geojsonLayer)
The GeoJSON layer (geojsonLayer) is a LineString.

timedLayer.on("click", console.log("Line clicked on:" + event.latlng)) has no effect.
Also geojsonLayer.on("click", console.log("Line clicked on:" + event.latlng)) has no effect, since this layer is not added to the map. If its added to the map, then there is a output on the console. But I no longer able to use the timeDimension player etc.

Workarounds to get the event.latlng when the user click on the LineString?

Why can i not access the Figma API token with a http request?

i am trying to acess the figma API using my personal token, but once i make the request it sends a response with the 403 status (forbidden), can someone help me ?

I generated a token: My token

I am making the request to the following url: ‘https://api.figma.com/v1/files/${mytoken}’;

The status code is the following: 403

What is wrong with my code? is the url wrong ?

Cant connect to external Back-end (ngrok)

I’m in a project which uses ngrok as the back-end and it runs on a coworker’s computer. I’m the only one that cant access it through the front-end. I can access it by accessing the ngrok link, but the front-end never points to the ngrok, so I cant get anything to load, even though my .env is connected to it. I’m using a Google Chrome with CORS disabled, because they havent fixed CORS issue yet. The front-end only points to localhost, even thought the .env is indeed pointing to the ngrok.

How do I fix this?
Also, no one else on the project has had this issue and they dont know how to fix it either.

I’ve tried to get .env and other files from my coworkers, but it still doesnt connect. It connects for them though.

The expected result is the front-end point to the ngrok so I can access the project and code/test stuff ,but it never does, it only points to localhost.

How to assert that a component’s prop is in a certain number range?

In languages such as C or C++, the standard library provides an assert macro that exits the application if the provided condition is false.

What’s the JS/React alternative?

Is there a standardized solution to my problem? a function that would throw an error if the provided condition is false?

The code below best explains what I’d hope to achieve:

function Component ({ value }) {
  assert((value >= 0) && (value <= 100)) // throw an error if the expression is false?

  return <div>{value}</div>
}

I have tried using the most popular JS testing library – Jest. But, to my knowledge, there’s no way of asserting React component’s props.

Update State from Fetched API request

I’m fetching data from two separate APIs and updating their states individually. Afterwards, I’m mapping through the nba data and looping through the animeData object to update the allData state that will consist of an array of objects. The final output should be something like this
[
{
“PHI”: “Natsume Yuujinchou”
},
{
“LAL”: “Natsume Yuujinchou”
},
{
“MIN”: “Natsume Yuujinchou”
}]. Lastly, I will render this information but I can’t seem to update the allData state as it gives me the infinite rerender loop. Is there any way to fix this?

const [nbaData, setNbaData] = useState(null)
const [animeData, setAnimeData] = useState(null)
const [allData, setAllData] = useState(null)

const getData = async () => {
    const nbaone = await fetch(`https://www.balldontlie.io/api/v1/games? 
    start_date=2023-03-10}&end_date=2023-03-10`)
    const nbaData = await nbaone.json()
        if(nbaData !== null){
            setNbaData(nbaData.data)
        }
        const anime = await fetch(`https://animechan.vercel.app/api/random`)
        const animechan = await anime.json()
        if(animechan !== null){
            setAnimeData(animechan)
        }
    
}

if(nbaData !== null && animeData !== null){
    setAllData(() => {
        nbaData.map(item => {
            for(let key in animeData){
                return {
                    [item.home_team.abbreviation]: animeData[key]
                }
            }
        })
    })
}



useEffect(() => {
    getData()
}, [])