Javascript – map is not a function

I’m having an odd issue. So I’m using fetch api to get some static data from an api endpoint to get some data. When I then try to map over the data it tells me map is not a function. So I’m making this in react. Also I haven’t used fetch too much so maybe I’m missing something easy.

Here is the fetchData code where I get the data no problem and then using setScanData(resData) for some state.

const fetchData = async () => {
  const res = await fetch(baseURL + apiAddOn);
  const resData = await res.json();
  setScanData(resData)
}

Here is how the resData comes back.

[
    {
        "teamName": "Team 1",
        "date": "2021-01-19",
        "tasksAWeek": 14
    },
    {
        "teamName": "Team 2",
        "date": "2021-01-19",
        "tasksAWeek": 21
    },
    {
        "teamName": "Team 3",
        "date": "2021-01-19",
        "tasksAWeek": 36
    }
]

And then here is how I try to map over the data and where is gives me the map is not a function error.

 {scanData.map((data) => {
        <div key={`${data.teamName}-${data.date}`}>
            <p>Team Name: {data.teamName}</p>
            <p>Date: {data.date}</p>
            <p>Scans a Week: {data.scansAWeek}</p>
            <p>Total Scans: {data.totalScans}</p>
        </div>
    })}

But ye so I’m not too sure where I’m going wrong with this. Any help would be useful.

how to update attributes of an object from user input?

(i am new to JS and i am facing a problem with getting user input in one of the functions)

i am writing a code where i have three classes (book, donor, bookCatalog)

class ‘book’ and ‘donor’ have only constructors while ‘bookCatalog’ have some functions like addbook(), addDonor() etc.

in one of the functions (in bookCatalog) i’m supposed to change the donor’s information, the function receives the donor id then search in a list of donors with that id and updates the donor attributes (like name,phone etc.)

i am supposed to test these methods in a new file but the problem is i dont know how to get the input from the user
i tried using prompt but i got an error “prompt is not defined”

Q. should the prompt be in the test file or inside ‘updateDonor’ function?

class bookCatalog:

export class BookCatalog{
    constructor(books, donors) {
        this.books = []
        this.donors = []
    }

updateDonor(donorId){
        const Id = prompt("enter donor ID: ")
        const firstname = prompt("enter first name: ")
        const lastname = prompt("enter lastname: ")
        const phone =  prompt("enter phone number: ")
        const street = prompt("enter street: ")
        const city = prompt("enter city: ")
        const email = prompt("enter email: ")
        const password = prompt("enter password: ")

        this.donors = this.donors.map(d =>{
            if(d.donorId === donorId){
                return {...d,
                    donorId: Id,
                    firstname: firstname,
                    lastname: lastname,
                    phone: phone,
                    street: street,
                    city: city,
                    email: email,
                    password: password
                }
            }
            return d
        })
    }
}

test file:

import {BookCatalog} from "./BookCatalog.js";
import {Donor} from "./Donor.js";

let catalog = new BookCatalog();
let donor1 = new Donor(0.1,"alex","A",726836,"st","chicago","[email protected]","123456")
catalog.addDonor(donor1)

console.log("donor 1 information after updating: ")
console.log(catalog.updateDonor(0.1))


How to set first value in “useState” function to true or false with “useEffect” function React

I am running into a problem with my current code. The code below is supposed to grab a JSON response from my backend and set “data” in the useState function to true or false based on the backend’s response. The issue I am having is that when I click on my button to redirect me to the page it must first go through this protected route in my react router. So it will run this script but the value of ‘data’ never changes. However, my console.log will output the correct boolean based on the JSON response sent from the backend. I am confused on how I can actually grab my JSON response on page load and set it to ‘data’ with useEffect? From my understanding, useEffect will only update my useState ‘data’ when the DOM re-renders.

In short, I want data to = true on page render by checking the JSON response from my backend using axios and if it is true I want to be redirected to the outlet.

