Text appearing under NavBar -REACT

I don’t know why when i click on the About icon (or other icons in the menu bar), I get the text under my NavBar instead of having it next to it.

The NavBar.jsx component:

import './NavBar.css'
import logo from "../Components/logo";
import { ITEMS } from "../Navigation";
import React from 'react'

export default function NavBar() {
    return (
        <div className="NavBar">
            <img className="logo" /> 
            <span className="textLogo">LOGO</span>
            <div className ="NavbarList">
                {ITEMS.map((item, i) => {
                    return (
                        <li key={i} className="row" id={window.location.pathname === item.href ? "active" : ""} 
                        onClick={() => {window.location.pathname = item.href;}}>                      
                            <div id="icon">{item.icon}</div>
                            <div id="title">{item.title}</div>   
                        </li>
                    );
                    
                })}
             
            </div>
        </div>
    );
}

My NavBar.css :

.NavBar{
  width: 15rem;
  height: 100vh;
  padding-top: 1rem;
  padding-bottom: 1rem;
  --tw-bg-opacity: 1;
  background-color: rgb(35,37,79);
  flex-direction: column;
  gap: 1.25rem

} 

.NavbarList{
padding-top:20px;
  
    }
...

And here the picture of what i get (there are other icons above About):
enter image description here

(I’m not able to put all the css file, because it says “too many codes”)

running setState right before submit is not submitting the correct information due to it being asynchronous

I am trying to run a function before setting state when the user clicks submit, but due to it being asynchronous I’m not getting the information that I’m looking for. The function splits a string into an array that is then set in state right before submit:

const [post, setPost] = useState({ title: '', description: '', tags: [] });
const [tagInput, setTagInput] = useState('');

const handleSubmit = (e) => {
    e.preventDefault();
    setPost((prevState) => ({
      ...prevState,
      tags: [
        ...tagInput
          .split(',')
          .splice(2)
          .map((value) => value.trim().replace(/[W_]+/g, '')),
      ],
    }));
   createPost(post)
          .then((response) => console.log(response))
          .catch((err) => console.log(err));
};

these values are coming from an input that holds ‘tags’ that the user submits.

<input
  type='text'
  placeholder='politics, humanitarian, nationalParks'
  name='tags'
  className='post-form-input'
  value={tagInput}
  onChange={handleTagInput}
/>

the value of that input is set to another state:

const [tagInput, setTagInput] = useState('');

which as shown above is then parsed and set into my ‘post’ state. onSubmit() I’m losing the tags, they aren’t saving. How can I implement this to get the array to save?

Resize the windows and get a stylish scroll bar for the menu

what parameters do i have to add in my NavBar.css (i.e menu in left side) if I want to see a scroll bar (in transparent white) appearing when i resize my windows (i.e I can scroll down or up if the window is not at the max so I can still scroll the menu and see the other icons) please ?

.NavBar{
  width: 15rem;
  height: 100vh;
  background-color: #FF7F50 ;
  flex-direction: colums;
  gap: 1.25rem

} 

This is what i want to have not in green but in transparent/grey bar .

enter image description here

Discord.JS Get Attachment URL and send in channel

