My Wep Page Show Nothing When i Use Route

Hi Guys i want to create a web page that change pages with Navbars so i want to use bootstrap and react-route-dom to create this but before i use bootstrap its show nothing some kind of errors may occurred that i didn’t see i post my code here i just create one page and used it in App.jsx file but it’s show nothing but when i use home page as in App file’s return function it works pretty much good and its ok i can’t find any error it’s just say’s

No routes matched location “/”

here is my index.jsx file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/pages/App';
import reportWebVitals from './reportWebVitals';

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App/>,
    rootElement
)
;
reportWebVitals();

and here is the App.jsx file:

import '../../App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import React from "react";
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import Home from './home';
import HeaderBar from '../layout/HeaderBar';

function App() {
    return (
        <Router >
            <div>
                <HeaderBar/>
                <Routes>
                    <Route exact path='./pages/home' component ={Home}/>
                </Routes>
            </div>
        </Router>
    );
}

export default App;

And my Home file:

import React from 'react';

const Home = () => {
    return (
        <div className="container">
            <h1 className='display-5 text-uppercase py-5 text-center'>
               Welcome to JavaScript World
            </h1>
        </div>
    );
};

export default Home;

and finally this is my package.json:

{
  "name": "forex_trader",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.1.3",
    "react": "^17.0.2",
    "react-bootstrap": "^2.1.0",
    "react-dom": "^17.0.2",
    "react-router-bootstrap": "^0.26.0",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "styled-components": "^5.3.3",
    "web-vitals": "^2.1.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Firebase auth user is null even tho the user is clearly signed in?

Whenever i sign in a user and get redirected to the right component and then reload the browser, i get an error saying “TypeError: Cannot read properties of null (reading ’email’)” because i’m trying to render the logged in user that i can see at first but not after i refresh the page.

Is there anyone who can point out what i’m doing wrong?

My Context


useEffect(() => {
    onAuthStateChanged(auth, (data) => {
      if (data) {
        // User is signed in
        setisSignedIn(true);
        setCurrentUser(data);
        console.log('state = definitely signed in');
        console.log(currentUser);
      } else {
        // User is signed out
        setisSignedIn(false);
        console.log('state = definitely signed out');
      }
    });
  }, [isSignedIn, currentUser]);

Signing in a user

const signInUser = (props: ISignIn) => {
    signInWithEmailAndPassword(auth, props.email, props.password)
      .then((user) => {
        setFirebaseError(false);
        navigate('/swipe');
      })
      .catch((error) => {
        setFirebaseError(true);
        setErrorMsg({ errorMessage: error.message, errorCode: error.code });
        navigate('/');
      });
  };

Using currentUser

import { useAuth } from '../Utils/Contexs/AuthContext';

export const SwipeView = () => {
  const { currentUser, signOutUser } = useAuth();
  return (
    <div>
      <h1>Swipe View</h1>
      <p>The current user logged in: {currentUser.email}</p>
      <button onClick={() => signOutUser()}>Log out</button>
    </div>
  );
};

Console.log’s

Loggin the currentUser img

Console error

error msg on page reload img

How can I solve the following error when. when I try to make a connection to mongo I have the following error “TypeError: db.on is not a function”

En el siguiente código:

var mongoose = require('mongoose');

var mongoDB = 'mongodb://localhost/red_bicicletas';
mongoose.connect(mongoDB, {useNewUrlParser: true });
mongoose.Promise = global.Promise;
var db = mongoose.Connection;
db.on('error', console.error.bind(console, 'MongoDB connection error'));

TypeError: db.on is not a function

Unable to append element on a list item

I am unable to add a delete button to a list item in my code, pls I need assistance. Below is my code

function addDeleteBtn() {
  const ul = document.querySelector("ul");
  let li = document.querySelectorAll("li");
  let btn = document.createElement("button");
  const text = document.createTextNode("delete");
  btn.appendChild(text);
  for (const item of li) {
    li.append(btn);
  }

  ul.appendChild(li);
}
addDeleteBtn();

Add Cron Job to Function (node.js, express, react, mongodb)

Can you help me with cron function in my app? I’m stuck with it(

Here’s my “track.controller.js” and “server.js” with “multiTrack” function. multiTrack() function starts re-crawling process by users URL’s, it’s starts manually via button in users dashboard, but i want to add cron job to this function (multiTrack).
Imported “multiTrack” function in server.js file return “req is not defined”…
Thank u!

/———–server.js————/

const cron = require('node-cron');
const multiTrackfunc = require('./controllers/track.controller.js');

cron.schedule("*/60 * * * * *", () => {
  try {
    multiTrackfunc.multiTrack(req, res, next);
    console.log(`Re-crawling starts via cron`);
  }
  catch (err) {
    console.log(`${err} - in cron`);
  }
});

/———–server.js————/

/———–track.controller.js————/

const cron = require('node-cron')

exports.multiTrack = async (req, res, next) => {
  try {
    const { userId, createdTracks } = req.body;
    const trackIds = createdTracks.map((createdTrack) => createdTrack._id);

    const user = await User.findById(userId);
    if (!user) {
      return res.status(401).json({
        success: false,
        error: "User does not exist",
      });
    }

    try {
      // loop through each track START
      await new Promise((resolve, reject) => {
        createdTracks.forEach(async (createdTrack) => {
          const existingTrack = await Track.findById(createdTrack._id);
          if (!existingTrack) {
            reject();
          }
          
          // crawl Amazon product
          console.log(`${createdTrack.name} re-crawling starts`);
          const browser = await puppeteer.launch();
          const page = await browser.newPage();

          await page.goto(createdTrack.productUrl, {
            waitUntil: "networkidle2",
          });

          const crawledProduct = await page.evaluate(() => {
            let actualPrice = 0;

            const prepOurPrice = document.querySelector("span.woocommerce-Price-amount.amount").innerText;

            const image = document.querySelector(".woocommerce-product-gallery__image a img").src;
            const ourPrice = parseFloat(prepOurPrice.replace(/[^0-9.-]+/g, ""));
            const salePrice = document.querySelector("#priceblock_saleprice");
            const dealPrice = document.querySelector("#priceblock_dealprice");

            ///parseFloat(actualPrice.replace(/[^0-9.-]+/g, ""))

            if (ourPrice) {
              actualPrice = ourPrice;
            } else if (salePrice) {
              actualPrice = salePrice.innerText;
            } else if (dealPrice) {
              actualPrice = dealPrice.innerText;
            }

            return {
              image,
              actualPrice,
            };
          });
          console.log(`${createdTrack.name} re-crawling ends`);
          await browser.close();

          const { image, actualPrice } = crawledProduct;

          if (existingTrack.image !== image) {
            existingTrack.image = image;
            await existingTrack.save();
          }

          if (existingTrack.actualPrice !== actualPrice) {
            existingTrack.actualPrice = actualPrice;
            await existingTrack.save();
          }

          resolve();
        });
      });
      // loop through each track END
    } catch {
      return res.status(401).json({
        success: false,
        error: "Found invalid track id",
      });
    }

    const tracks = await Track.find({ _id: { $in: trackIds } });

    return res.status(201).json({
      success: true,
      data: tracks,
    });
  } catch (err) {
    console.log("crawling failed");
    return res.status(500).json({ error: err.message });
  }
};

/———–track.controller.js————/

Does writing onPress={onPress()} have anything to do with iife?

If I write onPress below, when I click the button, the console will write test. But if I write onPress(), it writes a test on the console as the page renders. Does writing onPress() have anything to do with iife? Is that why it works without being called the moment the page is rendered?

import React from 'react';
import { Button } from 'react-native';

const Screen = () => {

    const onPress = () =>{
        console.log('test')
    }

    return (
        <Button title='button' onPress={onPress()}/>
    )
};

export default Screen;

Regex match tens only

i need regex to match follow by tens only

example

10 true
25 false
20 true
45 false
50 true
100 true
110 true
125 false
1150 true
1155 false
4450 true

and thank you for your time

Three.js – How to merge multiple GLTF models into one?

I know there is the grouping method:

...

//after loading cube models
const group = new THREE.Group();
group.add( cube1 );
group.add( cube2 );
group.add( cube3 );

scene.add( group ); //This gives me 3 calls when rendering

but this doesn’t affect performance, it’s just to make things synthetically more clear.

I would like to merge cube1, cube2, & cube3 into a single object to reduce the number of calls in the scene

import { BufferGeometryUtils } from '../jsm/BufferGeometryUtils.js'; //gives error: BufferGeometryUtils.js doesn't export BufferGeometryUtils

var geometries = [];

geometries.push( cube1 );
geometries.push( cube2 );
geometries.push( cube3 );

const cubes = BufferGeometryUtils.mergeBufferGeometries( geometries );//doesn't work (outdated?)

scene.add( cubes );

I’ve followed some tutorials on BufferGeometryUtils, but they seem outdated since BufferGeometryUtils.js doesn’t export a BufferGeometryUtils constructor

I need to set line-height dynamically based on the font size which is controlled from backend

.heading {
  font-size: 6rem;
  line-height: 4rem;
}
<div class="heading">
  <p> Hero
  <br>
  <span style="font-size:20px">Banner</span>
  <br>
  Text
  </p>
</div>

Here the gap between the text “banner” and Hero is too much as the line height is constant here. How to manage this by adjusting the line height dynamically so that the text doesn’t have too much spacing involved. Also suggest any other best way to achieve this

How to get image data from a file input in react.js

I want to get the data from an input file in react. I have created a class with the data as a state. The idea is that the data should be updated every time the input changes. As this happens, an image should load with the input data.

The code below is what I have created, but it does not work.


class ImagePicker extends React.Component {
    constructor(props){
        super(props);

        this.state = {
            data: null
        }
    }

    handleDataChange = e => {
        this.setState({
            data: e.target.value
        })
    }

    render(){
        return(
            <div>
                <input type='file' onChange={this.handleDataChange} />
                <img src={this.state.data}></img>
            </div>
        )
    }
}

I don’t know what the problem is, could you help?

why validate both the post request and the database schema in the backend?

Abstract: should I use express-validator if I can validate data using mongoose schema?

I’m a front end developer, and I usually do some validation on the form before submitting. Now, I’ve started studying express.

One of the first things I did was receive a form and validate it using a library called express-validator, then the database operations were done. very simple, no big deal. However, after doing a project by myself I realized that mongoose itself could handle the errors, not only that, but it was quite easy to return these errors on the front, especially in the case of an api.

So that is my doubt, why validate this data so many times? I know that database schemas is not only to do that, but doing theses things once in front and twice in backend cause too many
repetition and may be a little hard to maintain.

Here goes a few lines of code only to illustrate the case. Don’t judge me, I’m still learning.

import mongoose from "mongoose";

const TaskSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 20,
  },

  description: {
    type: String,
    required: false,
  },

  completed: {
    type: Boolean,
    default: false,
  },

  date: {
    type: Date,
    default: Date.now,
  },
});

