Trying to implement a basic search engine by hiding elements that aren’t results, but my code hides everything instead

I am trying to implement a very basic search engine. I iterate through an array of objects, checking if my search term matches some attributes, and if it does, I push each matching object onto an array. Now, in the rest of my code I have it so each object is represented by an element, and each element has a checkbox. Each checkbox has an ID that matches its object’s ID. So…. when I run the search function, I take the matches, correspond them to a checkbox through the IDs, and then I want to hide the elements that don’t match.

The problem is: it hides ALL the elements, instead of just the non-matchings IDs. Furthermore, it works when I want to manipulate the matches (say, surround them in a white border). Thank you for your time I look forward to your input.

Blake

function search() {
     var results = [];
     userData.forEach(task => {
         if (task.value.toLowerCase().includes(searchBar.value.toLowerCase()) 
             || task.note.toLowerCase().includes(searchBar.value.toLowerCase())) {
                 results.push(task.id);
             }
         })

         const checkboxes = document.querySelectorAll(".checkbox");

         checkboxes.forEach(checkbox => {
              if (!results.includes(checkbox.id)) {
                   checkbox.parentElement.style.display = "none";
              }
          })
     }
}

How to pass data between users and different browsers in React?

I am learning React and I’m making an app to better learn.
I created an app with Nodejs backend, Postgres DB and React frontend. I have different users and this is the case of what I need to do:

USER 1: Logs in mozilla and clicks a button on a page.
USER 2: Logs in firefox and sees a new button has appeared, because user in mozilla clicked it. Now he clicks this new button.
USER 1: Because USER 2 clicked new button, USER 1 sees something new displayed.

I am running it locally.

Do something when Promise outside then finished

Here is the code.

function getPromise():Promise<any> {
    let p = new Promise<any>((resolve, reject) => {
        //some logical
        resolve(data);
    });
    p.finally(()=>{ 
        //I want do something when outside then finished! 
        console.log("finally hit");
    });
    return p;
}

function doPromise():void {
    getPromise().then(data => { console.log("then hit"); });
}

But the finally runs before then. So how can I do something after outside then.

I do not want to add finally after then, because the promise called many places. so I want do it in one place.

child route not working in single spa react app

I have created react app using single spa and in my navigation bar React app i am showing which will take me to route page (‘localhost;9000/react’). I need to see how child route will work, I have created child route but if i clicked on childroute my main url isnt working it should show localhost;9000/react/childroute but it was not showing. Below is the code.

//root.component.js

