I have the required data in my database – but when trying to get the data, I am receiving error

Uncaught TypeError: Cannot read properties of undefined (reading ‘length’);
I am trying get the data from my mongodb database where I have two post stored. So, I must get
the tours.length at least 2 but instead I am receving the error as “Uncaught TypeError: Cannot read properties of undefined (reading ‘length’);”

import React, { useEffect } from "react";
import { MDBCol, MDBContainer, MDBRow, MDBTypography } from "mdb-react-ui-kit";
import { useDispatch, useSelector } from "react-redux";
import { getTours } from "../redux/features/tourSlice";

const Home = () => {
  const { tours, loading } = useSelector((state) => ({...state.tour}));

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getTours());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  console.log(tours);
  if (loading) {
    return <h2>Loading...</h2>;
  }



 return (
    <div
      style={{
        margin: "auto",
        padding: "15px",
        maxWidth: "1000px",
        alignContent: "center",
      }}
    >
  
  <MDBRow className="mt-5">
  {tours.length === 0 && (
      <MDBTypography className="text-center mb-0" tag="h2">
        No Tours Found
      </MDBTypography>
    )}

  <MDBCol>
    <MDBContainer>
      <MDBRow className="row-cols-1 row-cols-md-3 g-2">

      {tours && tours.map((item, index) => <h2>Tour Cards</h2>)}

      </MDBRow>
    </MDBContainer>
  </MDBCol>
      

  </MDBRow>


</div>

);
};

export default Home;

Recursive Component returning property undefined error in ReactJS

I am currently completing a frontend mentor challenge that involves building an interactive comment section. In this project, I want the users to be able to reply to each other continuously, and hence I have used a recursive component.

I am going to be pasting the code for the two offending components

Here is my code for the Comment component

// Comment.jsx
import { useEffect } from "react";
import ReplySection from "./ReplySection";

const Comment =({content, upvotes,image,username, isUser, replies, replyMethod, createdAt, id,upvoteMethod})=> {
   useEffect(()=> {
       console.log(replies)
   })
    return(
        
        <div className="comment-container" key = {id}>
            <div className="comment">
                <div className="upvotes-section">
                    <div className="upvotes">
                        <img id="upvote" src="/images/icon-plus.svg" onClick={()=> {
                            upvoteMethod(id, "upvote")
                        }}></img>
                        <h3>{upvotes}</h3>
                        <img id="downvote" src="/images/icon-minus.svg" onClick={()=> {
                            upvoteMethod(id, "downvote")

                        }}></img>

                    </div>
                </div>
                <div className="comment-side">
                    <div className="comment-header">
                        <div className="profile">
                            <img src={image}></img>
                            <h5>{username}</h5>
                            <h6 className="created-at">{createdAt}</h6>
                        </div>
                        <div className="options">
                            <img src={isUser ? "images/icon-delete.svg" : ""}></img>
                            <img src="/images/icon-reply.svg" onClick={()=> {
                                replyMethod(id)
                            }}></img>
                        </div>
                    </div>

                    <div className="comment-content">
                        <h5>{content}</h5>
                    </div>
                </div>
            
            </div>

            <ReplySection reply={replies} replyMethod={replyMethod} upvoteMethod={upvoteMethod}></ReplySection>

          
        </div>
    )

}

export default Comment;

and here is the Reply Section, where all the replies for each comment are stored.

import { useEffect } from "react";
import Comment from "./Comment";
const ReplySection=({reply,replyMethod,upvoteMethod})=> {
    return(
        <div className="reply-section">
           {reply.map(el=> {
               return(
                 <Comment content = {el.content} upvotes={el.score} id={el.id} upvoteMethod = {upvoteMethod} image = {el.user.image.png} username = {el.user.username} replyMethod = {replyMethod} replies = {el.replies} createdAt={el.createdAt} isUser={ el.user.username === "juliusomo"? true :false} key={el.id}></Comment>
                  
               )
           })}
        </div>
    )

}

export default ReplySection;

when I open live server, I ended up getting this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')
    at ReplySection (ReplySection.jsx:5:1)
    at renderWithHooks (react-dom.development.js:16398:1)
    at mountIndeterminateComponent (react-dom.development.js:21144:1)
    at beginWork (react-dom.development.js:22634:1)
    at beginWork$1 (react-dom.development.js:27597:1)
    at performUnitOfWork (react-dom.development.js:26733:1)
    at workLoopSync (react-dom.development.js:26642:1)
    at renderRootSync (react-dom.development.js:26611:1)
    at recoverFromConcurrentError (react-dom.development.js:26020:1)
    at performSyncWorkOnRoot (react-dom.development.js:26264:1)

strangely enough, when I console log the replies array in my Comment component, it just shows an array, nothing out of the ordinary.

I am stumped on this problem and would like to know what’s going on. Help would be greatly appreciated.

Need Javascript Regex code for String matching

I am newbie. I have a requirement to sort an array of strings having certain characters.

