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.

Encrypt and decrypt in Java in CRT mode like CryptoJS does

I am using this algorithm to encrypt from JavaScript using the CryptoJS library, the algorithm I need to implement is AES of type “CTR No Padding“:

var key = CryptoJS.enc.Hex.parse('F29BA22B55F9B229CC9C250E11FD4384');
var iv = CryptoJS.enc.Hex.parse('C160C947CD9FC273');

function encrypt(plainText) {

    return CryptoJS.AES.encrypt(
        plainText,
        key, {
            iv: iv,
            padding: CryptoJS.pad.NoPadding,
            mode: CryptoJS.mode.CTR
        }
    );
}

Now I need the function to decrypt this on the server with the Java language and also the function to decrypt, does anyone know the algorithms?

How to automatically pass javascript variable after the session is done to the mysql database?

I have searched for ways and I can’t implement it the way I want it’s result on my part.

if(snakeX < box || snakeX > 17 * box || snakeY < 3*box || snakeY > 17*box || collision(newHead,snake)){
                    clearInterval(game);
                    dead.play();
                    alert("You died.");
                    window.location.href = "home.php";
                }

I have this part of a JavaScript code to a snake game and I wanted to log the username and the score of that user, I was able to log the ‘username’ but this is the part where i’m stuck, logging the ‘score’ as well.

This is my score.php page

<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "highscore";

$con = mysqli_connect($host, $username, $password, $database);

$query = "SELECT * FROM user";
$highscore = $con->query($query) or die($con->connect_error);
$row = $highscore->fetch_assoc();
$total = $highscore->num_rows;
?>

//part of the html code
<?php do { ?>
        <tr>
          <td><?php echo $row["username"]; ?></td>
          <td><?php echo $row["score"]; ?></td>
        </tr>
      <?php  } while($row = $highscore->fetch_assoc()); ?>

The output will be ‘username’ while the score is 0 because there is no value yet but when the game starts, it will be updated once the game is finished. If the player had 13 scores then that would be added to the database which will then be shown onto the score.php page.

I have tried passing variables but it seemed thats not possible since client based and server based thing. Most solutions I found were functions with the button but mine has none and i still tried to implement it on my terms which was not successful

How to find a json value when you know the location to the key but how nested the value is changes

So I have an array with many different items in it. I know the names of the keys and I want to get
neededvalue, But the issue is that while I know that neededvalue is in item2.item3 in this case there may be a case where it is in item2.item3.item4.item5 or many other cases. I will always know the location of the neededvalue but it may be in multiple different json. So I was wondering if there way a way that I could find the value using a way that will allow me to use any array.

let list = {
  "item1": "test",
  "item2": {
    "item3": {
      "neededvalue": "neededvalue"
    }
  }
}

console.log(list);

console.log(list["item2"]["item3"]); // This gets the value but I don't want to have to add in brackets for ever value I want to check

//console.log(list["item2/item3"]) or console.log(list["item2.item3"]) both return undefined

How can i fit my table in Bootstrap off-canvas

i’m using bootstrap off-canvas and i put a table in the canvas
but the table isn’t fit in the canvas body

<div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasExample"
            aria-labelledby="offcanvasExampleLabel" style="width: min-content;">
            <div class="offcanvas-header">
                <h5 class="offcanvas-title text-center" id="offcanvasLabel">extra-infos</h5>
                <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas"
                    aria-label="Close"></button>
            </div>
            <div class="offcanvas-body">
                <div>
                    <table class="table table-striped status-table" style="max-width: 100vw; overflow-x: auto;">
                        <tr style="text-align: center;">
                            <th>status</th>
                            <th>info</th>
                        </tr>
                    </table>
                </div>
            </div>
        </div>

i create table completly with js file

