How can I get all of my Cards to be centered? [duplicate]

Screen Capture of the issue in question

I am working on my first Project, it is a Book-list library.

I can’t seem to get the Card components to be centered on the site. It is shifted to the left.

I have all of my Card information in the App.js file, Card.js, and Card.css

I have tried multiple methods, videos, and even tried to see if ChatGPT could give some insight but nothing seems to get them centered.

(I have added a screen capture of the issue above)

Thank you very much

**App.js code below:**

    function App() {

  return (

    <Router>
      <div style={{ display: 'flex' }}>

        <Navbar />
        <div style={{ marginLeft: '200px', padding: '20px' }}>

          <Routes>
            <Route path="/catalog" element={<Catalog />} />
            <Route path="/favorite" element={<Favorites />} />
            <Route path="/" element={

              <div className="App">

                {/* First Row: */}

                <div className="col">

                  <Card
                    imgSrc={img12}
                    imgAlt="Harry Potter and the Prisoner of Azkaban"
                    title="Harry Potter and the Prisoner of Azkaban"
                    description="Author: J.K. Rowling; Cover design by Olly Moss, 2017"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/import-9781338815283/19690866?ean=9781338815283"
                  />
                  <Card
                    imgSrc={img6}
                    imgAlt="Jaws"
                    title="Jaws"
                    description="Author: Peter Benchley; Cover design by Paul Bacon, 1974"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/jaws-peter-benchley/15279162?ean=9780345544148"
                  />
                  <Card
                    imgSrc={img5}
                    imgAlt="The Great Gatsby"
                    title="The Great Gatsby"
                    description="Author: F. Scott Fitzgerald; Cover art by Francis Cugat, 1925"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/the-great-gatsby-f-scott-fitzgerald/18533627?ean=9780743273565"
                  />

                </div>

                {/* Second Row: */}

                <div className="col">

                  <Card
                    imgSrc={img7}
                    imgAlt="Pride and Prejudice"
                    title="Pride and Prejudice"
                    description="Author: Jane Austen; Cover design by Hugh Thomson, 1894"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/pride-and-prejudice-jane-austen/15657135?ean=9780141439518"
                  />

                  <Card
                    imgSrc={img3}
                    imgAlt="I Know Why the Caged Bird Sings"
                    title="I Know Why the Caged Bird Sings"
                    description="Author: Maya Angelou, Cover design by Janet Halverson, 1969"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/i-know-why-the-caged-bird-sings-maya-angelou/8496752?ean=9780375507892"
                  />

                  <Card
                    imgSrc={img11}
                    imgAlt="The Handmaids Tale"
                    title="The Handmaids Tale"
                    description="Author: Margaret Atwood, Cover design by Fred Marcellino, 1986"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/brave-new-world-aldous-huxley/18711990?ean=9780060850524"
                  />


                </div>

                {/* Third Row: */}

                <div className="col">

                  <Card
                    imgSrc={img1}
                    imgAlt="Harry Potter and the Chamber of Secrets"
                    title="Harry Potter and the Chamber of Secrets"
                    description="Author: J.K. Rowling; Cover design by Olly Moss, 2016"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/harry-potter-and-the-chamber-of-secrets-minalima-edition-illustrated-edition-volume-2-j-k-rowling/15063913?ean=9780439064866"
                  />

                  <Card
                    imgSrc={img4}
                    imgAlt="The Catcher in the Rye"
                    title="The Catcher in the Rye"
                    description="Author: J.D. Salinge; Cover design by E. Michael Mitchell, 1951"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/the-catcher-in-the-rye-j-d-salinger/114571?ean=9780316769488"
                  />

                  <Card
                    imgSrc={img2}
                    imgAlt="Brave New World"
                    title="Brave New World"
                    description="Author: Aldous Huxley, Cover design by Leslie Holland, 1932"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/brave-new-world-aldous-huxley/18711990?ean=9780060850524"
                  />

                </div>

                {/* Fourth Row: */}

                <div className="col">
                  <Card
                    imgSrc={img8}
                    imgAlt="Slaughterhouse-Five"
                    title="Slaughterhouse-Five"
                    description="Author: Kurt Vonnegut, Cover design by Paul Bacon, 1969"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/slaughterhouse-five-or-the-children-s-crusade-a-duty-dance-with-death-kurt-vonnegut/15551258?ean=9780440180296"
                  />

                  <Card
                    imgSrc={img18}
                    imgAlt="Lord of the Rings"
                    title="Lord of the Rings: The Return of the King"
                    description="Author: J. R. R. Tolkien; Cover design by Johan Egerkrans, 2020"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/song-of-solomon-toni-morrison/285447?ean=9781400033423"
                  />


                  <Card
                    imgSrc={img17}
                    imgAlt="The Color Purple"
                    title="The Color Purple"
                    description="Author: Alice Walker; Cover design by Judith Kazdym Leeds, 1982"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/the-color-purple-alice-walker/285324?ean=9780143135692"
                  />

                </div>


                {/* Fifth Row: */}

                <div className="col">

                  <Card
                    imgAlt="Favorites List"
                    title="Favorites List:"
                    buttonText="View Favorites"
                    link="http://localhost:3000/components/Favorites"
                  />

                  <Card
                    imgAlt="Book Catalogs"
                    title="Book Catalogs:"
                    buttonText="View Catalogs"
                    link="http://localhost:3000/components/Catalog"
                  />

                  <Card
                    imgSrc={img14}
                    title="Audible.com"
                    imgAlt="Audible.com"
                    description="Online audiobook and podcast service"
                    buttonText="View Here"
                    link="https://www.audible.com/"
                  />

                  <Card
                    imgSrc={img13}
                    title="NY Times Best Sellers List"
                    imgAlt="NY Times Best Sellers List"
                    description="Authoritatively ranked lists of Best Seller books, from 'The New York Times'"
                    buttonText="View Here"
                    link="https://www.nytimes.com/books/best-sellers/"
                  />


                  <Card
                    imgSrc={img10}
                    imgAlt="Jurassic Park"
                    title="Jurassic Park"
                    description="Author: Michael Crichton; Cover design by Chip Kidd, 1990"
                    buttonText="Learn More"
                    link="https://bookshop.org/p/books/jurassic-park-michael-crichton/14708249?ean=9780345538987"
                  />

                </div>

              </div>
            }
            />
          </Routes>
        </div>
      </div>
    </Router>
  );
}

