How can we write (req, res, function) in this way in javascript

Hi I’m trying to make a register route in my page using passport. What I can’t understand is

What passport.authenticate(“local”)(req,res,function(){}) is

I understand passport.authenticate(“local”) is by using local strategy, we judge id/password is right or not. But I have no idea how (req,res, function(){}) after that part works. How can we write like that?

+) “User” in the code is just a model name.

app.post(“/register”, function(req,res){ 
User.register({username:req.body.username}, 
req.body.password, function(err,user){

  if (err) {
    console.log(err);
    res.redirect(“/register”);
    }else{
    passport.authenticate(“local”)(req,res,function(){
      res.redirect(“/secrets”);
});

multiple query-string in react router v6

I want to use two query strings in my URL
when it has both filter=done and search=something
I want to show in URL localhost3000/?filter=done&search=something
but it overwrites one of them and shows only one.
I use HOC to pass the location and navigate to my class component.
this is my code:

class TodoList extends Component {
  constructor(props) {
    super(props);
    const { filter } = queryString.parse(this.props.location.search, {
      ignoreQueryPrefix: true,
    });
    const { search } = queryString.parse(this.props.location.search, {
      ignoreQueryPrefix: true,
    });
    this.searchParams = {
      filter: filter || "all",
      search,
    };
    this.state = {
      todolist: [],
      addtodo: "",
      searchterm: "",
      searchtodolist: [],
      filter: "",
    };
  }

when I click to filter the list, this function is calls

 handleFilter = (value) => {
        this.setState(
          {
            filter: value,
          },
          () => this.replaceUrlFilter()
        );
      };
  replaceUrlFilter = () => {
        this.props.navigate(
          this.state.filter === "all" ? "/" : `?filter=${this.state.filter}`
        );
      };

when I search something in search input, this function is calls

handleSearch = (event) => {
    this.setState(
      {
        searchterm: event.target.value,
      },
      () => this.replaceUrlSearch()
    );
  };
 replaceUrlSearch = () => {
    this.props.navigate(
      this.state.searchterm === "" ? "" : `?search=${this.state.searchterm}`
    );
  };

Get data attribute from element and add class

This jquery code works and it is in use, but somehow my items filter not working with it correctly. But somehow my vanilla js working with that filter I use.

So my question is:

How I can change this jquery code to vanilla js?

$(".cat-name .cat-link").click(function () {

    let catID = $(this).data("id"),
        $allItem = $('.category')

    let $currentItem = $('.cat[data-category=' + catID + ']');
   
    $('.cat[data-category=' + catID + ']').addClass('active');
        $allItem.not($currentItem).removeClass('active');
    
    $('.all-items').removeClass('active'); // Remove active class from "All Items" tab
   
   });

Thanks if you have time to help me!

How do I change the state of an item in a flatlist from another item in the same flatlist?

I’m working on making nested comments that have collapsible replies. To do this I simply render all comments in a flatlist in the order that I receive them and then add a margin to the left based on the level attribute that each item has. The incoming comment data is as follows.

{
    id: "1a",
    parent: "a",
    author: "joemorgan",
    body: "Such an amazing car, had seen this one in Paris earlier!",
    level: 0,
    replies: ["4w", "2f"]
},
{
    id: "4w",
    parent: "1a",
    author: "jason",
    body: "Truly a beast",
    level: 1,
    replies: []
},
{
    id: "2f",
    parent: "1a",
    author: "katparis",
    body: "Rightly said",
    level: 1,
    replies: []
},

I then render these comments using the following flatlist

             <FlatList
                    data={SAMPLE_COMMENTS}
                    keyExtractor={item=>item.id.toString()}
                    renderItem={Comment body={item.body} level={item.level} commentId={item.id} commentChildren={item.replies} />}
/>

Finally, I have wrapped the actual comment component in a Collapsible (react-native-collapsible package). This way I can collapse the specific comment by tapping on it. The ‘collapsed’ prop is set using isCollapsed state.

   const [isCollapsed, setIsCollapsed] = useState(false);


   <Collapsible collapsed={isCollapsed}>
    
        <TouchableWithoutFeedback onPress={()=> setIsCollapsed(true) }>
            <View style={styles.container}>
               

            </View>
        </TouchableWithoutFeedback>

    </Collapsible>

With the above code, I can collapse each individual comment by tapping on it.

The problem is I don’t want to collapse the comment I’m pressing on. I want to collapse its children, to do that I really want to know how I can manipulate the isCollapsed state for the children of a parent comment without affecting the said parent comment. Since every comment has a unique id, I believe it could possibly be done using it perhaps? The children of every comment is also an attribute so maybe that could help as well.

Any leads would be very helpful. Thanks

Automatically generating and display color code after pressing button

I have a button “White color” and I am curious how can I make the text under the button “#White” automatically generate after clicking on it and not be hardcoded as in the example I have below. For example showing as “#000000” after pushing the button.

const buttonColor = document.querySelector("[data-buttColor]");
const pEl = document.querySelector("[data-colorCode]");
const background = document.querySelector("[data-background]");

const buttonColorWhite = document.querySelector("[data-buttColorWhite]");
const buttonColorBlack = document.querySelector("[data-buttColorBlack]");

buttonColor.addEventListener("click", () => {
  let color = "#";
  color += Math.random().toString(16).slice(2, 8);
  background.style.backgroundColor = color;
  pEl.innerText = color;
  console.log(color)
})

buttonColorWhite.addEventListener("click", () => {
  let colorWhite = background.style.backgroundColor = "white";
  let color = "#white";
  pEl.innerText = color;
  console.log(color)

})

buttonColorBlack.addEventListener("click", () => {
  let colorWhite = background.style.backgroundColor = "black";
  let color = "#black";
  pEl.innerText = color;
  console.log(color)
})
<div class="text-center text-white animate__animated animate__flipInX">
  <button data-buttColor class="btn btn-primary btn-lg mt-3">Random color</button>
  <button data-buttColorWhite class="btn btn-primary btn-lg mt-3">White color</button>
  <button data-buttColorBlack class="btn btn-primary btn-lg mt-3">Black color</button>
  <p data-colorCode>The color is</p>
  <p data-background>&nbsp;</p>
</div>

Remove the Operator Signs in textbox [closed]

I’m creating a calculator using the JS, I created buttons so it will concatenate the numbers before clicking the operators. I want to use the eval() funtion to compute the numbers in the textbox but the Operator signs must not be displayed in the textbox. So instead of 2 +1 the result in the textbox will be 2 >>operator button clicked >> 1 then the result would be 3 Any Help? Thanks

<div class = btnDiv1>               
                <button onclick="view('7')">7</button>
                <button onclick="view('8')">8</button>
                <button onclick="view('9')">9</button>
                <button onclick="viewOp('*')">X</button>
                <button onclick="btnClear('')">C</button>
                <br>

                <button onclick="view('4')">4</button>  
                <button onclick="view('5')">5</button>
                <button onclick="view('6')">6</button>
                <button onclick="viewOp('/')">/</button>
                <button onclick="view('')">H</button>
                <br>

                <!-- Create another div so align equal sign buttons -->     
                <div class=btnDiv2>
                    <button onclick="view('1')">1</button>
                    <button onclick="view('2')">2</button>
                    <button onclick="view('3')">3</button>
                    <button onclick="viewOp('-')">-</button>
                    <button onclick="Compute(' ')" class = "btnCmp">=</button>
                    <br>

                    <button onclick="viewNegate('')">+/-</button>
                    <button onclick="view('0')">0</button>
                    <button onclick="view('.')">.</button>
                    <button onclick="viewOp('+')">+</button>
                    <br>                    
                </div>          
            </div>

Javascript
// passed the value of the clicked button
function view(num)
{   
    document.getElementById("txtResult").value+= num;
}

How to generate randome Integers in react js without repeating [duplicate]

When the user press the button next function NextQuestion will be called this function should be able to loop randomly through data (array of objects with two properties name and description) without repeating the same elements each time the user press the button next and then after it finishes showing all elements it should call another function to alert me (for future developing)

import React, {useContext} from 'react';
import CheckAnswer from './CheckAnswer';
import { RandomIntContext } from '../Contexts/RandIntContext';
import { ExamStateContext } from '../Contexts/ExamStateContext';
import { DataContext } from '../Contexts/DataContext';

import { ButtonGroup, ToggleButton, Button } from 'react-bootstrap';

const NextQuestion = () => {

    const {randInt, setRandInt} = useContext(RandomIntContext);
    const {examState, setExamState} = useContext(ExamStateContext);
    const {data} = useContext(DataContext);

    const nextQuestion = () => {
        setRandInt(Math.floor(Math.random() * data.length));
    }

    return (
        <div className="next_cont">
            <div>
                <ButtonGroup>
                    <ToggleButton type="radio" variant="outline-dark" value="word" size="md" checked= {examState === "word"} onClick={(e) => setExamState("word")}> Word</ToggleButton>
                    <ToggleButton type="radio" variant="outline-dark" value="description" size="md" checked= {examState === "description"} onClick={(e) => setExamState("description")}> Description</ToggleButton>
                </ButtonGroup>
            </div>

            <h3>{examState === "word" ? "What is the description of the word" : "What is the word that describes"} {data[randInt][examState]}</h3>

            <CheckAnswer/>

            <div>
                <Button variant="outline-dark" onClick={nextQuestion}>Next</Button>
            </div>
        </div>
    )
}

export default NextQuestion

How to transfer custom SPL token by ‘@solana/web3.js’ and ‘@solana/sol-wallet-adapter’

Hello I am trying to transfer a custom SPL token with the solana-wallet adapter.
However i am having trouble getting the wallet’s secret key/signing the transaction.

I’ve looked at these answers for writing the transfer code but i need to get the Singer and i have trouble figuring out how with solana-wallet adapter. These examples hardcode the secret key and since i’m using a wallet extension this is not possible.

How can you transfer SOL using the web3.js sdk for Solana?

How to transfer custom token by ‘@solana/web3.js’

according to this issue on the webadapter repo https://github.com/solana-labs/wallet-adapter/issues/120 you need to:

  1. Create a @solana/web3.js Transaction object and add instructions to it
  2. Sign the transaction with the wallet
  3. Send the transaction over a Connection

But i am having difficulty finding examples or documentation as to how to do step 1 and 2.

const SendTransaction: React.FC<Props> = ({ children }) => {
    const { connection } = useConnection()
    const { publicKey, sendTransaction } = useWallet()

    const onSendSPLTransaction = useCallback(
        async (toPubkey: string, amount: number) => {
            if (!toPubkey || !amount) return
            const toastId = toast.loading('Processing transaction...')

            try {
                if (!publicKey) throw new WalletNotConnectedError()
                const toPublicKey = new PublicKey(toPubkey)
                const mint = new PublicKey('Mint address')
                const payer = '????' // how to get this Signer
                const token = new Token(connection, mint, TOKEN_PROGRAM_ID, payer)
                const fromTokenAccount = await token.getOrCreateAssociatedAccountInfo(publicKey)
                const toTokenAccount = await token.getOrCreateAssociatedAccountInfo(toPublicKey)

                const transaction = new Transaction().add(
                    Token.createTransferInstruction(
                        TOKEN_PROGRAM_ID,
                        fromTokenAccount.address,
                        toTokenAccount.address,
                        publicKey,
                        [],
                        0
                    )
                )

                const signature = await sendTransaction(transaction, connection)

                const response = await connection.confirmTransaction(signature, 'processed')
                console.log('response', response)
                toast.success('Transaction sent', {
                    id: toastId,
                })
            } catch (error) {
                toast.error(`Transaction failed: ${error.message}`, {
                    id: toastId,
                })
            }
        },
        [publicKey, sendTransaction, connection]
    )

    return <>{children(onSendSPLTransaction)}</>
}

Can’t get user id in TS file in Angular

Can’t get user id in TS file in Angular _id: undefined
Http failure response for http://localhost:5000/users/undefined

Service File:
UpdateUser(userID:any,data : any){
return this.httpClient.put(${environment.APIURL}/users/${userID},JSON.stringify(data),this.options)
.pipe(map((res:any)=>{
return res
}))
}

Optimal setting of triggers in React (similar to Google maps)

I am new to React and I have a question.

I have a conditionally infinite space in 4 directions implemented through a transform translate, like Google maps. I can also move in four directions. However, I have a question about how to implement a trigger to load new objects and simultaneously delete old objects in the React.

I made an implementation via observer, in the form of four divs in all directions. I didn’t really like this solution because of the constant excessive manipulation of the DOM tree, in the form of rebuilding divs after loading objects.

I also tried to make an implementation through a coordinate tracking transformer to calculate the moment of loading objects. But with this implementation, I will need to use setInterval. And that’s not cool (probably).

If you have any idea how it is implemented on Google maps?
Scheme

JavaScript: mouseover function not working in iframe

I have an iFrame and what I want to do is to change the height and width of the div when the mouse hovers around the elements inside the iframe, but the mouseover function is not working. What am I missing?

<html>
  <body>
    <div>
      <iframe
        id="zzz"
        width="500"
        height="500"
        srcdoc="<html><body><h1>hello</h1><button>click</button><div id='abcd' style='background: red; width: 300px; height: 300px;'></div></body></html>"
      ></iframe>
    </div>

    <script>
      window.addEventListener("load", () => {
        var my_iframe = document.getElementById("zzz").contentWindow.document;
        div = my_iframe.getElementById("abcd");
        div.style.background = "blue"; //just for testing

        my_iframe.addEventListener("mouseover", function (e) {
          elem = e.target;
          var rect = elem.getBoundingClientRect();
          w = rect.width;
          h = rect.height;
          div.style.width = w;
          div.style.height = h;
        });
      });
    </script>

  </body>
</html>

How to search number from html table using javascript?

I am having difficulty searching numbers from the HTML table using javascript. What I want to do, if I enter 500 then the results should be 500 and numbers that are also greater than 500. F
I checked other StackOverflow questions but it is not answered as I expected. Can anyone help me, please?

HTML CODE:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Number</th>
    <th style="width:40%;">Alphabats Code</th>
  </tr>
  <tr>
    <td>500</td>
    <td>ANAA</td>
  </tr>
  <tr>
    <td>520</td>
    <td>MNAAA</td>
  </tr>
  <tr>
    <td>400</td>
    <td>INNA</td>
  </tr>
  <tr>
    <td>200</td>
    <td>OISSS</td>
  </tr>
  <tr>
    <td>500</td>
    <td>QIIWS</td>
  </tr>

</table>

JavaScript Code – or Example, if I search 500 then the result should come 500, 520. I mean must be greater then and equal to the number which I put in search field.

function myFunction(){

   let filter = document.getElementById('myInput').value;
   let myTable = document.getElementById('myTable');
   let tr = myTable.getElementsByTagName('tr');
   for(var i=0; i<tr.length; i++)
   {
     let td = tr[i].getElementsByTagName('td')[0];
     if(td)
     {
       let textValue = td.textContent || td.innerHTML;
      if(textValue >= filter  )
      {

        tr[i].style.display = "";

      }
      else 
      {
        tr[i].style.display = "none";
      
      }

     }

   }


}