Why is using AnimatePresence from framer motion causing server error in my Next app

I have been trying to add animation for page transitions in my next application. However, when I’m importing and using AnimatePresence tag, my app shows a server error.

The error only occurs when using AnimatePresence.

Server Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
renderElement
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6043:9)
renderNodeDestructiveImpl
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6104:11)
renderNodeDestructive
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6076:14)
renderNode
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6259:12)
renderHostElement
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5642:3)
renderElement
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5952:5)
renderNodeDestructiveImpl
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6104:11)
renderNodeDestructive
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6076:14)
renderNode
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6259:12)
renderChildrenArray
file:///D:/New%20Portfolio%20Website/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6211:7)

Below is the code for the _app.js file

import { ChakraProvider } from "@chakra-ui/react";
import Layout from "../components/layout/main";
import Fonts from "../components/fonts";
import theme from "../lib/theme";
import {AnimatePersence} from 'framer-motion';
const Website = ({ Component, pageProps, router }) => {
    return (
        <ChakraProvider theme={theme}>
            <Fonts/>
            <Layout router={router}>
                <AnimatePersence exitBeforeEnter initial={true} >
                <Component {...pageProps} key={router.route} />
                </AnimatePersence>
            </Layout>

        </ChakraProvider>
    )
}

export default Website;

I don’t know what is causing this error, so could anyone please help me understand why this is happening and how I can solve it.

Can’t get Bootstrap pills to change and display content

I have tried everything I have found so far, unsure what’s left. I just want to have two pills and change the content displayed depending on which one is clicked. Simple enough. I have tried copying exactly what is in the Bootstrap docs, as well as many other websites’ solutions, all to no avail.

The code in my header.ejs file includes…

<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<!-- BOOTSTRAP AND CSS  -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/css/styles.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>

The code on the page in question is:

<ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" id="pills-home-tab" data-toggle="pill" href="#pills-home" role="tab" aria-controls="pills-home" aria-selected="true">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="pills-profile-tab" data-toggle="pill" href="#pills-profile" role="tab" aria-controls="pills-profile" aria-selected="false">Profile</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="pills-contact-tab" data-toggle="pill" href="#pills-contact" role="tab" aria-controls="pills-contact" aria-selected="false">Contact</a>
    </li>
</ul>
<div class="tab-content" id="pills-tabContent">
    <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">Test content 1</div>
    <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">Test content 2</div>
    <div class="tab-pane fade" id="pills-contact" role="tabpanel" aria-labelledby="pills-contact-tab">Test content 3</div>
</div>

But I have tried a few different solutions to try and solve this.

The bottom of that same file now also includes:

<script>
        $(".nav li a").on("click", function() {
            $(".nav li a").removeClass("active");
            $(this).addClass("active");
        });

    </script>

Now this has made it so that the pill I click on changes color to the one I clicked on (which didn’t use to happen), but the content displayed remains the same.

I am so lost. Willing to learn, but I have read that many websites and articles and videos to no avail yet.

Thank you.

HTML, JavaScript and JSON fake Rest API

# Movie Cruiser Assignment

## Objective

The Objective of this assignment is to work with ReST API's , understand asynchronous programming and build interactive web pages

using Javascript.

## Prerequisites

1. Fork this boilerplate repository  
2. Clone the boilerplate repository and cd into it  
3. Install dependencies. The idea here is to use json-server to serve static pages and data for movies.  

```
  npm install
  npm run start or json-server db.json -s ./public
```

## Coding Guidelines

1. All your HTML code resides in public/index.html  
2. All your JavaScript code resides in the public/js folder  
3. All your CSS code resides in the public/css folder  
4. All your images resides in the public/images folder  
5. HTML, Javascript, CSS code should be well indented and commented  
6. You shall use Bootstrap to style your pages and elements  
7. The Assignment should be pushed to gitlab on completion and submitted for Preliminary Automated Review as described below.  

## Assignment

1. Populate data for ***Movies*** collection in db.json while another ***Favourites*** collection could be left empty initially.  
2. Create Two Sections/List ***Movies*** and ***Favourites*** in your HTML page.  
3. ***Movies*** and the ***Favourites*** section of the page should populate all the movies and favourites from the db.json using

AJAX calls.
4. Every Movie item should have a Add to Favourites button.
5. On click of the Add to Favourites button the copy of the movie item should be moved to the Favourites list/section. The
movie added to Favourites section should also be added to the
Favourites collection of db.json using AJAX calls.