I come once again to ask you a question, I have this bot code “discord.js v13”, I need to get the URL of the attached file and send the link right away. how can I do this? I will leave the code part below

            // save file in folder 'musicas'
            stream.pipe(createWriteStream(__dirname + `/musicas/${pegaid}.mp3`)).on('finish', () => {

                // Sending the attachment, and its link
                try {
                    message.channel.send({
                        files: [{
                            attachment: (__dirname + `/musicas/${musicid}.mp3`),
                            name: `${musicid}.mp3`
                        }],
                    });
                } catch (e) {
                    return message.channel.send(`${message.author}, Error ao tentar converter a música!`);
                }

When is it necessary to automate a task in a website or javascript game?

So what I mean by “automate” is using a setInterval() to. well. you know: automate the task or multiple tasks. For example in a game you could use a setInterval() to automatically update a health bar or a stamina bar, and maybe on a website you might use it to update statistics (it doesn’t matter what they are). At what point does it become over-used or unneeded? and when would you need to have something like this?

Reverse bits Leetcode question solution not passing all tests

This is the question and this is my solution which is not getting accepted. What am I doing wrong?

/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function(n) {
    let arrOne = [];
    let arrTwo = [];
    let num = 0;
    arrOne = n.toString(2).split("");
    let m = 0;
    for (let i = arrOne.length - 1; i >= 0; i--) {
        arrTwo.push(arrOne[i]);
    }
    console.log(arrTwo);
    for (let k = arrTwo.length - 1; k >= 0; k--) {
        if (arrTwo[k] == 1) {
            num += (2**m);
        }
        m++;
    }
    return num;
};

Showing a forEach inside a forEach?

Im pretty sure this isn’t the way to do it. But, I have a number of rounds for exercises between 1-5 (lets say) and inside these rounds ill have a number of exercises anywhere between 2-8.

I am able to create a forEach to show the rounds. But how do I show the exercises as well.

I know its showing double the amounts of rounds and not showing any exercises with the way im doing it (which I know wouldn’t work).

How would I show the forEach of exercises with the correct round (thats also a forEach)?

const Rnds = document.getElementById("rnds");

const rd = query(collection(db, "user", uid, "yourWorkouts", id, "rounds"));

const uns = onSnapshot(rd, (querySnapshot) => {
  querySnapshot.forEach((doc) => {
    console.log("rounds", doc.data());

    const DocId = doc.id;
    const Title = doc.data().title;

    const rdex = query(
      collection(
        db,
        "user",
        uid,
        "yourWorkouts",
        id,
        "rounds",
        docId,
        "exercises"
      )
    );
    querySnapshot.forEach((doc) => {
      console.log("exercises", doc.data());

      const ExName = doc.data().exerciseName;

      Rnds.innerHTML += `
        <h2>${Title}</h2>                        
        <p>${ExName}</p>
      `;
    });
  });
});

I am fetching the data form Firestore.

Access database connection in child thread

I have an application that uses worker_threads. When the application starts up, I create a connection to the database in the main project, then when I start a thread, is it possible to access that database connection without having to connect to the database in the child thread?

// main.database.ts
export abstract class SqlDatabase {
  private static db: Database;
  static connect(dbPath: string) {
    this.db = new Database(dbPath);
  }
  mutate(sql: string, ...parameters: string[]) {
    const stmt = SqlDatabase.db.prepare(sql);
  }
}


// files.database.ts
class FilesDatabase extends SqlDatabase {
  someFunction(){}
}
export const files = new FilesDatabase();


// index.ts
SqlDatabase.connect('/path/to/sqlite.db');

Then I have an action which starts up a Worker process:

export function runThread(file: string, args: { [key: string]: any; }) {
  return new Worker(path.resolve(__dirname, './worker.js'), {
    workerData: {
      aliasModule: file,
      ...args
    }
  });
}

In the worker process I have something like this:

import { files } from '../../database/files.database';
files.someFunction();

When running the process I get the following error message:

const stmt = SqlDatabase.db.prepare(sql);

Is there a way that I can get access to this database without having to make another connection in the child?

Array of objects isn’t empty but ngFor* shows as if there are none

I use an HTTP Get request to get a list of notifications, the name could be misinterpreted because it is just a list of posts that is collected, it doesn’t change. The problem is that I use an array to collect all the notifications with an interface and it doesn’t display them.

If I use a button called test to check the content of the array I see that all the objects are in the array yet it doesn’t work. error message

The example under load more is an example of one notification and how it should look like (hardcoded)
example

Code overview.component.html

<div class="content-wrapper">
  <div class="container-fluid">
    <div class="card mb-3">
      <div class="card-header">
        <i class="fas fa-bell"></i> Notifications
      </div>
      <div class="card-body">
        <div class="list-group list-group-flush small">
          <app-notification *ngFor="let notification1 of notifications" icon1="{{notification1.icon}}" message1="{{notification1.message}}"></app-notification>

          <button mat-raised-button (click)="test()">test</button>
          <a class="list-group-item list-group-item-action">Load more...</a>
        </div>
      </div>
    </div>
  </div>
</div>
<p *ngFor="let notif of notifications">{{notif.id}}</p>

Code overview.component.ts

export class OverviewComponent implements OnInit {

  notifications : Notificatie[] = [];

  constructor(private NotificationService: NotificationServiceService) { }

  ngOnInit(): void {
  this.NotificationService.getNotifications().subscribe((reponse => {this.notifications = Object.values(reponse)}));
  }
  test(){
    console.log(this.notifications);
  }

}

Code Notificatie Interface

export interface Notificatie {
    id?:number;
    message:string;
    icon:string;
}

Code Notification Service

export class NotificationServiceService {

  constructor(private http:HttpClient) { }

  url = "http://www.mocky.io/v2/5be453402f00002c00d9f48f";
  

  // Observable<Notificatie[]>
  getNotifications(): Observable<Notificatie[]>{
    return this.http.get<Notificatie[]>(this.url)
    
  }
}

Mongoose return 10 results sorted by date for every user id in array of ids

lets say we have an array of user ids :

    "ids": [
        "623d71c628820d09797be558",
        "62419d6477775214de099838",
        "62419d7877775214de099845",
        "62419d8877775214de09984c"
    ]

and we want to return the first 10 documents of every id sorted by date. I know we can do :

  const docs = await Model.find({ id: { $in: ids } })
    .sort("date")
    .limit(10);

which returns 10 documents sorted by date,but not for every user,how could i return 10 for every one in array ?

Having trouble accessing the nested values of my object. JavaScript

So I am trying to create a function that will list all the stats of a specific player in below object. I am simply trying to return the nested object associated with the playerName itself. I’m guessing map isn’t working for me here. Instead I am returning an array of the individual letters of the name “Jeff Adrien”. Can someone help me understand where I am going wrong?

//Code in question
function playerStats(playerName) {
    let specificPlayer = allPlayers().players

    if (playerName === specificPlayer) {
        return specificPlayer
    }
    const stats = Object.values(playerName).map((nums) => {
        return [nums]
    })
    return stats.flat()
}

console.log(playerStats('Jeff Adrien'))

// details

function allPlayers() {
    const everyPlayer = Object.assign(homePlayers, awayPlayers)
    return everyPlayer
}

const gameObject = () => {
    return {
        home: {
            teamName: 'Brooklyn Nets',
            colors: ['black', 'white'],
            players: {
                'Alan Anderson': {
                    number: 0,
                    shoe: 16,
                    points: 22,
                    rebounds: 12,
                    assists: 12,
                    steals: 3,
                    blocks: 1,
                    slamDunks: 1,
                },

                'Reggie Evans': {
                    number: 30,
                    shoe: 14,
                    points: 12,
                    rebounds: 12,
                    assists: 12,
                    steals: 12,
                    blocks: 12,
                    slamDunks: 7,
                },
                'Brook Lopez': {
                    number: 11,
                    shoe: 17,
                    points: 17,
                    rebounds: 19,
                    assists: 10,
                    steals: 3,
                    blocks: 1,
                    slamDunks: 15,
                },
                'Mason Plumlee': {
                    number: 1,
                    shoe: 19,
                    points: 26,
                    rebounds: 12,
                    assists: 6,
                    steals: 3,
                    blocks: 8,
                    slamDunks: 5,
                },
                'Jason Terry': {
                    number: 31,
                    shoe: 15,
                    points: 19,
                    rebounds: 2,
                    assists: 2,
                    steals: 4,
                    blocks: 11,
                    slamDunks: 1,
                },
            },
        },

        away: {
            teamName: 'Charlotte Hornets',
            colors: ['turquoise', 'purple'],
            players: {
                'Jeff Adrien': {
                    number: 4,
                    shoe: 18,
                    points: 10,
                    rebounds: 1,
                    assists: 1,
                    steals: 2,
                    blocks: 7,
                    slamDunks: 2,
                },

                'Bismak Biyombo': {
                    number: 0,
                    shoe: 16,
                    points: 12,
                    rebounds: 4,
                    assists: 7,
                    steals: 7,
                    blocks: 15,
                    slamDunks: 10,
                },
                'DeSagna Diop': {
                    number: 4,
                    shoe: 14,
                    points: 24,
                    rebounds: 12,
                    assists: 12,
                    steals: 4,
                    blocks: 5,
                    slamDunks: 5,
                },
                'Ben Gordon': {
                    number: 8,
                    shoe: 15,
                    points: 33,
                    rebounds: 3,
                    assists: 2,
                    steals: 1,
                    blocks: 1,
                    slamDunks: 0,
                },
                'Brendan Haywood': {
                    number: 33,
                    shoe: 15,
                    points: 6,
                    rebounds: 12,
                    assists: 12,
                    steals: 22,
                    blocks: 5,
                    slamDunks: 12,
                },
            },
        },
    }
}

What does event.body?

I am new and I would like to find someone to help me understand the two lines explained below. In particular I cannot understand what event.body returns in this line:

let requestJSON = JSON.parse (event.body);

and what returns JSON.stringify (body) in this line:

body = JSON.stringify (body).

Can anyone kindly help me understand?

const AWS = require("aws-sdk");

const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context) => {
    let body;
    let statusCode = 200;
    const headers = {
        "Content-Type": "application/json"
    };

    try {
        switch (event.routeKey) {
            case "PUT /items":
                let requestJSON = JSON.parse(event.body);
                await dynamo
                    .put({
                        TableName: "http-crud-tutorial-items",
                        Item: {
                            id: requestJSON.id,
                            price: requestJSON.price,
                            name: requestJSON.name
                        }
                    })
                    .promise();
                body = `Put item ${requestJSON.id}`;
                break;
            default:
                throw new Error(`Unsupported route: "${event.routeKey}"`);
        }
    } catch (err) {
        statusCode = 400;
        body = err.message;
    } finally {
        body = JSON.stringify(body);
    }

    return {
        statusCode,
        body,
        headers
    };
};```


Obviously I refer to the example shown.

add an input to a foreach loop with pagination : don’t see it to other pages

In my html I have a some data displayed with a foreach loop. I created a small form inside with an input checkbox and I have a pagination system.

My issue is when I change the page, I didn’t see my checkbox, I see it only in the firstpage or when I refresh the second page.

there is a part of my code :

<form>

<div>

  {% for annonce in annonces %}

   {{SomeDataDisplayed}}

 <input type="checkbox"/>

 {% endfor %}

 <input type="submit" />

</div>

</form>

Someone can explain me why that happen and how can I fix it ?

thanks you

Can I use vue-router to data-bind a dropdown’s value to a URL’s query parameter?

I want to bind a dropdown to a query parameter in the URL, so

  • when opening /page?dropdown=foo, I want the dropdown to have foo pre-selected
  • and the other way round: when changing the dropdown’s value to bar, to have the URL rewritten into /page?dropdown=bar.

My question now:
Is there an out-of-the-box way to tell vue-router to data-bind this?

Or do I need to do it by hand, so when entering/changing the route, setting the dropdown’s value and using a :onchange on the dropdown to call router.replace()?