export default App;

Card.js code below:

import React from "react";
import { Link } from 'react-router-dom';
import "./Card.css";

export const Card = ({
    imgSrc,
    imgAlt,
    title,
    description,
    buttonText,
    link,
}) => {

    return (
        <div className="card-container">
            {imgSrc && imgAlt && (
                <img src={imgSrc} alt={imgAlt} className="card-img" />
            )}
            {title && <h1 className="card-title">{title}</h1>}
            {description && <p className="card-description">{description}</p>}
            {buttonText && link && (
                <a href={link} className="card-button-link">
                    <button className="card-button">{buttonText}</button>
                    <Link to={link} style={{ textDecoration: 'none', color: 'inherit' }}></Link>
                </a>
            )}
        </div>
    );
};

export default Card;

nextauth 4x credentials sign in – how to append additional db data to user session

I am trying to build a simple credentials sign flow using next-auth ^4.24.5 with nextjs 14. My user model has a boolean prop called ‘isAdmin’ that I would like to expose out to my session using a jwt strategy.

I can see the isAdmin prop as part of the returned user from User.find().
However, I do not see it as part of ANY object returned from any of the callbacks.

This is my config:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import User from "../../../../models/User";

export const authOptions = {
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    strategy: "jwt"
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",

      credentials: {
        username: {
          label: "Username",
          type: "text",
          placeholder: "[email protected]",
        },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        try {
          const user = await User.findOne({
            email: credentials.username,
          }).exec();
          if (user) {
            const isValid = await user.comparePassword(credentials.password);
            if (isValid) return user;
          }

          return null;
        } catch (err) {
          console.log(err);
        }
      },
    }),
  ],
  callbacks: {
    async signIn({ user, account, profile, email, credentials }) {
      return true;
    },
    async redirect({ url, baseUrl }) {
      return baseUrl;
    },
    async jwt({ token, user, account, profile, isNewUser }) {
      return token;
    },
    async session({ session, user, token }) {
      return session;
    },
  },
  pages: {
    signIn: "/auth/signin",
    signOut: "/auth/signout",
    error: "/auth/error", // Error code passed in query string as ?error=
    verifyRequest: "/auth/verify-request", // (used for check email message)
    newUser: "/auth/register", // New users will be directed here on first sign in (leave the property out if not of interest)
  },
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };


I can’t adjust collision and gravity in canvas

I am trying to implement a fairly simple merge fruit game using canvas, in which the balls must fall into a glass, and if the balls are the same size, they touch each other. They turn into one big ball. But there is a problem with gravity and collision. Over time, they just start to squeeze into each other. Most likely, this is due to gravity, which attracts them until they touch the floor. But I do not know how to manipulate her. And do not lose gravity in a collision. Because it is necessary that the balls still have the opportunity to roll over each other. Please help me!