## Instructions 

 1. Each movie item in db.json to have atleast  `id`, `title`, `posterPath` 
 2. It is mandatory to use Fetch API and Promises for all the HTTP calls   
 3. `public/js/script.js` is expected to have three functions -  
  a. `getMovies()` - to fetch movies from `http://localhost:3000/movies`, populate them in DOM under `<ul

id=”moviesList”>and returns a promise with the JSON response from API b.getFavourites()- to fetch favourites fromhttp://localhost:3000/favourites, populate them in DOM under and returns a promise with the JSON response from API c.addFavourite()- as the click event handler for the buttonAdd to Favouritescorresponding to each movie listed underMovieson page, this shall takeidof a movie as input, copy the respective movie toFavouritessection, post the movie to db.json viahttp://localhost:3000/favouritesand returns a promise with the complete list of favourites been loaded on the page 4.public/index.html- Movies list to be populated underand Favourites list to be populated under, getMovies()andgetFavourites()` to be
invoked as shown in the file

HTML Code:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Movie Cruiser</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-12 col-md-6"> <!-- Bootstrap classes can be modified as desired -->
                <h2>Movies</h2>
                <ul id="moviesList">
                    <div class="container">
                        
                    </div>
                    <!-- Fill the Movies data here -->

                </ul>
            </div>
            <div class="col-12 col-md-6"> <!-- Bootstrap classes can be modified as desired -->
                <h2>Favourites</h2>
                <ul id="favouritesList">
                        
                    <!-- Fill the Favourites data here -->  

                </ul>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="/js/script.js"></script>
    <script type="text/javascript">
        getMovies();
        getFavourites();
    </script>
</body>
</html>



JS code:

const url = 'http://localhost:3000/db'
const title = document.getElementById("title")
const posterPath = document.getElementById("posterPath")

async function getMovies() {
    try{
    let response = await fetch(url)
    let data = await response.json();
    return data;
    }catch(err){
        console.log(err)
    }
}
async function renderMovieList(){
    let movieList = await getMovies();
    let card =''
    movieList.forEach(movie =>{
        card = card + `<div class="card">
        <div class="card-body">
            <h5 class="card-title">${movie.title}</h5>
            <p class="card-text">${movie.posterPath}</p>
        </div>
    </div>`
    })
    let x =document.querySelector('.container')
    x.innerHTML = card
}

renderMovieList()

function getFavourites() {

}

function addFavourite() {
    alert("Add Button Clicked")
    await fetch(url,{
        method: 'POST',
        headers:{
            'Content-Type' : 'application/json'
        }
    })

}

module.exports = {
    getMovies,`enter code here`
    getFavourites,
    addFavourite
};

// You will get error - Uncaught ReferenceError: module is not defined
// while running this script on browser which you shall ignore
// as this is required for testing purposes and shall not hinder
// it's normal execution






