React Promise Based Modal

I have developed the code for the modal in React. I wanted to make a generic modal for the application and I came up with a solution but god knows how. Can anyone take a look at the code and explain why is it working and how can we make it better?

I’m writting the code snippet in Stackoverflow for the first time and I’m getting error in the react code. Could anyone please see what is the issue.

const {useState} = React;

//this variable is getting assigned the resolve function of a Promise.
// If the variable is defined inside the App() component then it does not work and throws undefined
// can anyone explain how this is working.
let resolveHelper;
const App = ()=> {
  const [data, setData] = useState(["Apple", "Banana", "berries", "Kiwi"]);
  const [isModalHidden, setIsModalHidden] = useState(false);

  const handleDelete = async (fru) => {
    try {
      const res = await handlePromise();
      if (res) {
        // Delete Logic will come here
        console.log("We will delete you");
      } else {
        // No is clicked escape logic will come here
        console.log("you can go");
      }
    } catch (err) {
      console.log(err);
    }
  };

  // This function is returning a promise and assigning resolve function to a variable
  const handlePromise = () => {
    setIsModalHidden((prev) => !prev);
    return new Promise((resolve) => {
      resolveHelper = resolve;
    });
  };

  // This function is listening to the button click of Modal
  const handleConfirmation = (confirmation) => {
    return new Promise((resolve, reject) => {
      if (confirmation) resolveHelper(true);
      else resolveHelper(false);
    });
  };

  // Mapping the data to HTML
  const dataContent = data.map((fruit) => (
    <li key={fruit}>
      {fruit} <button onClick={() => handleDelete(fruit)}>delete</button>
    </li>
  ));

  // Modal show or hide based on the flag value
  const displayValue = isModalHidden ? "block" : "none";
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <ul>{dataContent}</ul>

      <div style={{display:`${displayValue}`}}>
        Are you sure you want to delete this
        <button onClick={() => handleConfirmation(true)}> Yes</button>
        <button onClick={() => handleConfirmation(false)}> No </button>
      </div>
    </div>
  );
}

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App/>
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>

Creating the object then pass the values in array

I have Multi-level hierarchies will be on a select list. Now that I have a table, he may select values from the subsequent column and push them into the filter by clicking the column.

var name = ['Akansha', Navya]

var age = ['24', '26']

var id = ['2345', '34555']

All of those values must now be passed in JSON format to the filter. The actual hierarchy will look as follows since we must follow to the hirearchy in order to push the values that are in the json format.

Values: Array(2)

I must build the same array list because these Values is predefined in the JSON.

Values:(2)
0:{name:'Akansha', age:'24', id:'2345'}
1:{name:'Navya', age:'26', id:'34555'}

I used a for loop to build the array list, which will produce the same array list as needed.

var nameValues =[];

for(var i=0; i < name.length; i++){
 var  filterValue = new nam3({ // name3 object is prdefined for the filter so i have insitalize the object
name: name[i];
age: age[i];
id: id[i]
});
nameValues.push(filterValue);
}

console.log(nameValues); //This gives me the same array list and format the values as required.
//(2)
//0:{name:'Akansha', age:'24', id:'2345'}
//1:{name:'Navya', age:'26', id:'34555'}

Now i have to push name.values to the filter .Product is the filter id

product.values.push(nameValues);
I have therefore added these values to the Values Array’s product filter. But, the problem is that when I push those data, a nested array is created, which causes an object refrence error.
When I send the JSON array to the filter, It Appear Like This In Console.
This is the result I receive after running the entire script.

Values:Array(1)
       0: Array(2)
          0:{name:'Akansha', age:'24', id:'2345'}
          1:{name:'Navya', age:'26', id:'34555'}
T

But the output we required

Values:(2)
0:{name:'Akansha', age:'24', id:'2345'}
1:{name:'Navya', age:'26', id:'34555'}

Now I have the pass nameValue in the Values Array that are in Json . Can anybody help me with this

m not sure how we can accomplish this to pass it in the Values Array right now. I’m new to javascript, so figuring out how to resolve this would be fantastic.

In JavaScript, how to determine if you are at the end of a feed (like some pages on Facebook or Quora)?

You can jump to the end of a webpage using JavaScript like this

window.scrollTo(0, document.body.scrollHeight);

but nowadays it is common that pages load more content when you reach the end. Two examples of such pages are https://www.facebook.com/friends/list and https.//www.quora.com

Let’s say you run the oneliner above in a loop to reach the end of a page that behaves like this, how can you detect that you have reached the end? That is, no more content will be loaded.