All Strings are words of length 5. Like –
Icons
Weary
India
Flips

[a] will return India as it has an a
[ai] will return Icons,Weary,India and Flips as it contains at least one a or one i

But I am looking for a RegEx like [aii] which should only return India because India has both a and i and i appears twice.

Thank you in advance

How to share the user state (profile) in all my application using NGXS

Kind regards, my doubt is based on how to share the value of the profile in different parts of my app, example: A user logs in and the profile property is filled with the user’s data, but then in other components of my app (chat , setting, …) I want to get that profile, should I create a new selector in each class state? should inherit from AuthState? which is the most conveenter image description herenient flow to share the profile throughout my application knowing that each part of it will have its own state (chatState, settingState,…). Thank you very much.

pure css/js/html responsive sidebar image for any dimensions (wide/tall/huge)

I am working on a responsive web sidebar with pure html/css/javascript.

I want to include an image in my sidebar, and that image can be anything, so there are three image resolution types I am trying to test with to make sure they are displayed responsively, and that when the user resizes the window, the image will fill in any remaining availalbe free space height.

These are the three resolution types I am trying to cover:

I have all three of these image inputs as html <img> elements, and can comment them in and out to test how responsive they act. I have tried to implement responsive image style css but it does not work for my first example, the incredibly tall image.

In my jsfiddle below, the image is at the bottom of the sidebar, but clips, I’m trying to make it only take up the available sidebar space

https://jsfiddle.net/martinradio/b5rw9f0s/2/

var isSidebarOpen = false;

function sideNavClicked(){
    console.log('sideNavClicked()')
    isSidebarOpen ? closeNav() : openNav();
}

function openNav() {
console.log('openNav')
    isSidebarOpen=true;
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}

function closeNav() {
console.log('closeNav')
    isSidebarOpen=false;
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";
}
body {
  font-family: "Lato", sans-serif;
}

.sidebar {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebar a:hover {
  color: #f1f1f1;
}

.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.openbtn {
  font-size: 20px;
  cursor: pointer;
  background-color: #111;
  color: white;
  padding: 10px 15px;
  border: none;
}

.openbtn:hover {
  background-color: #444;
}

#main {
  transition: margin-left .5s;
  padding: 16px;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
  .sidebar {padding-top: 15px;}
  .sidebar a {font-size: 18px;}
}


/* image css */
.content {
    background-color: yellow;    
}

.row {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -webkit-box-orient: horizontal; 
    -moz-box-orient: horizontal;
    box-orient: horizontal;
    flex-direction: row;

    -webkit-box-pack: center;
    -moz-box-pack: center;
    box-pack: center;
    justify-content: center;

    -webkit-box-align: center;
    -moz-box-align: center;
    box-align: center;  
    align-items: center;

    background-color: red;

}

.cell {
    -webkit-box-flex: 1;
    -moz-box-flex: 1;
    box-flex: 1;
    -webkit-flex: 1 1 auto;
    flex: 1 1 auto; 

    padding: 0px;
    margin: 0px;

    background-color: green;
    border: 1px solid red;
    text-align: center;
}
img {max-width:100%;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

<div id="mySidebar" class="sidebar">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
  
  <!-- image -->
  <div class="content">
  <div class="row"> 
    
    <div alt='tall' class="cell">
      <img alt='tall' src="https://i.imgur.com/6A4NudP.png"/>
    </div>
    
    <!--
    <div alt='big' class="cell">
      <img alt='big' src="https://i.imgur.com/97NzyII.png"/>
    </div>
    -->
    
    <!--
    <div alt='wide' class="cell">
      <img alt='wide' src="https://i.imgur.com/UqFxOza.png"/>
    </div>
    -->
    
  </div>
</div>
  
</div>

<div id="main">
  <button class="openbtn" onclick="sideNavClicked()">☰</button>  
  <h2>Collapsed Sidebar</h2>
  <p>Click on the hamburger menu/bar icon to open the sidebar, and push this content to the right.</p>
</div>


</body>
</html> 

Mongo DB Search and sort not working – collection.find(…).sort is not a function

I have a use case to search for a particular string on one field and return the results in sorted order based on another field.
The below is the function I’m using in Node.js and the error being thrown.

router.get("/getappts/:username", function (req, res) {
  console.log(req.params.username)
  collection.find({ username: req.params.username }).sort( {date : 1} ), function (err, appointments) {
    if (err) throw err;
    
    console.log(appointments)
    res.json(appointments);
  } 
})

Error – collection.find(…).sort is not a function.

Not sure how to model the query.

But the below query on Mongo Compass seems to work fine –

enter image description here

Unauthenticated error in the browser, but it perfectly works on postman

I have this piece of code that works fine on postman when I set the header to the token generated from the access token. but when I’m using the same piece of code on the browser when I log in, I get the authorization access, but the moment I manually input the new router, I get an unauthorized error.

const verifyToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
if (authHeader) {
    const token = authHeader.split(" ")[1];
    jwt.verify(token, process.env.jwtToken, (err, user) => {
        if (err) {
            res.status(500).json("Invalid Token");
        } else {
            req.user = user;
            next();
        }
    });
} else {
    res.status(500).json("You are not authenticated");
}

};