JSON File:
{
  "movies": [
    {
      "id": 101,
      "title": "Titanic",
      "posterPath": "https://www.google.com/imgres?imgurl=https%3A%2F%2Fm.media-amazon.com%2Fimages%2FI%2F71V3V0FE1gS._AC_SL1200_.jpg&imgrefurl=https%3A%2F%2Fwww.amazon.ca%2FRetro-Vintage-Titanic-Poster-Plaque%2Fdp%2FB098MVVRJF&tbnid=ytku5nl58-hvrM&vet=12ahUKEwixg9bSvvz4AhWDlmoFHciwB9wQMygBegUIARDNAg..i&docid=f4jGg_MR-X2yZM&w=800&h=1200&itg=1&q=titanic%20poster&ved=2ahUKEwixg9bSvvz4AhWDlmoFHciwB9wQMygBegUIARDNAg"
    },
    {
      "id": 102,
      "title": "avengers endgame",
      "posterPath": "https://en.wikipedia.org/wiki/Avengers:_Endgame"
    },
    {
      "id":103,
      "title": "Spiderman: far from home",
      "posterPath":"https://www.google.com/imgres?imgurl=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fen%2Fthumb%2F0%2F0f%2FTom_Holland_as_Spider-Man.jpg%2F220px-Tom_Holland_as_Spider-Man.jpg&imgrefurl=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FPeter_Parker_(Marvel_Cinematic_Universe)&tbnid=rod-f7mjRAAsWM&vet=12ahUKEwjShbuLv_z4AhXXmmoFHaB1BIgQMygFegUIARDmAQ..i&docid=WzgDlGUQwU798M&w=220&h=369&itg=1&q=spiderman&ved=2ahUKEwjShbuLv_z4AhXXmmo`enter code here`FHaB1BIgQMygFegUIARDmAQ"
    },
    {
      "id":104,
      "title": "Mr. Bean",
      "posterPath":"https://www.google.com/imgres?imgurl=https%3A%2F%2Fm.media-amazon.com%2Fimages%2FM%2FMV5BOGNjZTRlNDctNGI0Yi00YmFkLTljMmQtMjQ1ZjdiNmU5YTc0XkEyXkFqcGdeQXVyNTA4NzY1MzY%40._V1_FMjpg_UX1000_.jpg&imgrefurl=https%3A%2F%2Fwww.imdb.com%2Ftitle%2Ftt0096657%2F&tbnid=t9twEMxHcgx4gM&vet=12ahUKEwjEuPiqv_z4AhW3kWoFHQzUBywQMygBegUIARDdAQ..i&docid=garU2V7DqdmjaM&w=1000&h=1471&q=mr%20bean&ved=2ahUKEwjEuPiqv_z4AhW3kWoFHQzUBywQMygBegUIARDdAQ"
    },
    {
      "id":105,
      "title":"Rush Hour",
      "posterPath":"https://www.google.com/imgres?imgurl=https%3A%2F%2Fm.media-amazon.com%2Fimages%2FM%2FMV5BNTViODJjYzQtMDIyYi00OWFkLWEyMTktNGJhYTY4ZGQzZmVkXkEyXkFqcGdeQXVyMTExNDQ2MTI%40._V1_.jpg&imgrefurl=https%3A%2F%2Fwww.imdb.com%2Ftitle%2Ftt0120812%2F&tbnid=A289KAZGb49WjM&vet=12ahUKEwjB3Zu9v_z4AhUdkWoFHRBODfAQMygCegUIARDkAQ..i&docid=q235VD2Da6EFGM&w=1000&h=1500&q=rush%20hour&ved=2ahUKEwjB3Zu9v_z4AhUdkWoFHRBODfAQMygCegUIARDkAQ"
    },
    {
      "id":106,
      "title":"John Wick",
      "posterPath":"https://www.google.com/imgres?imgurl=https%3A%2F%2Flionsgate.brightspotcdn.com%2F59%2Fe8%2F576c91ae47e4aa7fd6240dc48674%2Fjohn-wick-chapter-1-movies-poster-01.jpg&imgrefurl=https%3A%2F%2Fwww.lionsgate.com%2Ffranchises%2Fjohn-wick&tbnid=bnKcHU-Dg2o_hM&vet=12ahUKEwjn3pvbv_z4AhV2j2oFHQ6DCMkQMygCegUIARDdAQ..i&docid=yrSe5uPKyQl_kM&w=350&h=525&q=john%20wick&ved=2ahUKEwjn3pvbv_z4AhV2j2oFHQ6DCMkQMygCegUIARDdAQ"
    }
  ],
  "favourites": [
  ]
}
 

No response after clicking button on JS

sorry for this very basic question.
So I want to know how to make buttons responsive.

I have a client.js and index.html as shown below