I appreciate any help thanks.

 const useAuth = () => {
    
      const [data, setData] = useState(false);
    
      useEffect(() => {
        const fetchAuthData = async () => {
          await axios.get('http://localhost:5000/auth')
            .then(resp => {
              console.log(resp.data)
              setData(resp.data);
            })
            .catch(err => {
              console.log(err);
              setData(false)
            });
    
    
        };
    
        fetchAuthData()
      }, []);
    
      console.log(data)
      // Logic to check if backEndResponse is true or false
      if (data === true) {
        const authorized = { loggedIn: true }
        return authorized && authorized.loggedIn;
      } else {
        const authorized = { loggedIn: false }
        return authorized && authorized.loggedIn;
      }
    
    };
    
    
    const ProtectedRoutes = () => {
      const isAuth = useAuth();
      return isAuth ? <Outlet/> : <Navigate to="/login" />;
    }

How get data from component in another component?

I’m trying to pass data to the callback function, but for some reason it breaks everything and I always get the timer by zeros:

const [timerData, setTimerData] = useState({
    seconds: 0
    minutes: 0
    hours: 0
  });

  const callBackTimer = data => setTimerData(data);

  useEffect(() => {
    console log(timerData);
  },[timerData])

  const Timer = ({callback, data}) => {
    const [seconds, setSeconds] = useState(data.seconds);
    const [minutes, setMinutes] = useState(data.minutes);
    const [hours, setHours] = useState(data.hours);
    const [isActive, setIsActive] = useState(clients.length > 1);

    let toggle = () => {
      setIsActive(!isActive)
    }

    let reset = () => {
      setSeconds(0);
      setIsActive(false);
    }

    useEffect(() => {
      let interval = null;
      if (isActive) {
        interval = setInterval(() => {
          if(seconds < 60) setSeconds(seconds => seconds + 1);
          else {
            setSeconds(0);
            if(minutes < 60) setMinutes(minutes => minutes + 1);
            else {
              setMinutes(0);
              setHours(hours => hours + 1);
            }
          }
          console.log({hours, minutes, seconds});
          callback({hours, minutes, seconds});
        }, 1000);
      } else if (!isActive && seconds !== 0) {
        clearInterval(interval);
      }
      return() => clearInterval(interval);
    }, [isActive, seconds, minutes, hours, timerData]);

    return(
        <div className={'timer'}>
          <h1>{seconds}</h1>
          <h1>{minutes}</h1>
          <h1>{hours}</h1>
        </div>
    )
  }

My callback function not working and timer not updated.

I call the timer like this:

<Timer callback={callBackTimer} data={timerData}/>

Please tell me what I did wrong. Thanks.

My project run properly in my c-drive. but copy this project file to another drive . When try to run its give this error. in c drive it worked good

./node_modules/@pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js
Error: [BABEL] F:Programming herop-hero course-(Main-course)milestone-12( doctor portal project)module-69-74(final project)doctor-portal-client-sitenode_modules@pmmmwhreact-refresh-webpack-pluginclientReactRefreshEntry.js: Cannot find module ‘F:Programming herop-hero course-(Main-course)milestone-12( doctor portal project)module-69-74(final project)doctor-portal-client-sitenode_modulesbabel-preset-react-appnode_modules@babelplugin-proposal-nullish-coalescing-operatorlibindex.js’. Please verify that the package.json has a valid “main” entry (While processing: “F:Programming herop-hero course-(Main-course)milestone-12( doctor portal project)module-69-74(final project)doctor-portal-client-sitenode_modulesbabel-preset-react-appdependencies.js”)

DiscordAPIError: Invalid Form Body message_id: Value “10s” is not snowflake

My code

I have a discord bot using djs with over 216 commands and i was trynna make a giveaway command without using discord-giveways npm

I have tried asking many many people for solutions and everyone has said that they dont know. I looked on google, not a single useful answer. I would appreciate it if someone could help me out on this

I get this error:

 throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Invalid Form Body
message_id: Value "10s" is not snowflake.

This happens when i run the giveaway. it works fine till it ends, once it ends this error occurs before i even try to reroll the giveaway