const verifyAndAuth = (req, res, next) => {
verifyToken(req, res, () => {
    if (req.params.id === req.user.id) {
        next();
    } else {
        res.status(500).json("You are not verified");
    }
});

};

the verifyAndAuth middleware is added to every route for example:

router.get("/", admin, async (req, res) => {
try {
    const noteData = await users.find();
    res.status(200).json(noteData)
} catch (err) {
    res.status(500).json(err)
}

});

Trying to splice an array one by one randomly until empty

This is a javascript for a scratch card game. So far I want to make it to have one user can only scratch the game once. There are 3 var for example so it will be like after 3 user scratch it, the array should be empty and the alert function will call out. Now I can only use loop to empty the array and I can’t figure out how to make it splice one by one per attempt.

var promoCode = '';
var bg1 = 'https://cdn.pixabay.com/photo/2020/06/01/22/23/eye-5248678__340.jpg';
var bg2 = 'http://farm5.static.flickr.com/4017/4717107886_dcc1270a65_b.jpg';
var bg3 = 'http://images6.fanpop.com/image/photos/41500000/adorable-puppies-cute-puppies-41538743-590-393.jpg';


var bgArr = [bg1, bg2, bg3];
  for(var i=0; i <1; i++){
selectBG = bgArr.splice(Math.floor(Math.random() * bgArr.length), 1)[0];
console.log(selectBG);
}


if (selectBG === bg1) {
  promoCode = 'SCRATCH400';
  var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
  audio.play();
  
} else if (selectBG === bg2) {
  promoCode = 'SCRATCH500';
  var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
  audio.play();
  
} else if (selectBG === bg3) {
  promoCode = 'SCRATCH600';
  var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
  audio.play();
  
} else if (bgArr.length === 0) {
  alert("No more voucher");
}


$('#promo').wScratchPad({
  // the size of the eraser
  size: 70,
  // the randomized scratch image   
  bg: selectBG,
  // give real-time updates
  realtime: true,
  // The overlay image
  fg: 'https://cdn.glitch.com/2c225b7b-6134-4f2b-9842-1d5d060d9cd4%2Foverlay.png',
  // The cursor (coin) image
  'cursor': 'url("https://cdn.glitch.com/2c225b7b-6134-4f2b-9842-1d5d060d9cd4%2Fcoin1.png") 30 30, default',

  scratchMove: function(e, percent) {
    console.log(percent);
    console.log(promoCode);

    // Show the plain-text promo code and call-to-action when the scratch area is 50% scratched
    if ((percent > 50) && (promoCode != '')) {
      $('.promo-container').show();
      $('body').removeClass('not-selectable');
      $('.promo-code').html('Your code is: ' + promoCode);
      
    }
  }
});

Is it possible just adding value in the if statment no checking condition [duplicate]

I am actually following a course of javascript and came across a piece of code where he say if true then do {} but what is true not specifically explained

//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
function letsLearnScope() {
  console.log(a, b) // JavaScript 10, accessible
  if (true) {
    let a = 'Python'
    let b = 100
    console.log(a, b) // Python 100
  }
  console.log(a, b)
}
letsLearnScope()
console.log(a, b) // JavaScript 10, accessible

The issue is this code working fine not giving error my question what true he is talking about

React can the callback function of useState increase performance?

With Callback

  const [state, setState] = useState(() => {
    email: '',
    password: '',
  });

  const handleStateChange = useCallback((stateName) => (e) => {
    setState((prevState) => ({
      ...prevState,
      [stateName]: e.target.value,
    }));
  }, []);

Without Callback

const [state, setState] = useState(() => {
    email: '',
    password: '',
  });

  const handleStateChange = useCallback((stateName) => (e) => {
    setState({
      ...state,
      [stateName]: e.target.value,
    });
  }, [stateName]);

It’s possible to use dispatch of useState without appending dependencies through the callback function.

I think it reduces dependencies so that helps for performance.

Is this correct?

In addition, sometimes, the callback argument doesn’t get current state correctly. I don’t know why it doesn’t work.

Why are the unicode numbers not being selected in regex

I am creating a discord command to create a poll but for whatever reason, the emoji 1️⃣ wont pick up.

MY CODE

const EMOJIREGEX = /((?<!\)<:[^:]+:(d+)>)|p{Emoji_Presentation}|p{Extended_Pictographic}/gmu;



  let element='1️⃣some text➡️'
        if (element.match(EMOJIREGEX)) {
          let emojis = element.match(EMOJIREGEX)
          console.log(emojis)
        
        } else {
        console.log('no emojis')
         
        }

OUTPUT

[ '➡' ]

I’ve tried several other emojis and the 0-9 ones are the only ones that wont work (which is unfortunate because they’re prolly the most important ones)

Any help would be great, thanks!