Sorry if the code looks clumsy. I just tried everything I could and eventually started getting confused in my own code.

you can check it in code pen version

https://codepen.io/njtbmhbh-the-animator/pen/wvLrmdK


  //Функция для ограничения количества кадров в секунду
       var limitLoop = function (fn, fps) {
     
                // Use var then = Date.now(); if you
                // don't care about targetting < IE9
                var then = new Date().getTime();
            
                // custom fps, otherwise fallback to 60
                fps = fps || 60;
                var interval = 1000 / fps;
             
                return (function loop(time){
                    requestAnimationFrame(loop);
             
                    // again, Date.now() if it's available
                    var now = new Date().getTime();
                    var delta = now - then;
             
                    if (delta > interval) {
                        // Update time
                        // now - (delta % interval) is an improvement over just 
                        // using then = now, which can end up lowering overall fps
                        then = now - (delta % interval);
             
                        // call the fn
                        fn();
                    }
                }(0));
            };



            //Полезные функции

            function randomIntFromRange(min,max) {
                return Math.floor(Math.random() * (max - min + 1) + min);
            }

            function frameCheck(ball){
              if(ball.y + ball.radius  + ball.velocity.y > canvas.height){
                ball.velocity.y = -ball.velocity.y * 0.6;
              } else {
                if(!ball.colideState){
                ball.velocity.y += gravity;
            }
              }
              
              if(ball.x + ball.radius + ball.velocity.x >= canvas.width || ball.x - ball.radius + ball.velocity.x<= 0){
                ball.velocity.x = -ball.velocity.x;
              }
            }


            function getDistance(x1, y1, x2, y2){
              let xDistance = x2 - x1;
              let yDistance = y2 - y1;

              return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2))
            }
            
            //Утилита для рассчета коллизии

            /**
     * Rotates coordinate system for velocities
     *
     * Takes velocities and alters them as if the coordinate system they're on was rotated
     *
     * @param  Object | velocity | The velocity of an individual particle
     * @param  Float  | angle    | The angle of collision between two objects in radians
     * @return Object | The altered x and y velocities after the coordinate system has been rotated
     */

    function rotate(velocity, angle) {
      const rotatedVelocities = {
          x: velocity.x * Math.cos(angle) - velocity.y * Math.sin(angle),
          y: velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
      };

      return rotatedVelocities;
    }

    /**
    * Swaps out two colliding particles' x and y velocities after running through
    * an elastic collision reaction equation
    *
    * @param  Object | particle      | A particle object with x and y coordinates, plus velocity
    * @param  Object | otherParticle | A particle object with x and y coordinates, plus velocity
    * @return Null | Does not return a value
    */

    function resolveCollision(particle, otherParticle) {
      const xVelocityDiff = particle.velocity.x - otherParticle.velocity.x;
      const yVelocityDiff = particle.velocity.y - otherParticle.velocity.y;

      const xDist = otherParticle.x - particle.x;
      const yDist = otherParticle.y - particle.y;

      // Prevent accidental overlap of particles
      if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {

          // Grab angle between the two colliding particles
          const angle = -Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);

          // Store mass in var for better readability in collision equation
          const m1 = particle.mass;
          const m2 = otherParticle.mass;

          // Velocity before equation
          const u1 = rotate(particle.velocity, angle);
          const u2 = rotate(otherParticle.velocity, angle);

          // Velocity after 1d collision equation
          const v1 = { x: u1.x * (m1 - m2) / (m1 + m2) + u2.x * 2 * m2 / (m1 + m2), y: u1.y };
          const v2 = { x: u2.x * (m1 - m2) / (m1 + m2) + u1.x * 2 * m2 / (m1 + m2), y: u2.y };

          // Final velocity after rotating axis back to original location
          const vFinal1 = rotate(v1, -angle);
          const vFinal2 = rotate(v2, -angle);
          if(particle.y != particle.pastY){
          // Swap particle velocities for realistic bounce effect
          if(particle.y + particle.radius  + particle.velocity.y < canvas.height){
            particle.velocity.y = vFinal2.y * 0.8;
          }
          
          if(otherParticle.y + otherParticle.radius  + otherParticle.velocity.y < canvas.height){
            otherParticle.velocity.y = vFinal2.y * 0.8;
          }
        }
          if(particle.x + particle.radius + particle.velocity.x < canvas.width && particle.x - particle.radius + particle.velocity.x > 0){
            particle.velocity.x = vFinal1.x ;
          } else {}

         if(otherParticle.x + otherParticle.radius + otherParticle.velocity.x < canvas.width && otherParticle.x - otherParticle.radius + otherParticle.velocity.x > 0){
           otherParticle.velocity.x = vFinal2.x ;
         } else {}





      }
    }




            //game
            const canvas = document.querySelector('canvas')
            const c = canvas.getContext('2d');
            canvas.height = window.screen.height - window.screen.height * 0.6; // window heigh - 20 percents
            canvas.width = document.querySelector('.container').clientWidth * 0.5; // container width
            let objects = []
       //Массив шариков
            let  ballsTemplates = {
              1:{
                y: 50,
                direction: 0,
                radius: 20,
                color: "blue",
                level: 1
              },
              2:{
                y: 50,
                direction: 0,
                radius: 25,
                color: "green",
                level: 2
              },
              3:{
                y: 50,
                direction: 0,
                radius: 30,
                color: "black",
                level: 3
              },
              4:{
                y: 50,
                direction: 0,
                radius: 35,
                color: "red",
                level: 4
              },
            }


            const gravity = 0.5;
            //objects
            class Ball {
                constructor(x, y, dx, dy, bp, radius, color, level) {
                  this.x = x
                  this.y = y
                  this.pastX = 0
                  this.pastY = 0
                  this.colideState = false;
                  this.velocity = {
                    x: dx,
                    y: dy
                  }
                  this.level = level
                  this.bp = bp;
                  this.radius = radius
                  this.color = color
                  this.mass = 1;
                }
              
                draw() {
                  c.beginPath()
                  c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
                  c.fillStyle = this.color
                  c.fill()
                  c.closePath()
                }
              
                update = objects => {

                  this.pastX = this.x;
                      this.pastY = this.y

                  this.y += this.velocity.y
                  this.velocity.x = this.velocity.x * 0.99;
                  this.x += this.velocity.x;
                  //Не даём шарику возможности упать за границы карты
                  frameCheck(this);

                  for (let i=0; i < objects.length; i++){
                    if(objects[i]){
                    if(this === objects[i]) continue;
                    if(getDistance(this.x, this.y, objects[i].x, objects[i].y) - (this.radius + objects[i].radius) < -0.8){
                      
                      //Вызов функции коллизии
                      resolveCollision(this, objects[i]);
                      

                     
                      let lvl = this.level;
                      let lvl2 = objects[i].level;
                      if(lvl === lvl2){
                        if(lvl < 4){
                        let x = (this.x + objects[i].x) / 2
                        let y = (this.y + objects[i].y) / 2

                        this.x = x;
                        this.y = y;
                        this.direction = ballsTemplates[lvl + 1].direction;
                        this.dy = 0.5;
                        this.bp =  0.9;
                        this.radius =  ballsTemplates[lvl + 1].radius;
                        this.color =  ballsTemplates[lvl + 1].color;
                        this.level =  ballsTemplates[lvl + 1].level;
                        
                      delete objects[i];
                    }
                      }
                      
                        if(this.y == this.pastY){
                      this.colideState = true;
                    }
                      } else {
                      this.colideState = false;
                      }

                }
            }

              this.draw()
            
                }
              }


      //функция для создания шарика по клику
              canvas.addEventListener('mouseup', function (event) {
               // Implementation
               const rect = canvas.getBoundingClientRect();
               const computedStyle = getComputedStyle(canvas);
               const borderLeftWidth = parseInt(computedStyle.borderLeftWidth, 10);
               const borderTopWidth = parseInt(computedStyle.borderTopWidth, 10);
               let numb = randomIntFromRange(1,4);
               let x = event.clientX - rect.left - borderLeftWidth
               let y = event.clientY - rect.top - borderTopWidth

               let radius = 55;

                let dxWerid = 5;

               if(x + radius * 2 > canvas.width){
                x = canvas.width - radius;
               } else if (x - radius * 2 < canvas.width){
                x = x + radius;
               }

              let ball = new Ball( x , y, ballsTemplates[numb].direction , 1 , 0.9,ballsTemplates[numb].radius, ballsTemplates[numb].color, ballsTemplates[numb].level)
            
               objects.push(ball)

                
              });



            const animate = async () => {
                c.fillStyle="white"
              
                c.fillRect(0, 0, canvas.width, canvas.height) //background :/
                 objects.forEach(object => {
                  object.update(objects)
                 })
                
            }
        
            
            limitLoop(animate, 60);