if i change the args from 1 and 2 to 2 and 3 it will say unknown message

  if(args[1].toLowerCase() === "reroll" && message.member.permissions.has("MANAGE_GUILD") || message.member.roles.cache.find(r=> r.name === "Giveaway Manager")) {
                                let messageID = message.channel.messages.fetch(args[2])
                                if(!messageID) return message.reply({embeds: [new Discord.MessageEmbed()
                                    .setColor(colours.pink)
                                    .setTitle(`${emotes.Error} MISSING ARGUEMENT`)
                                    .setDescription("*Bakaa~* You need to provide a message ID for me to reroll!")
                                    .setTimestamp()
                                ], allowedMentions: {repliedUser: false}
                            })
                            if(messageID) {
                                for (let i = 0; i < winnerCount; i++) {
                                index2 = Math.floor(Math.random() * (participants.length -1));
                                if(!RerolledWinners.includes(participants[index2])) {
                                    RerolledWinners.push(participants[index2]);
                                } else i--;
                            }

Image to show how far it goes till it causes the error

React – Upload Build to Netlify Fail – Black Screen

I am uploading a build for the very first time and I am using Netlify for it.

I’ve linked my account to GitHub and uploaded my project from there. For the build command I entered “npm run build” and for the publish directory “build“. However once the website deployed all I have is a black screen. What can I do to fix it ?

Here is also my package.json:

 {
  "name": "netflix_clone",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^0.25.0",
    "firebase": "^9.6.3",
    "framer-motion": "^4.1.17",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-icons": "^4.3.1",
    "react-router-dom": "^6.0.2",
    "react-scripts": "4.0.3",
    "router-dom": "^2.2.6",
    "sass": "^1.44.0",
    "swiper": "^7.4.1",
    "web-vitals": "^1.1.2"
  },
  "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"
    ]
  }
}

Thank you for your help.

How to pause the video when popup is closed in bootstrap?

I am using Bootstrap 5 Modal Popup, I embedded an Iframe in the popup box and everything is working fine but the thing is that When I am closing the Popup the video is not stoping/pausing and even the Popup is closed it is still Running in the background and I tried to stop it via Jquery but don’t know why it is not working.
So can anyone please tell me how to pause/stop the video when the popup is closed?