// Function to change the content of t2
function modifyText() {
  const t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

// Add event listener to table
const el = document.getElementById("myButton");
el.addEventListener("click", modifyText, false);
<table id="outside">
  <tr><td id="t1">one</td></tr>
  <tr><td id="t2">two</td></tr>
</table>
<button id="myButton">Click Me!</button>

When I run on codepen it works fine.
But when I try to run these locally, with a server.js like this

console.log('Server-side code running');

const express = require('express');

const app = express();

// serve files from the public directory
app.use(express.static('public'));

// start the express web server listening on 8080
app.listen(8080, () => {
  console.log('listening on 8080');
});

// serve the homepage
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

and I change the html into having a script calling the client.js

<!DOCTYPE html>
<html lang="en" dir="ltr">
 <head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Example-1</title>
 </head>
 <body>
  <button id="myButton">Click me!</button>
  <table id="outside">
  <tr><td id="t1">one</td></tr>
  <tr><td id="t2">two</td></tr>
  <script src="client.js"></script>
  </table>

 </body>
</html>

Then I run node server.js and I type localhost:8080 in my browser, the html file gets displayed but when I click the button, it doesn’t cause any number changes.
How can I get these to work for real?

Also, ultimately I want the node.js server side to know a button has been pressed. Maybe print on the node.js console that “a button was pressed”, whenever it was done on my browser. How can I achieve that?

What I want is to pass information from client side to server side easily but I am quite confused with how to do that and many people suggest different ways.

Edit:
Aligned file names.

How to rename array keys to a string value in JavaScript

I have an array that conatins a list of objects, then am mapping through the object to display a list of data.
Right now when user add item to the list , I want to change the index of that newly added Item to a string value.

What am getting is this

 [{…}]
0: {categories: 'A very nice shawarma for 2!', discount: 0, id: 7,}

Instead what I want is the index key 0 of the array to change to a string value rather than the automatic 0, 2,3… inedex key base

Something like …

"String" : {categories: 'A very nice shawarma for 2!', discount: 0, id: 7,}

The sum of the same values in a field next to each other

please i need an advice how to handle work data in arrays,
i have two arrays:

const data = [ 250, 250, 500, 500 ]
const labels = [ '2022-05-10', '2022-06-10', '2022-07-10', '2022-07-10' ]

each date has a value, but I need to sum the same values for each day, so the output should look like this:

const data = [ 250, 250, 1000 ]
const labels = [ '2022-05-10', '2022-06-10', '2022-07-10' ]

Thank you in a advance

Express is posting data to MongoDB but wont redirect after success

noob app with react, express, nodeJS. After handleClick to post with express, data gets added to MongoDB, but can’t seem to find a way to redirect to a page after successful data entry.

server.js

require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const uri = process.env.MONGO_URI;
const path = require('path');
// const fs = require('fs');

const app = express();

app.use(express.static(path.join(__dirname, 'build')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const user = require("./src/models/registerUser");

mongoose
  .connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })

  .then(() => {
    console.log("Connected to database.");
  })
  .catch(() => {
    console.error("Error connecting to the database.");
  });

  app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
  })

  app.get('/petFinderHome', async(req, res) => {
    res.sendFile(path.join(__dirname, 'build', 'index.html'))
  })

  app.get('/petfinder', async(req, res) => {
    res.sendFile(path.join(__dirname, 'build', 'index.html'))
  })

  app.get('/signOn', async(req, res) => {
    res.sendFile(path.join(__dirname, 'build', 'index.html'))
  })

  app.get('/welcomeNewsletter', async(req, res) => {
    res.sendFile(path.join(__dirname, 'build', 'index.html'))
  })
  // app.use("/", function (req, res, next) {
  //   res.redirect("/welcomeNewsletter");
  //   next();
  // });

  app.post('/signOn', user, (req, res) => {
    res.redirect('http://');
  });



  app.listen(process.env.PORT || 3000, function(){
    console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
  });

signOn.js

import Nav from "../components/Nav";
import Footer from "../components/Footer";
import manImage from "../images/man.png";


const SignOn = () => {         
            
  return (
    <>
    <Nav />
    <div>
    <main className="form-signin text-center">
      <form action="/signOn" method="post">
        <img
          className="mb-5"
          src={manImage}
          alt="logo"
          width="170"
          height="195"
        />
        <h1 className="mb-3 fw-normal">Please Register</h1>

        <div className="form-floating">
          <input
            name="email"
            type="email"
            className="form-control"
            placeholder="[email protected]"
            autocomplete="off"
          />
          <label className="text-muted">Email address</label>
        </div>
        <div className="form-floating">
          <input
            name="password"
            type="password"
            className="form-control"
            placeholder="Password"
          />
          <label className="text-muted">Password</label>
        </div>

        <button className="w-100 btn btn-lg btn-primary" type="submit">
          Submit
        </button>
      </form>
    </main>
    </div>
    <Footer />
    </>
  );
};



export default SignOn;

welcomeNewsletter.js

const Nav = require("../components/Nav");
const Footer = require("../components/Footer");
const manImage = require("../images/man.png");
const gif = require("../images/signon-screen.gif")


const Welcome = () => {
  return (
    <div>
    <Nav />
      <main className="form-signin text-center">
        <form>
          <img
            className="mb-4"
            src={manImage}
            alt="logo"
            width="170"
            height="195"
          />
          <h1 className="mt-4 fw-normal">Welcome~</h1>
        </form>
      </main>
      <img
        className="image rounded mx-auto d-block"
        src={gif}
        alt="My Project GIF"
        width="550"
        height="350"
      />
      <Footer />
    </div>
  );
};

export default Welcome;