import React from 'react';
import {BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";
import TestRoute from './TestRoute';
//import Reactapp from './Reactapp';
import ReactComponent from './ReactComponent';

export default function Root(props) {
  return (
    <Router baseName='/react'>
       <Switch>
          <Route path="/" component={ReactComponent} />  
          <Route path="/childroute" component={TestRoute} />  
       </Switch>
    </Router>
    
  )
}
//ReactComponent.js
import React from 'react';
import { Link } from 'react-router-dom';

const ReactComponent = () => {
    return(
        <div>
            ReactComponent
            <Link to='/childroute'>Child Route</Link>
        </div>
    )
}
export default ReactComponent;
//TestRoute.js

import React from 'react';

const TestRoute = () => {
    return(
        <div>
            TestPage
        </div>
    )
}
export default TestRoute;
//mf-demo-react.js

import React from "react";
import ReactDOM from "react-dom";
import singleSpaReact from "single-spa-react";
import Root from "./root.component";


const lifecycles = singleSpaReact({
  React,
  ReactDOM,
  rootComponent: Root,
  errorBoundary(err, info, props) {
    // Customize the root error boundary for your microfrontend here.
    return null;
  },
});

export const { bootstrap, mount, unmount } = lifecycles;

React hooks onClick icon change is not working

I want to change my icon onClick. But for some that is not working. What I have done is that, if there is submenuIcon1, it will be rendered. If someone clicks on the submenu option, it will render the submenuIcon2, based on the clicked variable.
Maybe I have done something wrong in the ternary operations. Please can someone help me regarding this?
Required Behavior
Whenever clicking on the submenu options, the icon will change. In this case it will be from submenuIcon1 to submenuIcon2.
Current Behavior
Clicking on the submenu options, the icon doesn’t change.
What I have done so far is that,

const SidebarTitle = () => {
  return (
    <>
      <Box
        width='200px'
        height='160px'
        textAlign='start'
        bgColor='#473198'
        px={5}
        borderRadius={2}
      >
        <Text fontSize='2xl' color='white' fontFamily='Fjord One'>
         Some title
        </Text>
      </Box>
    </>
  );
};

export default function Sidebar() {
  const [selectedSubMenu, setSelectedSubMenu] = useState("");
  const [clicked, setClicked] = useState(false);
  let location = useLocation();

  const handleClick = (title) => {
    setClicked(!clicked);
    if (title === selectedSubMenu) {
      setSelectedSubMenu("");
    } else {
      setSelectedSubMenu(title);
    }
  };

  return (
    <div>
      <Box
        display='flex'
        justifyContent='flex-start'
        alignItems='flex-start'
        mb={10}
      >
        <Box>
          <SidebarTitle />
          {sidebarItems.map((items) => {
            return (
              <Box
                width='200px'
                textAlign='start'
                cursor='pointer'
                onClick={() => {
                  handleClick(items.title);
                  
                }}
                fontFamily='Fjord One'
                boxShadow='lg'
                _hover={{
                  bgColor: "#1a2963",
                  color: "white",
                }}
                key={items.title}
              >
                <Link
                  to={items.url}
                  as={RouterLink}
                  width='100%'
                  _focus={{
                    boxShadow: "none",
                  }}
                  style={{ textDecoration: "none" }}
                >
                  <Box display='flex' justifyContent='space-between'>
                    <Text fontSize='xl' alignItems='flex-start'>
                      {items.title}
                    </Text>
                    {!!items.submenuIcon1 ? (
                      <Box alignItems='flex-start'>{items.submenuIcon1}</Box>
                    ) : clicked ? (
                      <Box alignItems='flex-start'>{items.submenuIcon2}</Box>
                    ) : (
                      <Box></Box>
                    )}
                  </Box>
                </Link>

                <Collapse
                  in={items.title === selectedSubMenu}
                  transition={{ enter: { delay: 0.1 }, exit: { delay: 0.1 } }}
                >
                  {items.subMenu?.map((item) => {
                    return (
                      <Box
                        bgColor='#e4e8e5'
                        boxShadow='md'
                        textAlign='start'
                        width='200px'
                        color='black'
                        _hover={{
                          bgColor: "#666666",
                          color: "white",
                        }}
                        key={item.title}
                        onClick={(event) => {
                          event.stopPropagation();
                        }}
                      >
                        <Link
                          to={item.url}
                          as={RouterLink}
                          width='100%'
                          _focus={{
                            boxShadow: "none",
                          }}
                          style={{ textDecoration: "none" }}
                        >
                          <Text fontFamily='Fjord One'>{item.title} </Text>
                        </Link>
                      </Box>
                    );
                  })}
                </Collapse>
              </Box>
            );
          })}
        </Box>

        <Box width='100%'>
          <TransitionGroup>
            <CSSTransition
              key={location.pathname}
              classNames='fade'
              timeout={300}
            >
              <Routes location={location.pathname}>
              //routes
              </Routes>
            </CSSTransition>
          </TransitionGroup>
        </Box>
      </Box>
    </div>
  );
}

How can i protect api from client?

I’m developing a site with react and nextjs. So in the API folder, I write some API endpoints. Now I don’t know how can I protect them from clients?
I want to use these APIs directly from the site. and I won’t the user be able to access API from his browser.
With jwt can I solve this problem? Or right solution is something else?

Insert slide number and total count between navigation arrows of owl carousel

I have an ngx owl carousel in my angular application with configurations as below:

const carouselOptions = {
 items: 1,
 dots: false,
 nav: true,
 navText: ["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"]
};

<owl-carousel [options]="carouselOptions" [carouselClasses]="['owl-theme','row','sliding']">
 <div class="item" *ngFor="let imgUrl of imageList; let i=index">
     <img src={{imgUrl}} alt="image slide" />
 </div>
</owl-carousel>

I have altered the default navigation arrows into custom arrows by using the navText key inside the owl carousel options. What I need is a way to inject the slide numbers as (current slide)/(total slide count) in between this navText arrows of owl carousel.

I tried to check the documentation but they dont have the option to add the step numbers as 1/7 between the navigation arrows.
I have implemented it in a angular application and would like to know a suitable solution to achieve using typescript?

Integrating node modules and JavaScript into our Web API controller calls

Our main backend server is a .net 5 web api project. I’m needing to integrate some javascript modules and javascript code into our functionality. I’m wanting to save on the time of rewriting these modules all into c# to access from our code. Is there any packages or methods to accomplish this or am I best of running a separate node server for this functionality?

webpack: transpile web workers in public folder

I’m next js for my project and it uses webpack 5 to compile typescript codes

I have several web worker scripts inside my public folder under path “/workers/**/*.worker.js”

I was wondering if I can write them in typescript too
or at least use babel to transpile them for es5 (for old browsers)

I know that anything under the “public” folder is served as is and as a file (like a CDN)

can I add a “workers” folder to my project and load them in the public path with webpack and next js?

How to bind react route to a shown dialog?

React Router has a good tutorial on Nested Routes.

And it’s pretty easy to create and understand.

However, I want to bind a route to a dialog.

Basically I have a list of customers at /customers and I have a New button on it. When it’s clicked a form is shown inside a dialog. I’m using Material UI. I want to change the route to /customers/create route and as the result of that route change show the dialog. This means that even if users hit F5 and refresh the page, they would still see the form shown in the dialog.

I can’t make it work. I created the nested <Route /> definition:

<Routes>
    <Route path='/customers' element={<Customers />}>
        <Route path='create' element={<CreateCustomer />} />
    </Route>
</Routes>

And I also inserted an <Outlet /> in my Customers.js:

import { Outlet } from 'react-router-dom'

const Customers = () => {
    const [dialogIsShown, setDialogIsShown] = useState(false);
    return <div>
        <Button onClick={() => setDialogIsShown(true)}>Create</Button>
        {* customer creation component is here, inside a dialog *}
        <Dilog open={dialogIsShown}>
            <CreateCustomer />
        </Dialog>
        {* other UI parts *}
        <Outlet />
    </div>
}

And when I click the new button, I use useNavigate to change route. But nothing happens.

I’m stuck here.

Any help is appreciated.

Updating a global variable from within a function

I am defining two variables:

var information;
var secondary_information;

I update these variables within my function:

async function fetchInfo() {
var num = Math.floor(Math.random() * 20 + 1);

const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${pos.current.coords.latitude},${pos.current.coords.longitude}&radius=12000&type=restaurant&key=${key}`;

await fetch(url)
  .then((response) => response.json())
  .then((data) => setSearchResponse(data))
  .then(console.log("api request fired."));

let place_id = searchResponse.results[num].place_id;


const secondary_url = `https://maps.googleapis.com/maps/api/place/details/json?fields=formatted_phone_number,opening_hours,formatted_address&place_id=${place_id}&key=${key}`;

await fetch(secondary_url)
  .then((response) => response.json())
  .then((data) => setsecondarySearchResponse(data))
  .then(console.log("secondary api request fired."));

 information = {
  name: searchResponse.results[num].name,
  open_now: searchResponse.results[num].opening_hours.open_now,
  rating: searchResponse.results[num].rating,
  price: searchResponse.results[num].price_level
};

 secondary_information = {
  phone_number: secondarySearchResponse.result.formatted_phone_number,
  daily_hours: secondarySearchResponse.result.opening_hours.weekday_text,
  address: secondarySearchResponse.result.formatted_address
};
}

When I console log the variables from within the function it works as intended.

I am trying to pass the variables down as props to a react component but it keeps passing an empty object instead:

return (
<div className="App">
  <Filters />
  <Button variant="primary" onClick={fetchInfo}>
    Randomizer
  </Button>{" "}
  <Result info={information} />
</div>
);

Additionally, I have no clue if this is the correct way I should be going about making these API calls and storing them into state but this is the way that made sense to me. Any feedback is greatly appreciated.

Getting a “Cannot read property of undefined” error

I’m trying to retrieve a random value (id) in a dynamic way to as to be able to find a specific product in the future (I’m following a nodejs course from udemy and the instructor is building an online commerce webpage as an example). I’ve reviewed the code the instructor has written on the video over and over to make sure the error’s not on the syntaxis end, it clearly isn’t since all’s written exactly as it shows in the videos yet I keep on getting the error, if anyone can help please! I’ve got no clue what it could be since at this point I understand the error could be on the logic end of it, I don’t know if maybe I’m not understanding the logic well and therefore the mistake i’m making isn’t obvious to me yet.

I’ll give the community some of the code so you guys can give me a hdn, thank you all !

Error thrown in console:

TypeError: Cannot read property 'productId' of undefined
    at exports.getProduct (C:UsersTOMASDesktopnode js MVCcontrollersshop.js:14:29)
    at Layer.handle [as handle_request] (C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterlayer.js:95:5)
    at next (C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterroute.js:137:13)
    at Route.dispatch (C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterroute.js:112:3)
    at Layer.handle [as handle_request] (C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterlayer.js:95:5)
    at C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterindex.js:281:22
    at param (C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterindex.js:354:14)
    at param (C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterindex.js:365:14)
    at Function.process_params (C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterindex.js:410:3)
    at next (C:UsersTOMASDesktopnode js MVCnode_modulesexpresslibrouterindex.js:275:10)

product.js file:

const fs = require('fs');
const path = require('path');

const p = path.join(
    path.dirname(process.mainModule.filename), 
    'data', 
    'products.json'
);

const getProductsFromFile = cb =>{
    fs.readFile(p, (err, fileContent) => {
        if(err) {
            cb([]);
        } else{
            cb(JSON.parse(fileContent));
        }
    });
}

module.exports = class Product {
    constructor(title, imageUrl, description, price) {
        this.title = title;
        this.imageUrl = imageUrl;
        this.description = description;
        this.price = price;
    }

    save() {
        this.id = Math.random().toString();
        getProductsFromFile(products => {
            products.push(this);
            fs.writeFile(p, JSON.stringify(products), (err) => {
                console.log(err);
            });
        });
    }

    static fetchAll(cb) {
       getProductsFromFile(cb);
    };
};

shop.js file:

const Product = require('../models/product');

exports.getProducts = (req, res, next) => {
  Product.fetchAll(products => {
    res.render('shop/product-list', {
      prods: products,
      pageTitle: 'All Products',
      path: '/products'
    });
  });
};

exports.getProduct = (res, req, next) => {
  const prodId = req.params.productId;
  console.log(prodId);
  res.redirect('/');
};

exports.getIndex = (req, res, next) => {
  Product.fetchAll(products => {
    res.render('shop/index', {
      prods: products,
      pageTitle: 'Shop',
      path: '/'
    });
  });
};

exports.getCart = (req, res, next) => {
  res.render('shop/cart', {
    path: '/cart',
    pageTitle: 'Your Cart'
  });
};

exports.getOrders = (req, res, next) => {
  res.render('shop/orders', {
    path: '/orders',
    pageTitle: 'Your Orders'
  });
};

exports.getCheckout = (req, res, next) => {
  res.render('shop/checkout', {
    path: '/checkout',
    pageTitle: 'Checkout'
  });
};

product-list.ejs file:

<%- include('../includes/head.ejs') %>
<link rel="stylesheet" href="/css/products.css">
</head>
<body>
<%- include('../includes/navigation.ejs') %>
    <main>
        <% if (prods.length > 0) {%>
        <div class="grid">
            <div class="card">
                <% for (let product of prods) { %>
                <article class="product-item">
                    <header class="card__header">
                        <h1 class="product__title"> <%= product.title %> </h1>
                    </header>
                    <div class="card__image">
                        <img src="<%= product.imageUrl %>", alt="">
                    </div>
                    <div class="card__content"> 
                        <h2 class="product__price"> $<%= product.price %> </h2>
                        <p class="product__description"> <%= product.description %> </p>
                    </div>
                    <div class="card__actions">
                        <a href="/products/<%= product.id %>" class="btn">Details</a>
                        <form action="/add-to-cart" method="POST">
                            <button class="btn"> Add to Cart </button>
                        </form>
                    </div> 
                </article>
                <% } %>
            </div>
        </div>
        <% } else { %>
            <h1>No Products</h1>
        <% } %>
    </main>
<%- include('../includes/end.ejs') %>

users.js file:

const path = require('path');

const express = require('express');

const shopController = require('../controllers/shop');

const router = express.Router();

router.get('/', shopController.getIndex);

router.get('/products', shopController.getProducts);

router.get('/products/:productId', shopController.getProduct);

router.get('/cart', shopController.getCart);

router.get('/orders', shopController.getOrders);

router.get('/checkout', shopController.getCheckout);

module.exports = router;

Is there a way to get all created context menus for a chrome extension?

I’m working on a personal chrome extension to help me out with a part-time job in which the background script calls an API that pulls email template data from my personal Notion account. These various email templates are given their own context menu which, when clicked, enters the template into the email reply.

On install, a single context menu is created called “Load Emails” which calls the API to retrieve the data and create the rest of the context menus, I was wondering if there is a way to retrieve all the already created context menu data inside the onClicked callback so that I can check if a context menu with that id is already created or not before creating a new one (if I add a new email template to my Notion database).

The IDs that I’m using for the created context menus are the page id’s from Notion so they are unique.

Looking at the documentation for context menus, the only options are create, remove, removeAll and update.

If there is a better way that I can achieve what I’m trying to do that works too.

How to fetch only the array from the form elements javascript

I used like this

var fData = $('.my_form').serializeArray();

which was my formdata, which contains all the form inputs done by the user.

the output of serializeArray will look like this

  1. name: ‘library[0][] ‘,value : ‘3’
  2. name: ‘library[0][] ‘,value : ‘5’
  3. name: ‘time’ , value: ‘2:30 PM’
  4. name: ‘bookname’, value: ‘space mission’
  5. name: ‘library[1][] ‘,value : ‘8’
  6. name: ‘detail_days[0][]’, value: ‘3’
    .
    .

like this, i need only library array alone from it, how to fetch it?

library = >{ ‘0’ =>{‘3′,’5’}, ‘1’ =>{‘8′,’10’}
like this i need to access this specific array alone

is there anything like serializeArray, forgetting only the specific array

calling externally componentDidMount() in react

I have a requirement in which once page gets loaded my dropdownlist should be populated. for that I put that code in componentDidMount().

  componentDidMount() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
      const countryData = res.data;
      this.setState({ countryData });
      alert(countryData);
    });
  }

I have one user input field in which person enter the value and save it into database. I want once user save that value into DB, my dropdown should get refresh and that value should be visible in the dropdown. so how can I externally call componentDidMount()? is there any better way to handle the same?
As of now list is getting refreshed only when user resfresh the page.