$(document).ready(function() {
  var url = $("#how-it-works-video").attr('src');

  $("#exampleModal").on('hide', function() {
    $("#how-it-works-video").attr('src', '');
  });

  $("#exampleModal").on('show', function() {
    $("#how-it-works-video").attr('src', url);
  });
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>





<!-- Button trigger modal -->
<a class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#exampleModal">
  How it works
</a>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">

  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      
      
      <div class="modal-body">      
      <iframe id="how-it-works-video" width="100%" height="100%" src="https://www.youtube.com/embed/MC7reQGDBI0" title="YouTube video player" frameborder="5" allowfullscreen></iframe>
      </div>


    </div>
  </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

Error Can’t resolve ‘react-scroll’ module in react

Module not found: Error: Can’t resolve ‘react-scroll’ in
‘D:ProjectsTemp Projectsmy-appsrccomponents’ assets by path
static/ 31.8 MiB

ERROR in ./src/components/ButtonElements.js 4:0-36 Module not found:
Error: Can’t resolve ‘react-scroll’ in ‘D:ProjectsTemp
Projectsmy-appsrccomponents’ @
./src/components/HeroSection/index.js 8:0-43 52:37-43 @
./src/pages/index.js 7:0-52 40:35-46 @ ./src/App.js 6:0-27 17:19-23
36:35-39 @ ./src/index.js 6:0-24 9:33-36

enter image description here

import styled from "styled-components";
import {Link} from 'react-scroll';


export const Button = styled.button`
    border-radius: 50px;
    background: ${({primary}) => (primary ? '#01BF71' : '#010606') };
    white-space: nowrap;
    padding: ${({big}) => (big ? '14px 48px' : '12px 30px')};
    color: ${({dark}) => (dark ? '#010606' : '#fff')};
    font-size: ${({fontBig}) => (fontBig ? '20px' : '16px')};
    outline: none;
    border: none;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.2s ease-in-out;

    &:hover {
        transition: all 0.2s ease-in-out;
        background: ${({primary}) => (primary ? '#fff' : '#01BF71') };
    }


`;

react-icons/fa

import React from "react";
import { FaFacebook, FaInstagram, FaYoutube, FaTwitter, FaLinkedin } from "react-icons/fa";
import { animateScroll as scroll } from "react-scroll/modules";

import { 
    FooterContainer,
    FooterWrap,
    FooterLinksContainer,
    FooterLinksWrapper,
    FooterLinksItems,
    FooterLinkTitle,
    FooterLink,
    SocialMedia,
    SocialMediaWrap,
    SocialLogo,
    WebsiteRights,
    SocialIcons,
    SocialIconLink,


} from "./FooterElements";

**

App.js

import React from 'react';
import './App.css';
import Home from './pages';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import SigninPage from './pages/signin';
import Navbar from './components/Navbar';




function App() {
  return (
    <Router>
      
      <Routes>
        <Route path= "/" component={Home} exact />
        <Route path= "/signin" component={SigninPage} exact />
      </Routes>
      <Home />
     
    </Router>
  );
}

export default App;

**

MongoDB: Aggerate query is not passing value inside the function

I am facing a problem with the Mongoose aggregation query. I have the following schema which is an array of objects and contains the endDate value.

[
  {
    "id": 1,
    "endDate": "2022-02-28T19:00:00.000Z"
  },
  {
    "id": 2,
    "endDate": "2022-02-24T19:00:00.000Z"
  },
  {
    "id": 3,
    "endDate": "2022-02-25T19:00:00.000Z"
  }
]

So, during the aggregation result, I have to add a new field name isPast, It contains the boolean value, and perform the calculation to check if the endDate is passed or not. If it is already passed, then isPast will be true otherwise false.

I am using isBefore function from the moment library which returns the boolean. But inside this function facing a problem regarding passing the endDate value. $endDate is passing as a string, not a value.

Is there a way to pass the value of endDate inside the function?

const todayDate = moment(new Date()).format("YYYY-MM-DD");

db.collection.aggregate([
  {
    $addFields: {
      "isPast": moment('$endDate', 'YYYY-MM-DD').isBefore(todayDate)
    },
    
  },
  
])

Hugo form issues with javascript

I got a weird error blocking my ability in Hugo to submit a booking form ( even after I upgraded from 0.88 to 0.92 ) on Netlify.

The console error is

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
and the culprit is this bit of baseof.html:

I am not keen to remove the IE references as unfortunately many customers may use it.
If I delete those I get another problem:

404 page not found
with this javascript error even though I have 404.html in

Uncaught (in promise) SyntaxError: Unexpected token p in JSON at position 4
Any ideas how best to deal with this? This appears more JS related than Hugo but it all comes with the engine.

Thanks
Alfred

how to navigate on pages using material ui in reactjs

I am making a drawer for my dashboard using material-Ui, I have faced an issue navigating on my pages

first, I wanna share my app. js and here I have product route

<Provider store={store}>
<BrowserRouter>
    < Routes>
      <Route exact path='/' element={<Login/>} />
      <Route exact path='/dashboard' element={<Dashboard/>} />
      <Route exact path='/product' element={<Product/>}/>
    </Routes>
  </BrowserRouter>
</Provider>

here is my dashboard code:

In this code, I am an object who has an onClick function for navigation on pages

  const listItem = [
    {
      text:'Dashboard',
      onclick:()=>navigate("/dashboard")
    }, 
    {
      text:'Prdocut',
      onclick:()=>navigate("/product")
    } 
  ]

here is my list of who is rendering the items

<List>
  {listItem.map((item, index) => {
    const { text,onClick} = item;
      return (
         <ListItem button key={text} onClick={onClick}>
            <ListItemText primary={text} />
         </ListItem>
        )})}
</List>

but it’s not navigation my my product page