userSchema.js

const mongoose = require('mongoose');

const timeStamp = () => {
    const timeObj = JSON.stringify(new Date().toLocaleDateString())
    return timeObj;
}

const userSchema = new mongoose.Schema({
  
    email: {
        type: String,
        required: true,
        unique: true,
    },
    password: {
        type: String,
        required: true,
        bcrypt: true,
        rounds: 10,
    },
    date: {type: Date, default: timeStamp }
    
});

module.exports = mongoose.model('User', userSchema.plugin(require('mongoose-bcrypt')));

handleClick.js


import { isValidZip, showAlert } from "./validate.js";
import { showAnimals } from "../models/showAnimals";

export async function handleClick(event) {
  event.preventDefault();

  const zip = document.querySelector("#zip").value;
  const animal = document.querySelector("#animal").value;

  if (!isValidZip(zip)) {
    showAlert("Please Enter A Valid Zipcode", "danger");
    return;
  }

  let token;

  await fetch("https://api.petfinder.com/v2/oauth2/token", {
    body: `grant_type=client_credentials&client_id=${process.env.API_KEY}&client_secret=${process.env.API_SECRET}`,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    method: "POST",
  })
    .then((res) => res.json())
    .then((data) => {
      token = data.access_token;
      console.log(token);
    })
    .then(() => {
      fetch(
        `https://api.petfinder.com/v2/animals?type=${animal}&location=${zip}&limit=50`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + token,
          },
        }
      )
        .then((res) => res.json())
        .then((data) => showAnimals(data.animals));
    })
    .catch((err) => console.error(err));
}

I’ve tried res.redirect, url is correct, but page wont render.
Also wondering how to avoid cors errors.

Please lemme know if more code is needed. Thanks in advance~

Finding a name’s index inside a Variable [duplicate]

I have some exercises that are a little ambiguous: I have to find the first index of any name that is defined inside a prompt(), but the problem is that using indexOf() I must define a letter to start the search.

Is there an efficient way to define what would be the first and last letter of variable names that have not been explained to me in the course?