I’m scraping a web page so I am looping something like the oneliner above to get to the end but I don’t know when I have reached it. An important detail to take into consideration is that the page I am scrolling down is VERY long and, after scrolling down and loading new content for a while it starts to slow down the browser. If loading new content in the beginning might take 1-2 seconds, it can, after scrolling down for a while, take 10-20 seconds (and that is why I am scraping it – I am extracting the data to a CSV to be able to scroll through it faster instead of having to wait, if I would scroll manually, for the page load more content 50-100 times before I reach the end).

How to find the current caret/cursor index of a contenteditable=true tag

I am really struggling to find an answer that works for my use case. I need to have awareness of where in the contentEditable

tag the cursor/caret is.

I have tried various solutions and always get the same issue, caret solution is equal to 0.

Here is a sandbox example. If I could get it working here, I could get it working in my actual app.

Any assistance desired:

import { Component, h } from '@stencil/core'

@Component({
  tag: 'my-editable-component',
  styleUrl: 'my-editable-component.css',
  shadow: true,
})
export class MyEditableComponent {
  editableRef: HTMLParagraphElement

  getCaretPosition() {
    const selection = window.getSelection()
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      const preCaretRange = range.cloneRange()
      preCaretRange.selectNodeContents(this.editableRef)
      preCaretRange.setEnd(range.endContainer, range.endOffset)
      return preCaretRange.toString().length
    }
    return 0
  }

  handleInput = () => {
    console.log('Caret position:', this.getCaretPosition())
  }

  render() {
    return (
      <div>
        <p ref={el => (this.editableRef = el as HTMLParagraphElement)} contentEditable onInput={this.handleInput}>
          Click to edit text and log caret position
        </p>
      </div>
    )
  }
}

JavaScript error in writing text to a user defined file: failed to execute createWritable, user activation required

i am trying to write some text in a user defined text file.

In the JavaScript file i have kept a global variable to store the file Handle.

let dbFileHandle = null;

A button is clicked by the user which runs the following code

async function selectFile() {
    [dbFileHandle] = await window.showOpenFilePicker();
    document.getElementById("DbFileLoc").innerHTML = [dbFileHandle][0].name;
    getFileData();
}

This function inturn calls another function getFileData() which reads data from file and stores it in a variable text which is again a global variable.

async function getFileData() {
    let fileData = await dbFileHandle.getFile();
    text = await fileData.text();
}

After sometime the user clicks another button which calls saveData() function which should write another text inside the same file. So i tried to use the same dbFileHandle to do this. The function called in this case.

async function saveData() {
    let stream = await dbFileHandle.createWritable();
    await stream.write(txt);
    await stream.close();
    console.log("dataSaved!!");
}

Here txt is written to the file which is a global variable.

I am coding in VSCode and am using LiveServer plugin at one point i dont know how, it worked : the webpage gave a alert which said something like this the page will be able to access the file so i clicked on OK and it worked as intended. Since i was using LiveServer and the file being changed was placed in a directory which was in the same directory as the HTML file so it got reloded.

Since then i have tried opening the HTML file without live server / with liveServer but it gives the same error

Uncaught (in promise) DOMException : Failed to execute 'createWritable' on 'FileSystemFileHandle': User activation is required to request permissions.

and yes i am quite new to JS !!!

thanks in advance !

Cannot read properties of null (reading ‘useContext’) while using from ant design

I´m trying to use a Button from Ant Design, but I keep getting the error:

Cannot read properties of null (reading 'useContext')
TypeError: Cannot read properties of null (reading 'useContext')
    at Object.useContext (http://localhost:3000/main.19e2674394eb4e9a7d19.hot-update.js:36279:25)
    at InternalButton (http://localhost:3000/main.19e2674394eb4e9a7d19.hot-update.js:4513:42)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:21088:22)
    at updateForwardRef (http://localhost:3000/static/js/bundle.js:23659:24)
    at beginWork (http://localhost:3000/static/js/bundle.js:25706:20)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:10680:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:10724:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:10781:35)
    at beginWork$1 (http://localhost:3000/static/js/bundle.js:30655:11)
    at performUnitOfWork (http://localhost:3000/static/js/bundle.js:29902:16)

I´m using this code and trying to create a simple button but it does not work!

App.js:

import { Button } from 'antd';
import React from 'react';

function App() {
  return (
    <div>
      <h1>Teste</h1>
      <Button></Button>
    </div>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
// importando o CSS do Ant
import 'antd/dist/reset.css';

// importando o App
import App from './App';

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

Fetch data with SWR on client component with each request. Next.js 13.3 + SWR

Next.js 13.3 with app dir. I have a very simple component that displays a date. He displays it only 1 time and after that it is no longer updated until I rebuild it. In Next.js 12, this worked differently (refresh page – update data). What am I doing wrong? I can’t figure out how to make it update the date on every request.

Why doesn’t SWR update information on every request?

api/hello/route.ts


export async function GET(request: Request) {
  // const { searchParams } = new URL(request.url);

  const response = await fetch(
    "https://timeapi.io/api/Time/current/zone?timeZone=Europe/Kiev",
    { cache: "no-cache" }
  );

  const data = await response.json();
  console.log(data);

  return NextResponse.json(data);
}

time.tsx

"use client";

import useSWR from "swr";
import { fetcher } from "~/lib/fetcher";

export const Time = () => {
    const { data, error, isLoading } = useSWR("api/hello", fetcher);

  if (error) {
    return <div>error</div>;
  }

  if (isLoading) return <div>loading...</div>;

  console.log(data);
  return (
    <div>
      <div>{data.dateTime}</div>
    </div>
  );
};

fetcher.ts

export const fetcher = (...args: any) => fetch(...args).then(res => res.json())

page.tsx

import { Inter } from "next/font/google";
import { Time } from "~/components/time";

const inter = Inter({ subsets: ["latin"] });

export const revalidate = 0;

export default async function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <Time />
    </main>
  );
}

Should I use react State for adding and removing classes?

I am using intersection observer to add and remove classes so I can start an animation when certain div is being exhibited in the viewport. I am using this basically to add animation just like this website here:https://crypto.com/us, notice that when you scroll and certain section is exhibited an animation starts, showing the titles.

My code is below and is working fine:

useEffect(() => {
    const titleElements = document.querySelectorAll('.title, .description, .text');
    const options = {
      root: null,
      rootMargin: '0px',
      threshold: .4
    }

    const callbacks = (entries: any) => {
      entries.forEach((e: any) => {
        if (e.isIntersecting && e.target.className === 'text') {
          e.target.classList.add('text-animation');
        } else if (e.isIntersecting && e.target.className !== 'text') {
          e.target.classList.add('title-animation');
        } else {
          e.target.classList.remove('title-animation');
          e.target.classList.remove('text-animation');
        }
      });
    }

    let observer = new IntersectionObserver(callbacks, options);

    titleElements.forEach((e) => {
      observer.observe(e);
    })
  }, [])

I also noticed that I am not using react useState in another class. Everytime a value changes this function below runs returning one or another class. Obs: the function runs everytime when the value changes, when it happens the component is rendered again because I set the key value to always be different so if this function returns ‘current-price-up’ two or more times this animation will runs always as react is rendering a ‘new’ component everytime.

const handleUpdateEffect = (price: any, i: any) => {
    if (prevList.length === 1) {
      return ''
    } else if (price > prevList[i].current_price) {
      return 'current-price-up'
    } else if (price < prevList[i].current_price) {
      return 'current-price-down'
    } else {
      return 'current-price-keep'
    }
  }

Everything is working fine, my question is: once I am using react is it bad practice to add and remove classes directly in the DOM even if I am using useEffect (classes are added or removed after everything is rendered) in the first example or using a function in the second example?

Should I apply useState for all those classes? Does it cause performance problems? I’ve always used useState but I find this way using ‘.classList.add’ and it is working in this case, and I also realized I am using a function instead of state in the second example, what way is right in what contexts? Should I always use useState to toggle between classes to start animations and add effects?

Approach to loading node library in other language

Hi a lot of js library in npmjs now are in esm, cjs format only.

From python, php, .net background and other non node language when building web app we still require javascript for the web part.

What is the best approach is said library doesn’t provide browser support (cannot loading using tag ) ?

At least converting it to umd is the best, but now seems more and more library is forcing us to move to node.js entirely.

React Error: Cannot read properties of null (reading ‘replace’)

I’m just learning React and I’m designing a webstore project, I got this error in my ShoppingList when defining the variables and values , thank you for your help.

({value === “all” && items.map((item) => (
<Item item={item} key={${item.name}-${item.id}} />
))}
{value === “newArrivals” && items.map((item) => (
<Item item={item} key={${item.name}-${item.id}} />
))}
{value === “bestSellers” && items.map((item) => (
<Item item={item} key={${item.name}-${item.id}} />
))}
{value === “topRated” && items.map((item) => (
<Item item={item} key={${item.name}-${item.id}} />
))})

Incorrect operation of transferring variable values from one HTML file to another

I have page №1 where I enter text into the form. Then, in the form_check() function, I write to the name variable. After that, I need to open page №2 and output the text with the value of the name variable there. I use localStorage to write the name variable to the name_result key. I switch to another page using window.location.href = 'page2.html' and I call the result() function, in the body of which I get the value from localStorage by key and pass it to HTML via document.getElementById(). But the value of the name variable does not appear on the page №2.

HTML (page №1):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form>
        <label>Name:</label>
        <input type="text" id="name">
        <i id="name_error"></i>
    </form>
    <button type="button" onclick="form_check()">Submit</button>
    <script src="/script.js"></script>
</body>
</html>

HTML (page №2):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" src="/style.css">
    <title>Лабораторная работа №11</title>
</head>
<body>
    <p>Было введено название: <i id="name_result"></i></p>
    <script src="/script.js"></script>
</body>
</html>

JavaScript:

function result()
{
    console.log(localStorage.name_result);
    document.addEventListener(`DOMContentLoaded`, function() {
        document.getElementById(`name_result`).innerHTML = localStorage.name_result;
    });
}

function form_check()
{
    let name = String(document.getElementById(`name`).value);
    localStorage.setItem(`name_result`, name);
    window.location.href = `page2.html`;
    result();
}

I also tried passing the value of the name variable through the result function argument, but the result is the same.

Leaflet remove layer vue3

I have a map that displays json data, and a radio button that changes de FL of the displayed data. The problem that I have is that every time I change the Fl I am not able to remove the previous layer and it just overlays the previous one. I have tried the code below, but is not working. The new_storm_layer is stored in a Store created with pinia.

function create_map_layer(geojson_data, maptoplot) {
        //maptoplot.eachLayer((new_layer) => {
        //  layer.remove();
        //});
        const new_layer = leaflet.geoJSON(geojson_data).addTo(maptoplot)
        new_layer.clearLayers();
        new_layer.addData(geojson_data);
        return new_layer
      }

      async function foo(get_request) {
        await fetch(get_request
        ).then(
          res => res.json()
        ).then(
          data => create_map_layer(data, mymap)
        ).then(
          new_storm_layer => DataStore.$patch({ storm_layer: new_storm_layer })
        )
      }

Thank you in advance!

Described above, removing previous layers.

How to add hamburger menu & functionality in React for mobile view?

I’m working on a React project and I’m trying to make my header section more mobile-responsive. Currently, I have three links (Home, About, and Login) in the left section, a centered logo/title, and search and cart buttons on the right side.

I want to add a hamburger icon that appears on mobile devices (when the screen width is less than 768px) that will toggle a menu containing the Home, About, and Login links. However, I want to keep the search and cart buttons outside of this hamburger menu, and maintain their position on the right side of the header.and I want to add the functionality code for the hamburger part

Here’s my current code for the Header component (including the relevant styles):

Header.jsx


import { useEffect, useState, useContext } from "react";
import { useNavigate } from "react-router-dom";

import { TbSearch } from "react-icons/tb";
import { CgShoppingCart } from "react-icons/cg";

import Search from "./Search/Search";
import Cart from "../Cart/Cart";
import { Context } from "../../utils/context";

import "./Header.scss";

const Header = () => {

    const [scrolled, setScrolled] = useState(false);
    const [showCart, setShowCart] = useState(false);
    const [showSearch, setShowSearch] = useState(false);
    const { cartCount } = useContext(Context);
    const navigate = useNavigate()

    const handleScroll = () => {
        const offset = window.scrollY;
        if (offset > 200) {
            setScrolled(true);
        }
        else {
            setScrolled(false)
        }
    };

    useEffect(() => {
        window.addEventListener("scroll", handleScroll)
    }, []);

    return (
        <>
            <header className={`main-header ${scrolled ? 'sticky-header' : ''}`}>
                <div className="header-content">
                    <ul className="left">
                        <li onClick={() => navigate("/")}>Home</li>
                        <li onClick={() => navigate("/about")}>About</li>
                        <li onClick={() => navigate("/login")}>Login</li>
                    </ul>

                    <div className="center" onClick={() => navigate("/")}>GOLOC.</div>

                    <div className="right">
                        <TbSearch onClick={() => setShowSearch(true)} />

                        <span className="cart-icon" onClick={() => setShowCart(true)}>
                            <CgShoppingCart />
                            {!!cartCount && <span>{cartCount}</span>}
                        </span>
                    </div>
                </div>
            </header>

            {showCart && <Cart setShowCart={setShowCart} />}
            {showSearch && <Search setShowSearch={setShowSearch} />}
        </>
    );
};

export default Header;

Header.scss

@import "../../css-config/mixins.scss";

.main-header {
    width: 100%;
    padding: 0 20px;
    background-color: #212121;
    color: white;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    z-index: 99;

    @include md {
        padding: 0 40px;
    }

    .header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 50px;
        max-width: 1200px;
        margin: 0 auto;

        @include md {
            height: 80px;
        }

        .left {
            list-style-type: none;
            display: none;
            gap: 25px;

            @include md {
                display: flex;
            }

            li {
                font-size: 14px;
                font-weight: 600;
                text-transform: uppercase;
                cursor: pointer;

                @include sm {
                    // visibility: hidden;
                }
            }
        }

        .center {
            font-size: 22px;
            font-weight: 700;
            cursor:

I’ve tried looking up solutions online and have experimented with various CSS properties and React libraries (such as react-icons), but I can’t seem to get the desired result. Any help or guidance would be greatly appreciated!

This is Github repository of this project: https://github.com/aditya9-2/GOLOC

React Error while importing Google Maps module

I have created a webpage using react that displays a real-time map using Google Maps API, an array of strings with geographical addresses is given. All those addresses are to reflect on Google Maps using a marker at their respective addresses. However, I am getting the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

Check the render method of Map.
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

Check the render method of Map.
at createFiberFromTypeAndProps (http://localhost:3001/static/js/bundle.js:47804:21)
at createFiberFromElement (http://localhost:3001/static/js/bundle.js:47825:19)
at reconcileSingleElement (http://localhost:3001/static/js/bundle.js:36916:27)
at reconcileChildFibers (http://localhost:3001/static/js/bundle.js:36966:39)
at reconcileChildren (http://localhost:3001/static/js/bundle.js:39908:32)
at mountIndeterminateComponent (http://localhost:3001/static/js/bundle.js:40745:9)
at beginWork (http://localhost:3001/static/js/bundle.js:41973:20)
at HTMLUnknownElement.callCallback (http://localhost:3001/static/js/bundle.js:26983:18)
at Object.invokeGuardedCallbackDev (http://localhost:3001/static/js/bundle.js:27027:20)
at invokeGuardedCallback (http://localhost:3001/static/js/bundle.js:27084:35)

My Map component code is:

import React, { useState, useEffect } from 'react';
import { MapContainer, Marker, GoogleApiWrapper } from 'google-maps-react';
import { Loader } from '@googlemaps/js-api-loader';

const Map = ({ google }) => {
  const [addresses, setAddresses] = useState([
    '1600 Amphitheatre Parkway, Mountain View, CA',
    '1 Infinite Loop, Cupertino, CA',
    '350 Fifth Avenue, New York, NY',
  ]);

  const [coordinates, setCoordinates] = useState([]);

  useEffect(() => {
    const loader = new Loader({
      apiKey: 'YOUR_API',
      version: 'weekly',
      libraries: ['places'],
    });

loader.load().then(() => {
  const geocoder = new google.maps.Geocoder();

  const fetchCoordinates = async () => {
    const coordinates = [];

    for (let i = 0; i < addresses.length; i++) {
      const result = await new Promise((resolve, reject) => {
        geocoder.geocode({ address: addresses[i] }, (result, status) => {
          if (status === 'OK') {
            resolve(result[0].geometry.location);
          } else {
            reject(status);
          }
        });
      });

      coordinates.push(result);
    }

    setCoordinates(coordinates);
  };

  fetchCoordinates();
});
}, [addresses, google.maps.Geocoder, google.maps.places]);

return (
  <MapContainer google={google} center={{ lat: 37.7749, lng: -122.4194 }} zoom={10}>
    {coordinates.map((coordinate, index) => (
      <Marker key={index} position={{ lat: coordinate.lat(), lng: coordinate.lng() }} />
    ))}
  </MapContainer>
);
};

export default GoogleApiWrapper({
  apiKey: 'YOUR_API',
})(Map);

My App.js code is:

import { GoogleApiWrapper } from 'google-maps-react';
import Map from './components/locator/loc';

function App(props) {
  return (
    <div className="App">
      <Map google={props.google} />
    </div>
  );
}

export default GoogleApiWrapper({
  apiKey: 'YOUR_API',
})(App);