Does anyone know how to create a menu without exiting the page?

Does anyone know how to create a menu without exiting the page? I want to create a settings menu.

<style>
.material-symbols-outlined {
   align: right;
  font-variation-settings:
  'FILL' 0,
  'wght' 400,
  'GRAD' 0,
  'opsz' 48
         }
      </style>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />

     <a OnClick="open()" <span class="material-symbols-outlined">
engineering
</span></a>
<div class="menu">
<p>Settings</p>
</div>

(I know that i should not use onclick but i don’t know how to use anything else)

<script>
function show(){
div.menu.show=(true)
}
</script>

I wanted it to show div but div is always shown

Mongoose deleting object ($pull) in Array does not work

I’m trying to delete a object inside a array in my db uising the $pull in Mongoose but does not work.
This is my attempt:


const listSchema = new Schema({
    name: String,
    items: []
});

const List = mongoose.model("list", listSchema);

const itemDeleted = req.body.checkbox;
// i get here the ID of the object inside the array
const itemListDeleted = req.body.listDeleted;
// Here the name of the object that contains the array
List.findOneAndUpdate({name:itemListDeleted},{$pull:{items:{_id: itemDeleted}}},function (err,foundList) {
        if (foundList){
            res.redirect("/"+ itemListDeleted);
        } else {
            console.log(err);
        }
    })

I searched for solutions and every body recomends using $Pull but in my case it doesn’t work. I log the const and all things appers to be right. Please i need help!

Is it possible to call RichTextValueBuilder.setTextStyle( ) multiple times programmatically?

I got this these values.

enter image description here

And I want to have this result.

enter image description here

So I made the following test code and tried it to the first cell.