export default mongoose.model("Task", TaskSchema);
import taskModel from "../models/tasksModel";

export function createTask(req: express.Request, res: express.Response) {
  taskModel
    .create(req.body)
    .then((task) => res.status(201).send(task))
    .catch((err) => res.status(400).send(err));
}

How to close the side bar automatically when the li item is clicked

How do I close the side bar when someone clicks on the any of the li element. I have tried the code menuSidebar.display = "none" in the event listener, but this doesn’t seem to work

Thank you in advance

const menuButton = document.querySelectorAll("li");
const menuSidebar = document.getElementById("mySidebar");



/* Set the width of the sidebar to 250px and the left margin of the page content to 250px */
function openNav() {
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}

/* Set the width of the sidebar to 0 and the left margin of the page content to 0 */
function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft = "0";
}

// console.log(menuButton)
// console.log(mySidebar)
menuButton.addEventListener("click", ()=>{

  menuSidebar.display = "none";
  
  

});
:root {
  --title-font: "Titillium Web", sans-serif;
  --color-primary: #16e0bd;
  --color-secondary: #303030;
  --color-tertiary: #e0860b;
  --color-complimentary: #fc5817;
  --color-darkblack: #141414;
  --default: #ffffff;
}

.sidebar {
  height: 100%; /* 100% Full-height */
  width: 0; /* 0 width - change this with JavaScript */
  position: fixed; /* Stay in place */
  z-index: 1; /* Stay on top */
  top: 0;
  left: 0;
  background-color: var(--color-secondary); /* Black*/
  overflow-x: hidden; /* Disable horizontal scroll */
  padding-top: 60px; /* Place content 60px from the top */
  transition: 0.5s; /* 0.5 second transition effect to slide in the sidebar */
}

/* The sidebar links */
.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: var(--default);
  display: block;
  transition: 0.3s;
}

/* When you mouse over the navigation links, change their color */
.sidebar a:hover {
  color: var(--color-primary);
}

/* Position and style the close button (top right corner) */
.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

/* The button used to open the sidebar */
.openbtn {
  font-size: 20px;
  cursor: pointer;
  padding: 10px 15px;
  border: none;

  box-shadow: 3px 3px var(--color-complimentary),
    -0.1em -0.1em 0.4em var(--color-complimentary);
  background: linear-gradient(var(--default), var(--color-primary));
  color: var(--color-secondary);
}

/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
  transition: margin-left 0.5s; /* If you want a transition effect */
  padding: 20px;
}
   <div id="mySidebar" class="sidebar">
        <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
    <ul>
        <li><a href="#about-me">About Me</a></li>
        <li><a href="#skills">Skills</a></li>
        <li><a href="#projects">Projects</a></li>
        <li><a href="#experience">Experience</a></li>
        <li><a href="#education"> Education </a></li>
        <li> <a href="#contact">Contact</a></li>
    </ul>
      </div>
      
      <div id="main">
        <button class="openbtn" onclick="openNav()">&#9776; Open Menu</button>
      </div>