const name = prompt('please, type your name here);


document.body.innerHTML += `What's the first letter of your name? ${name.indexOf(0)}<br />`;
document.body.innerHTML += `What's the last letter of your name? ${name.lastIndexOf(-1)}<br />`;

Edit: I ended up finding a .CHM document that contained JS instructions, and in it I discovered the Slice() method, I ended up finding a solution for the first letter, but how could I always choose the last letter of any name within a variable?

Answer for the first letter:

document.body.innerHTML += `What's the first letter of your name ${name.slice(0, 1)}<br />`;

Error , Console log the axios network response

1.I’m working on an backend API but at some point I need to get user data from another API. I am trying to use Axios to make http request in order to do that. The request return the result in the browser as expected but the problem is that I can’t display console log in the terminal. It doesn’t show anything even though I asked the program to do so. Is there a problem probably with my code?

2.Error message =>>> POST http://localhost:8000/api/register 400 (Bad Request) Error: Request failed with status code 400`

const handleSubmit = async () => {
  //e.preventDefault();
  try 
  {
    // console.log(name, email, password, secret);
    const { data } = await axios.post("http://localhost:8000/api/register", {
      name,
      email,
      password,
      secret,
    });
    setOk(data.ok); //useState component
  } 
  catch (error) {
    **strong text**
    console.log(error.response.data);
  }

 }

import User from ‘../models/user’
//import{ hashPassword, comparePassword } from ‘../helpers/auth’

    export const register = async (req,res) => {
        //console.log('Register endpoint =>', req.body)
        //to make this work make express.json is applied in the above middleware
    
        //console.log error to debug code
    
    
        const {name, email, password, secret} = req.body;
    
        //validation
        if(!name) return res.status(400).send('Name is required')
        if(!password  || password.length < 6) return res.status(400).send('Password is 
         short 
        or password is not entered')
        if(!secret) return res.status(400).send('Answer is required')
        //The above code is for validation purpose to make sure data is correctly 
        entered

        const exist = await User.findOne({email })
    
    
        if(exist) return res.status(400).send('Email is taken')
   }

How can I make my discord bot assign roles to users (discord js)

Here is my code:

How can I assign roles to users with my discord js bot?

How can I make my discord bot assign roles to users (discord js)

I want it so that when I type !addrole a role gets added

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

client.on('ready', () => {
  console.log('Bot Online');
});

var prefix = "!"

client.on(`message`, message => {
  if(message.content.startsWith(prefix + "addrole"))
  {
    //ADD ROLE HERE
  }

});

client.on('ready', () => {
  client.user.setActivity(`!help`, { type: "PLAYING" });
});

client.login('TOKEN');

I am trying to create a “quote generator” i am having some issue with the loader

I am trying to create a js project “quote generator” i am having some issue with the loader. according to me this js code should be perfect but the loader is not hiding when the quote shows up. this is the js code. it would be great if anyone could help me. Let me know if i should use any classList property or not or just .hidden would be perfect.

const quoteContainer = document.getElementById('quoteContainer');
const quoteText = document.getElementById('quote');
const authorText = document.getElementById('author');
const twitterBtn = document.getElementById('twitter');
const newQuoteBtn = document.getElementById('new');
const loader = document.getElementById('loader');
const loading = () => {
  loader.hidden = false;
  quoteContainer.hidden = true;
}
const complete = () => {
  if (!loader.hidden) {
    quoteContainer.hidden = false;
    loader.hidden = true;
  }
}
getQuote = async() => {
  loading();
  const proxyUrl = 'https://whispering-tor-04671.herokuapp.com/'
  const apiUrl = 'http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json';
  try {
    const response = await fetch(proxyUrl + apiUrl);
    const data = await response.json();
    if (data.quoteAuthor === '') {
      authorText.innerText = 'Unknown';
    } else {
      authorText.innerText = data.quoteAuthor;
    }
    quoteText.innerText = data.quoteText;

    complete();
  } catch (error) {
    getQuote();
  }
}
const tweetQuote = () => {
  const quote = quoteText.innerText;
  const author = authorText.innerText;
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quote} - ${author}`;
  window.open(twitterUrl, '_blank');
}
newQuoteBtn.addEventListener('click', getQuote);
twitterBtn.addEventListener('click', tweetQuote);
getQuote();
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Template</title>
  <link rel="stylesheet" href="input.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
</head>

<body>
  <div id="quoteContainer" class="flex w-full min-h-screen justify-center items-center">
    <div class=" flex w-full max-w-4xl p-8 rounded-xl shadow-2xl">
      <div class="container text-center mx-auto rounded-lg">
        <p class="text-[60px] font-bold" id="quote"></p>
        <p class="text-xl font-serif" id="author"></p>

        <div class="flex justify-between">
          <button class="rounded-lg shadow-md mt-7 hover:bg-blue-600 text-white bg-black p-1 w-28 active:translate-y-1" id="twitter"><i class="fab fa-twitter"></i></button>

          <button class="rounded-lg shadow-md mt-7 hover:brightness-200 text-white bg-black p-1 w-28 active:translate-y-1" id="new">New
                            Quote</button>
        </div>
      </div>
    </div>
  </div>
  <div id="loader" class="flex items-center justify-center">
    <div class="spinner-border animate-spin inline-block w-8 h-8 border-4 rounded-full" role="status">
      <span class="visually-hidden">Loading...</span>
    </div>
  </div>
</body>
<script src="index.js"></script>

</html>

Memory leak in React when using HTML5 Canvas

I have a project in my React app that draws to the canvas.

I’m invoking it in my component like:

function CanvasProject() {

const canvasRef = useRef(null);
const cleanup = useRef(null);

useEffect(() => {
        
        var c = canvasRef.current;
        const cleanup.current = render(c);
}, [])

return(
   <canvas style={{width: "100%"}} ref={canvasRef}>    
       Your browser does not support the HTML5 canvas tag. Stop using Netscape.
   </canvas>
)
}

The render function gets the “2d” context from the canvas a few times, gets image data with ctx.createImageData, and sets image data with ctx.putImageData.

render() also adds an onclick handler to the canvas, but I’ve tried commenting out that code and the memory leak is still present.

As for the memory leak itself, when I go back and forth between routes on my App, it starts to slow down the page. I’m going back and forth between routes that respectively do and do not have my component.

I’ve tried examining the memory usage with Firefox dev tools, and here’s the memory profile when I first start the app:
enter image description here

Followed by the memory usage after I go back and forth between a few routes:
enter image description here

Obviously without seeing the full code I’m not expecting a “your bug is here” answer, but are there any things I should consider about the way canvas memory management works? Are there any other dev tools I could use to find out the source of the large chunks of Array and ArrayBuffer data that is being generated? Basically looking for any leads and a sanity check, to make sure I’m not missing something obvious.

How i get subgridcontext in Model Driven, and uptade the selected Itens?

I’m new to programming and I’m not sure how to do a task. In short, I have a business flow to clone a record from a entity called “Contracts.

The process has 2 stages. When loading the page it has to show only the tab to select the contract to be cloned, which is in a subgrid. To go to the next stage, by clicking on the button on the ribbon, the button must first validate if there are one or more contracts selected on the grid (how I get this context???) update a field of that selected contract, which when updating to true, it calls a plugin that clones the clone. (Here I have to do a retrieve multiple and then an update?) and proceed to stage 2 where only the second tab will be visible, where there will be an editable subgrid to edit the cloned contract products. Here’s the javascript I made so far but nothing is working, not even the visibility of the tabs only when it’s at its certain stage of the bussiness flow. Thank you for your help!enter code here

enter code here

if (typeof (Abi) === “undefined”) { Abi = {}; }
if (typeof (Abi.App360) === “undefined”) { Abi.App360 = {}; }
if (typeof (Abi.App360.ContractCloneProcess) === “undefined”) { Abi.App360.ContractCloneProcess = {}; }

var globalExecutionContext = null;

Abi.App360.ContractCloneProcess = {
onLoad: function (executionContext) {

    var formContext = executionContext.getFormContext();
    globalExecutionContext = executionContext;

    Abi.App360.ContractCloneProcess.prepareTabsToCreationProcess(executionContext);
    Abi.App360.ContractCloneProcess.reloadCreationProcess(executionContext);
    Abi.App360.ContractCloneProcess.lockFieldEditForm(executionContext);
    formContext.data.process.addOnPreStageChange(Abi.App360.ContractCloneProcess.preStageChange);
    formContext.data.process.addOnStageSelected(Abi.App360.ContractCloneProcess.stageSelected);

},

prepareTabsToCreationProcess: function (executionContext) {
    "use strict";

    var formContext = executionContext.getFormContext();

    if (formContext.ui.getFormType() == 1) {
        formContext.ui.tabs.get("abi_tab_contract_selection").setVisible(true);
        formContext.ui.tabs.get("abi_tab_contract_selection").setFocus();
        formContext.ui.tabs.get("abi_tab_edit_products_associated").setVisible(false);

    }
}, reloadCreationProcess: function (executionContext) {
    "use strict";

    var formContext = executionContext.getFormContext();

    if (formContext.ui.getFormType() != 1) {
        var activeStage = formContext.data.process.getActiveStage();
        var _activeStageId = activeStage._activeStageId;

        if (_activeStageId == "68b13123-f708-42af-8290-12d3828f9b2") {
            formContext.data.process.moveNext();
        } else {
            formContext.data.process.setActiveStage("a6449397-429c-41f2-aff9-1a0c439fc5b0");
        }

        formContext.data.process.setActiveStage("a6449397-429c-41f2-aff9-1a0c439fc5b0");

        formContext.ui.tabs.get("abi_tab_contract_selection").setVisible(true);
        formContext.ui.tabs.get("abi_tab_contract_selection").setFocus();
        formContext.ui.tabs.get("abi_tab_edit_products_associated").setVisible(false);

    }
},

preStageChange: function (executionContext) {

    var direction = executionContext.getEventArgs().getDirection();
    var formContext = executionContext.getFormContext();

    if (direction == "Previous") {
        Abi.App360.ContractCloneProcess.previousStep(formContext);
    }
},

stageSelected: function () {

    var retorno = setInterval(function () {
        var elemento = parent.document.getElementById("MscrmControls.Containers.ProcessStageControl-businessProcessFlowFlyoutFooterContainer")
        if (elemento != null) {
            parent.document.getElementById("MscrmControls.Containers.ProcessStageControl-nextButtonContainer").style.display = 'none';

            if (parent.document.getElementById("MscrmControls.Containers.ProcessStageControl-setActiveButtonContainer").style.display != 'none') {
                parent.document.getElementById("MscrmControls.Containers.ProcessStageControl-setActiveButtonContainer").style.display = 'none';
            }
        }
    }, 0.1)

    var retorno2 = setInterval(function () {
        var elemento = parent.document.getElementById("MscrmControls.Containers.ProcessStageControl-businessProcessFlowFlyoutFooterContainer")
        if (elemento != null) {
            parent.document.getElementById("MscrmControls.Containers.ProcessStageControl-setActiveButtonContainer").style.display = 'none';
        }
    }, 0.1)

},

previousStep: function (formContext) {
    "use strict";

    var activeStage = formContext.data.process.getActiveStage();
    var _activeStageId = activeStage._activeStageId;

    //EditProductsServices
    if (_activeStageId == "a6449397-429c-41f2-aff9-1a0c439fc5b0") {
        formContext.ui.tabs.get("abi_tab_contract_selection").setVisible(true);
        formContext.ui.tabs.get("abi_tab_contract_selection").setFocus();
        formContext.ui.tabs.get("abi_tab_edit_products_associated").setVisible(false);

    } else if (_activeStageId == "68b13123-f708-42af-8290-12d3828f9b2") {
        formContext.ui.tabs.get("abi_tab_edit_products_associated").setVisible(true);
        formContext.ui.tabs.get("abi_tab_edit_products_associated").setFocus();
        formContext.ui.tabs.get("abi_tab_contract_selection").setVisible(false);
    }

},

nextStep: function (primaryControl, selectedControlSelectedItemCount) {
    "use strict";

    var activeStage = primaryControl.data.process.getActiveStage();
    var _activeStageId = activeStage._activeStageId;

    var isValidatedStep = Abi.App360.ContractCloneProcess.validateRequiredFieldStep(primaryControl, _activeStageId);


    //ContractClone
    if (_activeStageId == "a6449397-429c-41f2-aff9-1a0c439fc5b0" && isValidatedStep == true) {
        primaryControl.ui.tabs.get("abi_tab_edit_products_associated").setVisible(true);
        primaryControl.ui.tabs.get("abi_tab_contract_selection").setVisible(false);

        primaryControl.data.save().then(
            function (success) {
                primaryControl.data.process.moveNext();
                console.log(success);
            },
            function (error) {
                console.log(error);
            });
    }
    //EditProductsServices
    else if (_activeStageId == "68b13123-f708-42af-8290-12d3828f9b25") {
        primaryControl.ui.tabs.get("abi_tab_edit_products_associated").setVisible(true);
        primaryControl.ui.tabs.get("abi_tab_contract_selection").setVisible(false);

        primaryControl.data.save().then(
            function (success) {
                var alertStrings = { confirmButtonLabel: "OK", text: "You have succesfully update records.", title: "Success!" };
                var alertOptions = { height: 120, width: 260 };
                Xrm.Navigation.openAlertDialog(alertStrings, alertOptions).then(
                    function (success) {
                        var pageInput = {
                            pageType: "entitylist",
                            entityName: "abi_baseline"
                        };
                        Xrm.Navigation.navigateTo(pageInput).then(
                            function success() {
                                console.log(success);
                            },
                            function error() {
                                console.log(error);
                            }
                        );
                    },
                    function (error) {
                        console.log(error.message);
                    }
                );
            },
            function (error) {
                console.log(error);
            });
    }

},

validateRequiredFieldStep: function (primaryControl, activeStageId, selectedControlSelectedItemCount) {
    "use strict";

    //ContractClone
    if (activeStageId == "a6449397-429c-41f2-aff9-1a0c439fc5b0") {
        var service = primaryControl.getControl("abi_contract");

        if (selectedControlSelectedItemCount != null && selectedControlSelectedItemCount > 0) {
            return true;
        } else {
            primaryControl.data.save();
            return false; "
        }

    }

},

}

Can’t get Admob example ads to show in Cordova app

I have a simple app I made in vanilla JS that I want to convert to a mobile app. I can do it easily with Cordova, but I can’t seem to get Admob ads to show up with any of the plugins I tried.

On this one I am using “admob-plus-cordova”. I created it with the example app ID, and followed the instructions in the documentation. I just can’t figure out why it doesn’t work.

    <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta
      name="viewport"
      content="initial-scale=1, width=device-width, viewport-fit=cover"
    />
    <meta name="color-scheme" content="light dark" />
    <link rel="stylesheet" href="css/index.css" />
    <title>Admob</title>
  </head>
  <body>
    <div></div>
    <script src="cordova.js"></script>
    <script type="text/javascript">
      let banner

      document.addEventListener(
        "deviceready",
        async () => {
          await admob.start()
          banner = new admob.BannerAd({
            adUnitId: " ca-app-pub-3940256099942544/6300978111",
          })

          banner.on("impression", async (evt) => {
            await banner.hide()
          })

          await banner.show()
        },
        false
      )
    </script>
  </body>
</html>