<!-- language: lang-css -->




    .gameScreen {
        border: 10px solid white;
        background-color: black;
    }

<!-- language: lang-html -->

    <body>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="root"><div class="container" height="200" width="332"><div><div><canvas class="gameScreen"></canvas> <- С попощью левой кнопки мыши заспавни много шариков. Чтобы было несколько рядок</div></div></div></div>
      

    </body>```





I tried to implement a mechanic in which the balls push each other out when they collide. But it really spoils the physics and the external component. I'm trying to figure out how to do the right thing here.

Passing a variable to window.open method

I’m trying to pass a variable to window.open() method. I would like to use that passed variable to the opened html file.

**<script>

        var value = document.getElementById("oper").value;
        const Gobtn = document.getElementById("Go");

        Gobtn.addEventListener("click", function (){
            window.open("calculate.html", value);
        });

    </script>**

I’m trying to open “calculate.html” and use the content of the variable named “value” in the “calculate.html” file. Thanks.

Client side JS compiler – Running JS code(As a string) in Client Browser from React

I am building a JS compiler, So it is nothing but it will execute the JS code, So I am having two components in react, One will get input from user (The JS code they want to execute), The another one is showing the Output, typically the consoles in the code.

The first part is done, I can able to get the code from user. Now I don’t want to send this code to my server, rather I want to run this in the client browser itself. In online I can see we can use eval() function. But my requirement is to capture the console logs, errors and display in a output component.

I am struct at two things, 1. The execution should support asynchronous code, and if any object is consoling, I am expecting the complete object in an object format not as a string. I am looking for a solution.

Requirement 1: (A simple asynchronous func)

console.log('Start');
setTimeout(() => console.log('This is async'), 2000);
console.log('End');

So for this, Start & End should print in output window immediately, and after 2 sec This is async should print.

Requirement 2 :

let myObj ={"Key":"val"}
console.log("op",myObj)

So in this I am expecting this myObj as an Obj itself, So that I can view accordingly in my output component ( User can minimize or open an obj).

dont drag image after lost focus

I move the image – drag and drop. Everything is fine until I put the cursor in the input type ‘password’ – it stops working. If I click the mouse near to the image, it starts working again. Moreover, the input type ‘text’ does not affect it. Can this be fixed?

I tried a lot – changed the code, removed pieces of code, until I discovered that the problem is exactly when I put the cursor in an input type”password”
By the way, Firefox doesn’t have this problem!
https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop2
i insert here input type’password’ and the same problem…

I’m getting “jinja2.exceptions.TemplateSyntaxError: unexpected char ‘$’ at 3607” error while trying to render html using js and data from python

I’m trying to use data retrieved by my python get_data() api to create dynamic urls. The data is a dictionary which states whether or not a user owns a specific course. If they own the course (Ex. ‘ownsJava’ : True), then the button called ‘Learn’ will go to that course, if they dont own it (Ex. ‘ownsJava’ : False), then the button will be called ‘Purchase’ and will redirect to the shopping cart. However, to do this I need to include javascript variables into {{ url_for() }} so it will work properly, but I keep on getting this error: jinja2.exceptions.TemplateSyntaxError: unexpected char ‘$’ at 3607 at .

I tried to separate the functions (one function for fetching data and one for rendering the content) but it just ended in the same thing.

script in userdash.html

<script type="text/javascript">
      render_data.innerHTML = ``;
      const user_id = "{{ user_id }}";

      const url = `/get_data/${user_id}`
      
      function getPurchasing(key){
        if (key === 'pythonOwner'){
          return 'python';
        }
        else if(key === 'javascriptOwner'){
          return 'javascript';
        }
        else{
          return 'java';
        }
      }

      function getCourse(key){
        if(key === 'ownsJava'){
          return 'javacourse';
        }
        else if(key === 'ownsJavascript'){
          return 'javascriptcourse';
        }
        else{
          return 'pythoncourse';
        }
      }


      async function fetchAndRenderData() {
        try {
          const response = await fetch(url);
          if(!response.ok){
            throw new Error('Network response was not ok');
          }
          data = await response.json();  // Convert response to JSON
          // console.log(1);
          // console.log(data);
          // console.log(2);

        } catch (error) {
            console.error('Error:', error);
        }
        console.log(data);
        // return data;

        let user_url;
        let buttonText;
          for(const [key, values] of Object.entries(data)){
            
            if(values){
              user_url = `${user_id}/${getCourse(key)}`;
              buttonText = 'Learn';
            }
            else{
              user_url = `shoppingcart`;
              buttonText = 'Purchase';
            }
            render_data.innerHTML += 
            `<div class="cardBorder item">
                <div>
                  <img src="{{ url_for('static', filename='img/prof1.jpg') }}">
                </div>
                <div>
                  <h1>test</h1>
                  <h2>test</h2>
                  <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Alias esse culpa rerum, voluptate nisi ea dignissimos consequuntur ipsam ratione iusto nobis voluptatum maxime. Repudiandae, illum voluptate? Dolores, culpa accusantium asperiores ex, sint quia, nam ad animi accusamus ipsa molestiae quidem!</p>
                </div>
                <div class="purchaseButton">
                  <a href="{{ url_for(${user_url}) }}">
                    <button>
                        ${buttonText}
                    </button>
                  </a>
                </div>
            </div>`
      }
    }
fetchAndRenderData();
</script>

console.log(data);

ownsJava : false,
ownsJavascript : false,
ownsPython : false

app.py get_data():

@app.route('/get_data/<user_id>', methods=['GET'])
def get_data(user_id):
    user = load_user(user_id)
    if user is None:
        return jsonify({"error": "User not found"}), 404
    
    user_data = {
        "ownsPython": user.pythonOwner,
        "ownsJava": user.javaOwner,
        "ownsJavascript": user.javascriptOwner
    }
    extra = request.args.get("extra")
    if extra:
        user_data["extra"] = extra
    return jsonify(user_data)

How do you collect the information regarding the page route and the API it uses in a Vue project?

We have a Vue project that has over 1,000 pages, and all the pages are using a centralized axios-based request module to send requests to BE. In order to know which page uses what APIs, we use axios interceptor to collect the APIs a particular pages uses, that get the current route path the the API about to goes out.

However, we soon find problems, that the mappings we collect is not correct when the API is being handled async, for a simple example, if you have a request in setTimeout, it will mess it up that the routes has changed before the API was actually sent. And it would collect a wrong mapping.

We were trying very hard to find a solution that can actually solve this problem without making massive changes.

I understand the best way of solving this was to leverage the JS closure that fixing the route info for each page component and pass it to the request as a param. Or a request factory method for all pages. But this almost need us to do changes everywhere.

So with these I do need suggestions on an elegant way to solve this with minimum changes. How did your organization do similar things?

Data fetching with React Router using loader functions [duplicate]

{
    path: "/app",
    element: <AppLayout />,
    children: [
      {
        index: true,
        element: <Navigate to="discussions" />,
      },
      {
        path: "discussions",
        element: <Discussions />,
        loader: discussionsLoader,
        errorElement: .....
      }
    ]
  }

Here is the router structure. In the parent component I check for navigaion.state === “laoding” to render a loading indicator properly. But there is one problem.

If I actually want to start the React app with /app/discussions in my URL, then it will actually wait for this data to load before rendering any parent components and I end up with simply white screen untill the data is fetched.

Is there a work around? It would make more sense if actually parent components had gotten rendered, and then data fetching started 🙂

React: POST /refresh not setting refresh_token cookie

I am setting up login and refresh logic for my react app and running into a refresh token issue. I know that the overall refresh logic is sound because on postman it is working just fine. It’s within my application where the problem is.

I have my main server.js on PORT 8080 and authServer.js on PORT 8081. My front end application is using VITE and on http://localhost:5173.

My issue is req.cookies is always an empty object {} and it fails with status 401.

As I said, on postman everything works great. But after logging into my application and refreshing the page, /refresh has the following response:

bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 401
statusText: "Unauthorized"
type: "cors"
url: "http://localhost:8081/refresh

Here is the code:

authServer.js

import express from "express";
import cors from "cors";
import jwt from "jsonwebtoken";
import "dotenv/config";
import bcrypt from "bcrypt";
import cookieParser from "cookie-parser";
import { api } from "./db/queries.js";

const app = express();
const PORT = 8081;
const corsOptions = {
  origin: "http://localhost:5173",
  credentials: true,
};

app.use(cors(corsOptions));
app.use(express.json());
app.use(cookieParser());

// Define routes after middleware

const generateTokens = (user) => {
  // eslint-disable-next-line no-undef
  const accessToken = jwt.sign(user, process.env.VITE_ACCESS_TOKEN, {
    expiresIn: "15s",
  });
  // eslint-disable-next-line no-undef
  const refreshToken = jwt.sign(user, process.env.VITE_REFRESH_TOKEN, {
    expiresIn: "1d",
  });
  return { accessToken, refreshToken };
};

app.post("/refresh", (req, res) => {
  const token = req.cookies.refresh_token;
  if (token == null) return res.sendStatus(401);
  // eslint-disable-next-line no-undef
  jwt.verify(token, process.env.VITE_REFRESH_TOKEN, (err, user) => {
    if (err) return res.sendStatus(403);
    const { accessToken, refreshToken } = generateTokens({ name: user.name });
    res.cookie("refresh_token", refreshToken, {
      httpOnly: true,
      sameSite: "None",
    });
    res.json({ accessToken: accessToken });
  });
});

AuthContext.jsx

import { useContext, createContext, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

const AuthContext = createContext();

const AuthProvider = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [status, setStatus] = useState("");
  const navigate = useNavigate();

  const refreshToken = async () => {
    const url = "http://localhost:8081/refresh";
    console.log("Attempting to refresh token...");

    try {
      const response = await fetch(url, {
        method: "POST",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
        },
      });

      console.log("Received response from /refresh:", response);

      if (!response.ok) {
        console.error(
          `Failed to refresh token. Status code: ${response.status}`
        );
        setStatus(401);
        return;
      }

      const token = await response.json();
      console.log("Received token data:", token);

      const { accessToken } = token;
      console.log("Access token:", accessToken);

      setIsAuthenticated(!!accessToken);
      console.log("Authentication status set to:", !!accessToken);
    } catch (error) {
      console.error("Error occurred during token refresh:", error);
    }
  };

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated,
        refreshToken,
        status,
        setStatus,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export default AuthProvider;

export const useAuth = () => {
  return useContext(AuthContext);
};

ProtectedRoutes.jsx

import { useEffect, useState } from "react";
import { useAuth } from "../context/AuthContext";
import { Navigate } from "react-router-dom";

export const ProtectedRoutes = ({ children }) => {
  const { isAuthenticated, refreshToken } = useAuth();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const refresh = async () => {
      try {
        await refreshToken();
      } catch (error) {
        console.error("Error during token refresh:", error);
      } finally {
        setIsLoading(false);
      }
    };

    if (!isAuthenticated) {
      refresh();
    } else {
      setIsLoading(false); 
    }
  }, [isAuthenticated, refreshToken]);

  if (isLoading) {
    return <div>Loading...</div>; 
  }

  // Once loading is done, check authentication status
  return isAuthenticated ? children : <Navigate to="/login" />;
};

Using React 16 Node Modules in a React 18 Application

“Is it safe to use React 16 node modules in a React 18 application?

I’m working on a React project where I need to incorporate a third-party library that’s built for React 16. I’m concerned about potential compatibility issues and performance impacts when using this library in a React 18 environment.

Are there any specific challenges or workarounds I should be aware of when mixing React 16 and React 18 components?
What are the potential risks involved?

Will it work will react 18 application as we not not using any concurrent feature, will still concurrent rendering will work inside react and cause issue with react 16 node_module as it used lifecyles like unsafe_componentWillMount?

How do I align the button with the center of the neon circle?

What I’m trying to do is align the fingerprint button with the center of the neon loading circle. Also, when I click the finger print button it should start the animation rather than at the start of loading page.

I’ve included the HTML/CSS/JS I’m using right now.

HTML:

<!DOCTYPE html>

<head> 
    <title> @isaranwrap - Chess Lessons</title>
    <link href = "css/style.css" type = "text/css" rel = "stylesheet">
    <script src = "https://d3js.org/d3.v3.min.js"></script>
    <script src = "https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
    <script src = "https://kit.fontawesome.com/fd3faaa138.js" crossorigin="anonymous"></script>
</head>
<!-- 
<a href = "https://github.com/isaranwrap/StandardizingAKI"> jj
    <div id="flaggerLogo"> <img width=132 height=144 src="images/07hexlogo.png" style = "float: left"></div>
</a> -->

<body>

    <div class="card">
        <div class="rating">
            <div class="block">
                <button class="btn">
                <span class="material-icons-outlined"><i class='fas fa-fingerprint'></i></span>
                </button>
            </div>
        </div>
    </div>

        <!-- <div class="rating">
          <h2><span class="counter" data-target="50">50</span><sup>%</sup><br>HTML</h2>
          <div class="block"></div>
      </div>
    </div> -->

    <script>
        document.addEventListener('DOMContentLoaded', function () {
          var circleCursor = document.createElement('div');
          circleCursor.className = 'circle-cursor';
          document.body.appendChild(circleCursor);
        
          document.addEventListener('mousemove', function (e) {
            circleCursor.style.left = e.clientX + 'px';
            circleCursor.style.top = e.clientY + 'px';
            circleCursor.style.display = 'block';
            // document.removeEventListener('mousemove', this);
          });
        });
    </script>

    <script>
        const rating = document.getElementsByClassName('rating')[0];
        const block = document.getElementsByClassName('block');

        for (var i = 1; i < 100; i++){
        rating.innerHTML += "<div class='block'></div>";
        block[i].style.transform = "rotate("+ 3.6 * i + "deg)";
        block[i].style.animationDelay = `${i/40}s`; 
        }
    </script>

    <script src = "code/landingPage.js"></script>
</body>

CSS:

@import url('https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800,900&display=swap');
body {
    background: linear-gradient(
        90deg, rgba(46, 44, 45, 1) 0%,
        rgba(66, 64, 67, 1) 100%
    );
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    height: 100vh;
    margin: 0;
}

html, body, span, button {
    cursor: none;
}

.card {
    z-index:100;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: radial-gradient(#444,#222);
}

.card {
    position: relative;
    width: 200px;
    height: 200px;
}

.card .rating {
    position: relative;
    width: 100%;
    height: 100%;
    /* background: #f00; */
}

.card .rating .block {
    position: absolute;
    width: 2px;
    height: 10px;
    background: #000;
    left: 50%;
    transform-origin: 50% 100px;
    opacity: 0;
    animation: animate 2s linear forwards;
    /* transform: rotate(25deg); */
}

/* .block .btn {
    transform: translate(-50%, -50%);
} */

@keyframes animate {
    to {
        opacity: 1;
    }
}

.card .rating .block:nth-child(-n+51) {
    background: aquamarine;
    box-shadow: 0 0 15px aquamarine, 0 0 30px #0f0;
}

.card .rating h2 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-size: 1.2em;
    font-weight: 500;
    text-align: center;
    line-height: 1.5em;
}

.card .rating h2 span {
    font-size: 2.5em;
    font-weight: 700;
}

.card .rating h2 sup {
    font-size: 1.5em;
    font-weight: 300;
}


.circle-cursor {
    position: fixed;
    width: 10px;
    height: 10px;
    /* background-color: #008ECE; */
    background-color: rgb(135, 206, 235);
    border-radius: 50%;
    pointer-events: auto;
    z-index: 9999;
    display: none;
}

.btn {
    position: relative;
    width: 7em;
    height: 7em;
    border-radius: 50%;
    outline: none;
    border: 4px #090909 solid;
    background: linear-gradient(
        145deg, #171717, #444245
    );
    box-shadow: inset 2px 2px 0px #7d7c7e,
        inset -2px -2px 0px #1c1c1c;
    color: #a6a6a6;
}

.btn span {
    font-size: 2.9em;
}

.btn::before {
    content: "";
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: inherit;
    background: linear-gradient(
        145deg, #262626, #606060
    );
    width: 7.25em;
    height: 7.25em;
    z-index: -1;
    box-shadow: 11px 11px 22px #141414,
                -11px -11px 22px #525252;
}

.button-clicked {
    background: linear-gradient(
        -185deg, #131313, #444245;
    );
    box-shadow: inset -2px -2px 0px #5e5e5e,
        inset 2px 2px 0px #1c1c1c;
}

.button-hover {
    background: #5e5e5e;
}

.icon-clicked {
    color: #0fa;
    text-shadow:
    0 0 7px #fff,
    0 0 10px #fff,
    0 0 21px #fff,
}
/* .icon-clicked {
    color: #fff;
    text-shadow: 0px 0px 15px #008ECE;
} */

/* https://css-tricks.com/how-to-create-neon-text-with-css/ */

Javascript:

// Select the button

const btn = document.querySelectorAll('.btn');

for(let i = 0; i < btn.length; i++) {
    btn[i].addEventListener('click', function(e) {
        btn[i].classList.toggle('button-clicked');
        btn[i].firstElementChild.classList.toggle('icon-clicked');
    })
    btn[i].addEventListener('mouseover', function(e) {
        btn[i].classList.toggle('button-hover');
    })
    btn[i].addEventListener('mouseover', function(e) {
        btn[i].classList.add('button-hover');
    })
    btn[i].addEventListener('mouseout', function(e) {
        btn[i].classList.remove('button-hover');
    })
}

output

I tried messing around with the CSS and JS to no avail.