document.addEventListener('DOMContentLoaded', () => { 
    for (let i = 0; i < 22; i++) {
        const tr = document.createElement('tr')
        tr.innerHTML = `<td class="uppercase" id="other_status_title${i}"></td>
        <td id="other_status_body${i}"></td>`
        document.querySelector('.status-table').appendChild(tr);
    }
})

most of answers about mine like problems say use overflow-x: auto; but donesn’t work…help

What are some good approach to convert a customer list with name, product, cost to a unique customer list with user, total product and spent?

Asking for feedback on my approach, no code required. Given a customer list – id, name, product, cost. I am trying to convert this list into a new list that is sorted in a way that it returns unique user, the user’s total number of products bought, and total spent.

My initial thought: Create a new object array, run a loop on each object and append user name, product, and cost, to the new array if user is not already in it. If user is already in the new array, find the user and increment the user’s total product by 1. Total spent will be added to the existing amount.

Language: JavaScript/React

I read that I could create an Object Array and push each Object (user) to it, and each user would have those 3 properties (excluding id because I assume its auto generated).

var sample = new Array();
sample.push(new Object());

Draft pseudo code for the the process:

let usersArr = new Array();
ogSet.forEach(userData=> {
   if (!(userData.name in usersArr[any].name)) {
      usersArr.push(userData)
   } else {
      usersArr[matchedUser].totalNumberOfProduct++;
      usersArr[matchedUser].totalSpent+= userData.cost
   }
}
...
// print out 
usersArr.map(user => {
   console.log(user.name)
   console.log(user.totalNumberOfProduct)
   console.log(user.totalSpent)
}

Original JSON array:

[
  {
    "id": "1",
    "name": "Bill",
    "product": "chair",
    "cost": "222"
  }.
  {
    "id": "2",
    "name": "Bill",
    "product": "sofa",
    "cost": "9999"
  },
  {
    "id": "3",
    "name": "Steve",
    "Product": "Monitor",
    "Cost": "555"
  }
]
...

Result:

[
  {
    "id": "1",
    "name": "Bill",
    "totalNumberOfProduct": "2",
    "totalSpent": "10221"
  }
]
...

Any feedback/suggestions on the way I tackle this? What are some ways to optimize speed and time? Algorithms and React specific methods are welcome.

Adding Google Ads Code in NextJS for Automatic Units

I’m working on a nextjs project and I have to implement the google AdSense code that is for automatic ads.

So, my google ad code is just this:

<script
  async
  src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_GOOGLE_ADSENSE}`}
  crossOrigin="anonymous"
/>

There is no specific ad unit code. Based on this script load, Google will automatically add the ads.

In such a case, how will I implement this in my NextJS project ensuring that the ads will continue to work with the route change?

Currently, the problem I see is that if I just place this in the _document.js head, the ads will load only on full reload. There are some tutorials describing how to implement google Adsense in NextJS, but they all describe the case when you have specific ad units created for Adsense, but not the case of automatic ads based on this script alone.

Will really appreciate any input on this.

ERORR after upgrading to Expo SDK 43 – Unable to resolve module @unimodules/core

After I upgraded from Expo SDK 40 to SDK 43 and did npm start I got this error "Unable to resolve module @unimodules/core".

I then checked my package.json and I didn’t have this package installed.

Any help will be greatly appreciated.

Full Error Stack Trace:

Warning: https://github.com/expo/react-native/archive/sdk-43.0.0.tar.gz is not a valid version. Version must be in the form of sdk-x.y.z. Please update your package.json file.
info Launching Dev Tools...
iOS Bundling failed 4235ms
Unable to resolve module @unimodules/core from /Users/user/path/to/project/node_modules/expo-linking/build/Linking.js: @unimodules/core could not be found within the project or in these directories:
  node_modules
  ../../../../node_modules

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
> 1 | import { Platform, UnavailabilityError } from '@unimodules/core';
    |                                                ^
  2 | import Constants from 'expo-constants';
  3 | import invariant from 'invariant';
  4 | import qs from 'qs';

Here is my package.json:

{
    "main": "node_modules/expo/AppEntry.js",
    "scripts": {
        "start": "expo start",
        "android": "expo start --android",
        "ios": "expo start --ios",
        "web": "expo start --web",
        "eject": "expo eject",
        "test": "jest"
    },
    "jest": {
        "preset": "jest-expo"
    },
    "dependencies": {
        "@react-native-async-storage/async-storage": "^1.13.3",
        "@react-native-community/art": "^1.2.0",
        "@react-native-community/datetimepicker": "3.0.4",
        "@react-native-community/masked-view": "0.1.10",
        "@react-native-community/netinfo": "5.9.7",
        "@react-native-community/push-notification-ios": "^1.2.2",
        "@react-native-community/slider": "3.0.3",
        "@react-navigation/native": "^5.1.4",
        "aws-amplify": "^3.3.1",
        "aws-amplify-react-native": "^4.2.6",
        "axios": "^0.19.2",
        "expo": "^43.0.0",
        "expo-app-loading": "^1.0.1",
        "expo-barcode-scanner": "~9.1.0",
        "expo-camera": "~9.1.0",
        "expo-constants": "~9.3.3",
        "expo-font": "~8.4.0",
        "expo-linking": "~2.0.1",
        "expo-mail-composer": "~9.0.0",
        "expo-notifications": "~0.8.2",
        "expo-permissions": "~10.0.0",
        "expo-secure-store": "~9.3.0",
        "expo-sqlite": "~8.5.0",
        "expo-updates": "~0.4.1",
        "expo-web-browser": "~8.6.0",
        "file-saver": "^2.0.2",
        "jsbarcode": "^3.11.3",
        "link": "^0.1.5",
        "qs": "^6.9.4",
        "react": "16.13.1",
        "react-dom": "16.13.1",
        "react-native": "https://github.com/expo/react-native/archive/sdk-43.0.0.tar.gz",
        "react-native-barcode-expo": "^1.1.1",
        "react-native-elements": "^3.2.0",
        "react-native-fs": "^2.16.6",
        "react-native-gesture-handler": "~1.8.0",
        "react-native-modal": "^11.5.6",
        "react-native-modal-datetime-picker": "^8.6.0",
        "react-native-paper": "^3.10.1",
        "react-native-push-notification": "^3.5.2",
        "react-native-reanimated": "~1.13.0",
        "react-native-router-flux": "^4.2.0",
        "react-native-safe-area-context": "3.1.9",
        "react-native-screens": "~2.15.2",
        "react-native-snap-carousel": "^3.9.1",
        "react-native-svg": "12.1.0",
        "react-native-web": "~0.13.12",
        "react-navigation-animated-switch": "^0.6.4",
        "react-navigation-drawer": "^2.4.11",
        "react-navigation-header-buttons": "^3.0.5",
        "react-router-dom": "^6.0.0-alpha.3"
    },
    "devDependencies": {
        "@babel/core": "^7.12.9",
        "@babel/runtime": "^7.9.2",
        "@react-native-community/eslint-config": "^0.0.7",
        "babel-jest": "^25.1.0",
        "babel-preset-expo": "8.5.1",
        "eslint": "^6.8.0",
        "expo-cli": "^4.12.8",
        "jest": "^25.5.4",
        "jest-expo": "~43.0.1",
        "metro-react-native-babel-preset": "^0.59.0",
        "react-test-renderer": "^16.13.1"
    },
    "private": true
}

I am facing this problem while running react application. how to solve this issue?

Error: Cannot find module ‘E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesbabel-loaderlibindex.js’
Require stack:

  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesloader-runnerlibloadLoader.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesloader-runnerlibLoaderRunner.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_moduleswebpacklibNormalModule.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_moduleswebpack-manifest-plugindistindex.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesreact-scriptsconfigwebpack.config.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesreact-scriptsscriptsbuild.js