function test2() {
  const ss = SpreadsheetApp.getActive();
  const sheet = ss.getSheetByName("richText3");
  const range1 = sheet.getRange("A1");
  const text1 = range1.getValue();
  Logger.log(text1);
  const re = new RegExp(/([ a-zA-Z/']*)?/dg);  
  const redBold = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor('red').build();
  let array;
  while ((array = re.exec(text1)) !== null) {
    const [start, end] = array.indices[0];
    const richTxtValBlder = SpreadsheetApp.newRichTextValue()
        .setText(text1)
        .setTextStyle(start, end, redBold)
        .build();
    range1.setRichTextValue(richTxtValBlder);   
  }  
}

After first try, I got this result.

enter image description here

I checked the Reference Document again and I found this comment.

setText(text) : Sets the text for this value and clears any existing text style.
When creating a new Rich Text value, this should be called before setTextStyle()

I found that I should call .setText() once and call .setTextStyle() multiple times.
But the problem is .setTextStyle() should be called programmatically according to the number of patterns in each cell and I cannot find how to do it programmatically.

Each cell may have 0 to 10 patterns and I don’t want to make 10 different richTExtValueBuilder which only differ in the number of .setTextStyle() calls.

Do you have any different ideas ?

Discord JS unknown interaction

this is my first time posting here. I have a question, sorry if my question format is not professional. So my question is, when I execute a command in discord.js, it executes perfectly, but when I check the terminal, I always see unknown interaction. Usually what I know is when an unknown interaction error occurs, the command won’t be executed, but my command is executed perfectly even with an unknown interaction error in the terminal. Does anyone know why? Thank you

I have tried to use await deferReply and return editReply but it still shows that error. I want to know why the command still executed perfectly even if I got the error, also I want to know if is there any solution to fix this.

Browser won’t show my input value in address bar, and won’t log values in console

Basically when I type simple form like this

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="loginContainer">
      <form>
        <div>
          <label for="name">Name:</label>
          <input id="name" type="text" />
        </div>

        <div>
          <label for="password">Password:</label>
          <input id="password" type="password" />
        </div>

        <input type="submit" value="Login" />
      </form>
    </div>

    <script>
      let nameVal = document.getElementById("name").value;
      let passwordVal = document.getElementById("password").value;

      console.log(nameVal);
      console.log(passwordVal);
    </script>
  </body>
</html>

My browser just shows in the address bar file:///C:/Users/User1/Desktop/index.html?, and also it won’t log my name and password in console, it just looks like the page refreshes when I click the submit buttton and that’s it, I remember before when I did stuff with forms, it would usually write in the address bar something like “…index.html?name=somerandomdata”, did I write the form right? It seems like it doesn’t process input values at all..I’m confused

I tried on firefox this same code, same result

Add object to array in class component

I have a list of products (unordered list which I apply at the beginning and it shows on screen) and after click on one of them for example: milk, app should add it on screen to list “to buy”. But it shows on the screen after I click on another element or second time on the first one. It also not working when I only console.log() in addProduct

import React from "react";

import commonColumnsStyles from "../../common/styles/Columns.module.scss";

class ProductsList extends React.Component {
  constructor(props) {
    super(props);
    this.state = { productsToBuy: [] };

    this.addProduct = this.addProduct.bind(this);
  }

  addProduct(index) {
    let newProduct = [
      this.props.productsToDisplay.filter(
        (currEl, currIndex) => currIndex === index
      ),
    ];
    this.setState({
      productsToBuy: this.state.productsToBuy.concat(newProduct),
    });
    this.props.sendAddedProductsToParent(this.state.productsToBuy);
    console.log(this.state.productsToBuy);
  }

  render() {
    return (
      <div className={commonColumnsStyles.App}>
        <header className={commonColumnsStyles.AppHeader}>
          <p>Products list</p>
          <ul>
            {this.props.productsToDisplay.map((currProduct, index) => (
              <li key={index} onClick={() => this.addProduct(index)}>
                {currProduct.nazwa}
              </li>
            ))}
          </ul>
        </header>
      </div>
    );
  }
}

export default ProductsList;

I have tried setState (in function addProduct) with .concat. It appears immediately when I’ve used .push method but after click on second element this.state.productsToBuy.push is not a function.

After all I display this products by map method in another function component.

modules not found node.js

Am trying to run file with , a node run index.js. which inside the folder flashloan test but this is an error that I keep getting,…

node:internal/modules/cjs/loader:1042
  throw err;
  ^

Error: Cannot find module '/home/schette/Documents/flashloan test/run'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
    at Module._load (node:internal/modules/cjs/loader:885:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
    at node:internal/main/run_main_module:23:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

Node.js v19.2.0

what could be the problem, any solution? i tried to remove npm and and reinstall, but still.

I deleted npm packges and reinstall it. I also edited json packeg, scripts with start: node main.js

Get values ​in a function from another function

i have a button when registering to which i get the attribute attribute element, from the “clickTarget” function i need to pass this value to the “addImg” function

btn.addEventListener('click', clickTarget)
function clickTarget(e) {
    e.preventDefault()
    let target = e.target.closest('a')
    let { index } = target.dataset;
}
function addImg() {
    img.src = `${imgObject[index]}`
}

Prevent concurrent api pulls on page refresh

I’m learning REST api along with the MEVN stack and am looking for some guidance on how to improve my code when it comes to interfering with pulling information from an external api and pushing it to my mongo database. The problem is that the process of pulling information from a different api and saving it to my own database takes so long (I am rate limited pulling from the external api) such that if a user were to refresh the page, it can either break the process or send another identical request – both of which cause issues down the line.

Is there a way I can isolate the “read from external api & write to own database” process from user interactions/page reload once a request gets sent through? I’ve been trying to kiddy-proof the code to basically have a request pick up where it left off if a user were to reload the page, however I’m wondering if there’s a more robust method, such that on page reload, is more-so:

Hey man, I see you’ve sent in an identical request for information I’m already working on. How about I dismiss that request and keep working on the current one to reduce headache?

Code below is of basic architecture. The server code block is simplified and a lot of the kiddy-proofing logic is omitted for clarity.

// Codeblock on frontend to send request to server.
<script>

// template method that sends initial request.
async lookup() {
  const url = `http://localhost:5000/api/name/${this.$route.params.region}/${this.$route.params.username}`
  try {
    const res = await axios.get(url)
    this.nameInfo= res.data.shift()
    this.userReadyRender = true
  } catch (err) {
      console.log(err)
    }
</script>
<template>
// template things
</template>
// server.js on localhost:5000

const router = express.Router()

router.route('/:region/:name')
  .get(async (req, res) => {

    // Connect to mongodb
    await connectToMongo()

    // Check if the name exists in external api database
    const user = await checkExistence(req.params.name, req.params.region)

    if (user) {
      // Do multiple things:
      // 1) Insert new collection into database named `req.params.name`
      // 2) Pull information X from external api which is an array ranging from 50-800 elements
      // 3) Iterate through every X[i] which returns an object Y
      // 4) Push each object Y to a newly created document in the collection created in step 1

      // collection variable below is the collection in step 1
      res.send(collection)
    }
  })
 

Missing authorization header and hook return undefined while searching for data

Currently I’m working with a chat application which is based on json-server now the problem is while I’m requesting for conversations with like search (http://localhost:9000/[email protected]&_sort=timestamp&_order=desc&_page=1&_limit=5) it showing 200 response but data won’t shown up! while I check the json server it showing “missing authorization header”

Here is my conversation api

import { apiSlice } from "../api/apiSlice";

export const conversationsApi = apiSlice.injectEndpoints({
    endpoints: (builder) => ({
        //endpoints here
        getConversations: builder.query({
            query: (email) => `/conversations?participants_like=${email}&_sort=timestamp&_order=desc&_page=1&_limit=5`, 
        })
        
    })
})

export const {useGetConversationsQuery } = conversationsApi;
here is my converation slice
`

import { createSlice } from ‘@reduxjs/toolkit’
const initialState = {}

const conversationsSlice = createSlice({
name: “conversations”,
initialState,
reducers: {}
})

// export const { } = conversationsSlice.actions;
export default conversationsSlice.reducer;

`

here is my apiSlice

import { createApi, fetchBaseQuery } from ‘@reduxjs/toolkit/query/react’

export const apiSlice = createApi({
reducerPath: “api”,
baseQuery: fetchBaseQuery({
baseUrl: process.env.REACT_APP_API_URL,
prepareHeaders: async (headers, { getState, endpoint }) => {
const token = getState()?.auth?.accessToken;
if (token) {
headers.set(“Authorization”, Bearer ${token});
}
console.log(headers)
return headers;
}
}),
tagTypes: [],
endpoints: (builder) => ({

})

})

Getting the error message `error.toJSON() is not a function` while handling errors in axios

When I run my code, i get the message error.toJSON is not a function. How am I supposed to handle this error better?


const installDependencies = async (BASE_URL, body) => {
  try {
    const headers = {
      "Content-type": "application/json",
    };
    const response = await axios.post(`${BASE_URL}/data`, body, { headers });
    return response;
  } catch (error) {
    console.error(error.response?.data, error.toJSON());
    throw new Error("Failed to install dependencies");
  }
};

How to get the response of Firebase Messaging in django (FCM-DJANGO)

I’am trying to get the response errors from Firebase_Admin in my django application, because some users are not reciving the notifications, but when I use the code below I only recive a FirebaseResponseDict() with a batchResponse, the registration_ids_sent and deactivated_registration_ids inside
for example:

FirebaseResponseDict(response=<firebase_admin.messaging.BatchResponse object at 0x053E124>, registration_ids_sent=['...','...','...'],deactivated_registration_ids=[]
I need the error detail to know why some users are not reciving push notifications

I need the error detail to know why some users are not reciving push notifications

This is my Code:
`

devices.send_message(Message(webpush=WebpushConfig(notification=WebpushNotification(title=noticia.titulo, body=noticia.resumo, image=noticia.capa.url, icon=icone), fcm_options=WebpushFCMOptions(link='https://site/'+str(id)))))

`
any help will be helpfull

I am new in react i want to convert normal javascript code to the react i don’t know how to do that

this is my react java script where i want to insert the normal js code.
I have tried by using the {} brackets but that won’t run.

import './App.css';


function App() {
  


  return (
    
    <>
    <div className="container"></div><div className="box">
      <div className="wrapper">
        <div className="form-wrapper sign-in">
          <form action="">
            <h2 className="he">Login</h2>
            <div className="input-group">
              <input className="ip1" type="text" required/>
                <label for="">Username</label>
                <i></i>
              </div>
            <div className="input-group">
              <input type="password" required/>
                <label for="">Password</label>
                <i></i>
              </div>
  
            <button type="submit">Login</button>
            <div className="signUp-link">
              <p className="p1">Don't have an account? <a href="#" className="signUpBtn-link">Sign Up</a></p>
            </div>
          </form>
        </div>

        <div className="form-wrapper sign-up">
          <form action="">
            <h2 className="he2">Sign Up</h2>
            <div className="input-group">
              <input type="text" required/>
                <label for="">Username</label>
                <i></i>
              </div>
            <div className="input-group">
              <input type="text" required/>
                <label for="">Email</label>
                <i></i>
           
            <button type="submit">Sign Up</button>
            <div className="signUp-link">
              <p>Already have an account? <a href="#" className="signInBtn-link">Sign In</a></p>
            </div>
          </form>
        </div>
      </div>
    </div></>
 );
}
export default App;

This is the code that i wanto to merge.
I Want to merge the following code in the above code. I have a normal javaScript code but i don’t know how to write it in the React

const signInBtnLink = document.querySelector('.signInBtn-link');
const signUpBtnLink = document.querySelector('.signUpBtn-link');
const wrapper = document.querySelector('.wrapper');

signUpBtnLink.addEventListener('click', () => {
    wrapper.classList.toggle('active');
});

signInBtnLink.addEventListener('click', () => {
    wrapper.classList.toggle('active');
});