How to update my useEffect hook when State change happen in a different .js file’s component in ReactJS?

I am trying to make an API call in useEffect() and want useEffect() to be called everytime a new data is added in the backend.
I made a custom Button(AddUserButton.js) which adds a new user in backend. I am importing this button in the file (ManageUsers.js) where I am trying to display all the users. I just wanted to make an useState to keep track everytime an add button is clicked and make useEffect refresh according to it. For Example:

const [counter, setCounter] = useState(0);
...
const handleAdd = () => {
  setCounter(state => (state+1));
};
...
useEffect(() => {
 // fetch data here
 ...
}, [counter]);
...
return(
 <Button onClick = {handleAdd}> Add User </Button>

);

But currently because I have two .js files, I am not sure how to make my logic stated above
work in this case

ManageUsers.js

import AddUserButton from "./AddUserButton";
...
export default function ManageShades() {
...
useEffect(() => {
  axios
  .get("/api/v1/users")
  .then(function (response) {
    // After a successful add, store the returned devices
    setUsers(response.data);
    setGetUserFailed(false);
  })
  .catch(function (error) {
    // After a failed add
    console.log(error);
    setGetUserFailed(true);
  });
console.log("Load User useeffect call")

 },[]);
 return (
<div>
  ...
    <Grid item xs={1}>
      
      <AddUserButton title = "Add User" />
      
    </Grid>
  ...
</div>
);
}

AddUserButton.js

export default function AddDeviceButton() {
...

return (
 <div>
  <Button variant="contained" onClick={handleClickOpen}>
    Add a device
  </Button>
 ...
 </div>
 );
} 

mongoose.connection.once(‘open’) callback never firing

I’m currently setting up a custom Node server with Next.js. The fact that I’m using Next.js shouldn’t make any difference though.

In previous apps, I’ve always used mongoose.connection.once('open', callback) to start listening only when the database is open. This time, it’s not working.

This is my connection configuration file:

import mongoose from 'mongoose';
import { MONGO_URI } from '../constants'; // looks like 'mongodb://localhost/my-db' in development

mongoose
    .connect(MONGO_URI, () => {
        try {
            console.log(`Connected to ${MONGO_URI} with Mongoose.`);
        } catch (err) {
            throw err;
        }
    })

export default mongoose.connection;

I am importing this and using it in my main.ts file like so:

import express from 'express';
import next from 'next';

import * as dotenv from 'dotenv';
import logger from 'morgan';
import compression from 'compression';
import helmet from 'helmet';

import rateLimiter from './config/rateLimiter';
import db from './config/connection'; // This is the config file

dotenv.config();

const PORT = process.env.PORT || '8000';
const dev = process.env.NODE_ENV !== 'production';

const nxt = next({ dev });
const handle = nxt.getRequestHandler();

nxt.prepare().then(() => {
    const app = express();

    app.enable('trust proxy');

    app.use(logger('dev'));
    app.use(helmet());
    app.use(rateLimiter);
    app.use(compression());
    app.use(express.urlencoded({ extended: false }));
    app.use(express.json());

    db.once('open', () => {
        app.listen(PORT, () => {
            // This log never happens
            console.log(`Listening on port ${PORT}.`);
        });
    });
});

It’s extremely strange, because “Connected to mongodb://localhost/my-db with Mongoose.is in fact logged when using the code above, but the express app simply never listens; however, when I remove the app.listen out of the db.once callback function, “Listening on port 8000” does of course get logged.

I’m stumped. Why isn’t the 'open' event firing? I’ve verified that mongo is working locally through the Mongo shell, and this same exact code was working when I had the folder which these files are in (server) separate from the Next.js app (when I was still debating which type of view layer to write).

Conditionally assert element values in DOM depending on it’s value in backend with Cypress?

Trying to do Cypress Testing with my React app.

I’m retrieving an object with an attribute expirationDate from the backend. It’s an integer with format YYYYMMDD. In my corresponding frontend in the <input> component, it’s rendered as an YYYY-MM-DD string.

However the object may optionally not have an expiration date at all, which is instead represented as the attribute being -1 or -2. This is presented as an empty string ” in the <input>.

I thus need to conditionally check the value. How do I go about doing this with Cypress?

Closest I have right now is

cy.get('#input-expiration-date').should('have.value', expirationDate || '')

But this is not really an accurate test.

Rails AJAX Form Not Showing Up

I am trying to implement a contact form on my one-paged portfolio site using the mail_form gem and cannot seem to get the form to show up when using AJAX. I resorted to AJAX in place of the redirect_to approach because I do not want the site to refresh and scroll down to the anchor upon submission.

views/pages/home.html.erb:

<%= render 'contacts/new' %>

<div id="contact_form"></div>

config/routes.rb:

Rails.application.routes.draw do
  root 'pages#home'
  resources :contacts, only: [:new, :create]
end

models/contact.rb:

class Contact < MailForm::Base   
  attribute :name, validate: true   
  attribute :email, validate: /A([w.%+-]+)@([w-]+.)+([w]{2,})z/i   
  attribute :message, validate: true   
  attribute :nickname, captcha: true

  def headers
    {
      subject: "Regarding Your Portfolio",
      to: "email (removed for privacy)",
      from: %("#{name}" <#{email}>)
    }   
  end 
end

controllers/contacts_controller.rb:

class ContactsController < ApplicationController
  before_action :contact_params, only: [:new, :create]

  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact])
    @contact.request = request
    
    if @contact.deliver
      respond_to do |format|
        # format.html {redirect_to root_path(anchor: "contact"), notice: 'Thank you for your message! I will get back to you shortly.'}
        format.html {flash.now[:notice] = 'Thank you for your message! I will get back to you shortly.'}
        format.js {render partial: 'contacts/new'}
      end
    else
      respond_to do |format|
        format.html {flash.now[:alert] = 'Your message could not be sent. Please try again.'}
        format.js {}
      end
    end
  end

  private

  def contact_params
    params.require(:contact).permit(:name, :email, :message, :nickname, :captcha)
  end
end

controllers/pages_controller:

class PagesController < ApplicationController
  def home
    @contact = Contact.new
  end
end

contacts/_new.js.erb:

document.querySelector('#contact_form').innerHTML = '<%= j render 'new', locals: {contact: @contact} %>'

contacts/_new.html.erb:

<div class="row">
  <div class="mb-md-0 mb-5">
    <%= form_for @contact, id: 'contact_form', remote: true do |f| %>
      <div class="row">
        <div class="col-2"></div>
        <div class="col-md-4">
          <div class="md-form mb-0">
            <%= f.text_field :name, required: true, class: 'form-control', placeholder: "Name" %>
          </div>
        </div>

        <div class="col-md-4">
          <div class="md-form mb-0">
            <%= f.text_field :email, required: true, class: 'form-control', placeholder: "Email" %>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-2"></div>
        <div class="col-md-8">
          <div class="md-form mt-4">
            <%= f.text_area :message, rows: 8, required: true, class: 'form-control md-textarea', placeholder: "Message"%>
          </div>
        </div>
      </div>

      <div class= "hidden d-none">
        <%= f.text_field :nickname %>
      </div>

      <div class="text-center text-md-left">
        <%= f.submit 'Send Message', class: 'btn btn-outline-secondary btn-sm col-3 mt-4 mx-auto' %>
      </div>
    <% end %>
  </div>
</div>

The form works, but I would love to figure out why AJAX isn’t working for it. I have searched for many hours and have also copied code from a previous application of mine that uses AJAX for a form to no avail. I want to be able to have the same effect as redirect_to root_path without having to reload the page and auto-scroll to the anchor. I have also tried copying the create method from the contacts_controller to the pages_controller with no success either. Any tips would be greatly appreciated!

Mongoose – renaming object key within array

I have this one schema

{
  _id: "123456",
  id: "123",
  inventory: [
    {
      id: "foo",
      count: 0
    },
    {
      id: "bar",
      count: 3
    }
  ]
}

I wanted every “count” keys in the inventory array to be “price” which will look like this at the end:

{
  _id: "123456",
  id: "123",
  inventory: [
    {
      id: "foo",
      price: 0
    },
    {
      id: "bar",
      price: 3
    }
  ]
}

And I’ve tried this

Model.updateOne({ id: "123" }, { $unset: { inventory: [{ count: 1 }] } } )

But it seems to be deleting the “inventory” field itself

Unwanted element shows up because of empty properties in an object

Using react.js

The code below represents two input boxes with a submit button. Clicking on the submit button will print the information typed inside of the two input boxes.

You can also remove those messages by clicking the delete button.

The initial state already contains an invincible string message and that makes an unwanted delete button appear initially. How can I remove this initial delete button and make sure that they only appear once the first “submit” is sent.

Any help would be appreciated, thank you!

import ReactDOM from 'react-dom';

class AddMessage extends Component {
    state = { title: null, body: null, }

    handleChange = (e) => {
        this.setState({ [e.target.id]: e.target.value })
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.addMessage(this.state);
    }
    render() {
        return (<div>
            <form onSubmit={this.handleSubmit}>
                <label htmlFor="name">Title:</label>
                <input type="text" id="title" onChange={this.handleChange} />
                <label htmlFor="name">Body:</label>
                <input type="text" id="body" onChange={this.handleChange} />
                <button>Submit</button>
            </form>
        </div>)
    }
}

const Messages = (props) => {
    const { messages, deleteMessage } = props;
    const messageList = messages.map(message => {
        return (<div key={message.id}>
            <h3>{message.title}</h3>
            <h4>{message.body}</h4>
            <button onClick={() => deleteMessage(message.id)}>Delete</button>
        </div>)
    })

    return (<div>{messageList}</div>)
}

class TestTest extends Component {
    state = {
        messages: [{ title: "", body: "", id: 1 }]
    }
    addMessage = (message) => {
        message.id = Math.random();
        let messages = [...this.state.messages, message]
        this.setState({ messages: messages })
    }
    deleteMessage = (id) => {
        let messages = this.state.messages.filter(message => { return message.id !== id })
        this.setState({ messages: messages })
    }
    render() {
        return (
            <div>
                <Messages deleteMessage={this.deleteMessage} messages={this.state.messages} />
                <AddMessage addMessage={this.addMessage} />
            </div>
        )
    }
}

ReactDOM.render(<TestTest />, document.getElementById('root'));

export default TestTest```

Using regex with react hooks

I am basically trying to save the phone number entered by the user without braces, spaces or dashes but I somehow fail to do that. I am calling the regex after submitting the form in handleSubmit function through the setting of state and it prints out (and renders) without any change. Any idea what went wrong?

import React, { useContext, useState, useEffect } from "react";
import DataContext from "../store/data-context";

function Form() {
  const [name, setName] = useState("");
  const [secName, setSecName] = useState("");
  const [tel, setTel] = useState("");
  const [note, setNote] = useState("");
  const [state, setState] = useState({
    name: "",
    secName: "",
    tel: "",
    note: "",
  });
  

  const { dispatchDataState } = useContext(DataContext);

  const handleSubmit = (e) => {
    e.preventDefault();
    setTel((tel)=>tel.replace(/[^+d]+/g, ""))
    console.log(name);
    dispatchDataState({ type: "ADD_DATA", payload: state });
    setState(
      {
        name: "",
        secName: "",
        tel: "",
        note: "",
      }
    )
    console.log(state);
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          Jméno
          <input
            type="text"
            required
            value={state.name}
            onChange={(e) => setState({ ... state, name: e.target.value })}
          />
        </label>
        <label>
          Příjmení
          <input
            type="text"
            required
            value={state.secName}
            onChange={(e) => setState({ ... state, secName: e.target.value })}
          />
        </label>
        <label>
          Telefonní číslo
          <input
            type="text"
            required
            value={state.tel}
            onChange={(e) => setState({ ... state, tel: e.target.value })}
            
          />
        </label>
        <label>
          Poznámka
          <input
            type="text"
            value={state.note}
            onChange={(e) => setState({ ... state, note: e.target.value })}
          />
        </label>
        <input type="submit" value="Odeslat" />
      </form>
    </div>
  );
}

export default Form;

LuckyWheel – Show the Reward in a Div when the wheel lands on it

I am creating a little website/project for a friend. It’s a Lucky Wheel / Wheel of Fortune. I tried some premade script but none of them were like I needed and I thought that creating my own would be better.

I have made the actual Wheel in HTML / CSS. I already posted on Stack Overflow , got some help , advance the jscript part a bit but now i am missing only 1 thing. So my To Do list is as follows:

  • Have the wheel’s panel/li text (content) showed in my message box (where I have written “YOU JUST WON : XXXXXX”) once it lands on it.

FILENAME : wheel.php

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <meta http-equiv="x-ua-compatible" content="ie=edge" />
  <title>Material Design for Bootstrap</title>
  <!-- Favicon -->
  <link rel="icon" href="img/favicon.ico" type="image/x-icon" />
  <!-- Font Awesome 6 PRO -->
  <link rel="stylesheet" href="css/fontawesome/css/all.min.css" />
  <!-- Google Fonts Roboto -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" />
  <!-- MDB -->
  <link rel="stylesheet" href="css/mdb.min.css" />
  <!-- Custom styles -->
  <link rel="stylesheet" href="css/wheel.css">
  <!-- jQuery -->
  <script src="./js/jquery-3.6.0.min.js"></script>

</head>

<body class="bg-dark">

  <div class="container">
    <div class="row">
      <ul class="circle">
        <li>
          <div class="text">1</div>
        </li>
        <li>
          <div class="text">2</div>
        </li>
        <li>
          <div class="text">3</div>
        </li>
        <li>
          <div class="text">4</div>
        </li>
        <li>
          <div class="text">5</div>
        </li>
        <li>
          <div class="text">6</div>
        </li>
        <li>
          <div class="text">7</div>
        </li>
        <li>
          <div class="text">8</div>
        </li>
        <li>
          <div class="text">9</div>
        </li>
        <li>
          <div class="text">10</div>
        </li>
        <li>
          <div class="text">11</div>
        </li>
        <li>
          <div class="text">12</div>
        </li>
      </ul>
    </div>
    <div class="row justify-content-center mt-n4">
      <span class="spin_arrow"></span>
    </div>

    <!-- ### START ### MESSAGE BOX FOR REWARD : WILL SHOW ONLY WHEN A REWARD IS WON. -->
    <div class="message">
      <div class="row justify-content-center mt-4">
        <div class="col-md-8 bg-success text-white p-4 text-center">
          <h4>YOU JUST WON : XXXXXX</h4>
        </div>
      </div>
    </div>
    <!-- ### END ### MESSAGE BOX FOR REWARD : WILL SHOW ONLY WHEN A REWARD IS WON. -->

    <!-- ### START ### FORM FOR NUMBER OF SPINS + SUBMIT/SPIN BUTTON -->
    <div class="row justify-content-center mt-4">
      <div class="col-md-8 justify-content-center">
        <form action="#" method="POST" class="bg-light p-5">
          <div class="row justify-content-center">
            <div class="col-md-4 mb-4">
              <select class="select w-25" name="frm1_nbspin">
                <option value="1">1 Spin</option>
                <option value="2">2 Spins</option>
                <option value="3">3 Spins</option>
              </select>
              <label class="form-label select-label">Choose your Number of Spins</label>
            </div>
          </div>
          <div class="row justify-content-center">
            <div class="col-md-4 justify-content-center">
              <button type="submit" name="frm1_submit" id="frm1_submit" class="btn btn-block btn-primary">SPIN THE WHEEL</button>
            </div>
          </div>
        </form>
      </div>
    </div>
    <!-- ### END ### FORM FOR NUMBER OF SPINS + SUBMIT/SPIN BUTTON -->

  </div>

</body>

<!-- MDB -->
<script type="text/javascript" src="./js/mdb.min.js"></script>
<!-- WHEEL SPIN -->
<script type="text/javascript" src="./js/spinwheel.js"></script>

</html>

FILENAME : wheel.css

body {
  background: #2f2f2f;
}

.circle {
  position: relative;
  border: 1px solid black;
  padding: 0;
  margin: 1em auto;
  width: 25em;
  height: 25em;
  border-radius: 50%;
  list-style: none;
  overflow: hidden;
}

li {
  overflow: hidden;
  position: absolute;
  top: 0;
  right: 0;
  width: 50%;
  height: 50%;
  transform-origin: 0% 100%;
}

.text {
  position: absolute;
  left: -100%;
  width: 200%;
  height: 200%;
  text-align: center;
  -webkit-transform: skewY(60deg) rotate(15deg);
  -ms-transform: skewY(60deg) rotate(15deg);
  transform: skewY(60deg) rotate(15deg);
  padding-top: 20px;
  color: white;
  text-shadow: 1px 0 0 #000, 0 -1px 0 #000, 0 1px 0 #000, -1px 0 0 #000;
  font-size: 2em;
}

li:first-child {
  -webkit-transform: rotate(0deg) skewY(-60deg);
  -ms-transform: rotate(0deg) skewY(-60deg);
  transform: rotate(0deg) skewY(-60deg);
}

li:nth-child(2) {
  -webkit-transform: rotate(30deg) skewY(-60deg);
  -ms-transform: rotate(30deg) skewY(-60deg);
  transform: rotate(30deg) skewY(-60deg);
}

li:nth-child(3) {
  -webkit-transform: rotate(60deg) skewY(-60deg);
  -ms-transform: rotate(60deg) skewY(-60deg);
  transform: rotate(60deg) skewY(-60deg);
}

li:nth-child(4) {
  -webkit-transform: rotate(90deg) skewY(-60deg);
  -ms-transform: rotate(90deg) skewY(-60deg);
  transform: rotate(90deg) skewY(-60deg);
}

li:nth-child(5) {
  -webkit-transform: rotate(120deg) skewY(-60deg);
  -ms-transform: rotate(120deg) skewY(-60deg);
  transform: rotate(120deg) skewY(-60deg);
}

li:nth-child(6) {
  -webkit-transform: rotate(150deg) skewY(-60deg);
  -ms-transform: rotate(150deg) skewY(-60deg);
  transform: rotate(150deg) skewY(-60deg);
}

li:nth-child(7) {
  -webkit-transform: rotate(180deg) skewY(-60deg);
  -ms-transform: rotate(180deg) skewY(-60deg);
  transform: rotate(180deg) skewY(-60deg);
}

li:nth-child(8) {
  -webkit-transform: rotate(210deg) skewY(-60deg);
  -ms-transform: rotate(210deg) skewY(-60deg);
  transform: rotate(210deg) skewY(-60deg);
}

li:nth-child(9) {
  -webkit-transform: rotate(240deg) skewY(-60deg);
  -ms-transform: rotate(240deg) skewY(-60deg);
  transform: rotate(240deg) skewY(-60deg);
}

li:nth-child(10) {
  -webkit-transform: rotate(270deg) skewY(-60deg);
  -ms-transform: rotate(270deg) skewY(-60deg);
  transform: rotate(270deg) skewY(-60deg);
}

li:nth-child(11) {
  -webkit-transform: rotate(300deg) skewY(-60deg);
  -ms-transform: rotate(300deg) skewY(-60deg);
  transform: rotate(300deg) skewY(-60deg);
}

li:nth-child(12) {
  -webkit-transform: rotate(330deg) skewY(-60deg);
  -ms-transform: rotate(330deg) skewY(-60deg);
  transform: rotate(330deg) skewY(-60deg);
}

li:first-child .text {
  background: #FF3C38;
}

li:nth-child(2) .text {
  background: #ECC30B;
}

li:nth-child(3) .text {
  background: #E980FC;
}

li:nth-child(4) .text {
  background: #B96AC9;
}

li:nth-child(5) .text {
  background: #371E30;
}

li:nth-child(6) .text {
  background: #902D41;
}

li:nth-child(7) .text {
  background: #E57A44;
}

li:nth-child(8) .text {
  background: #8F5C38;
}

li:nth-child(9) .text {
  background: #7209B7;
}

li:nth-child(10) .text {
  background: #3A0CA3;
}

li:nth-child(11) .text {
  background: darkred;
}

li:nth-child(12) .text {
  background: gold;
}

.spin_arrow {
  color: #fff;
  font-size: 48px;
  text-align:center;
}

.spin_arrow::before {
  content: "2191";
}

FILENAME : spinwheel.js

$(function() {
  // Spin Counter, init as 0
  var spinCount = 0;
  var slices = [{
    label: "1",
    start: 0,
    end: 29
  }, {
    label: "2",
    start: 30,
    end: 59
  }, {
    label: "3",
    start: 60,
    end: 89
  }, {
    label: "4",
    start: 90,
    end: 119
  }, {
    label: "5",
    start: 120,
    end: 149
  }, {
    label: "6",
    start: 150,
    end: 179
  }, {
    label: "7",
    start: 180,
    end: 209
  }, {
    label: "8",
    start: 210,
    end: 239
  }, {
    label: "9",
    start: 240,
    end: 269
  }, {
    label: "10",
    start: 270,
    end: 299
  }, {
    label: "11",
    start: 300,
    end: 329
  }, {
    label: "12",
    start: 330,
    end: 359
  }]

  function spin(el) {
    var i = 0;
    // Select random Degree between 0 and 360
    var d = Math.floor(Math.random() * 360);
    // Reset Transform if already rotated
    if ($(el).css("transform") != "none") {
      console.log($(el).css("transform"), "Resetting to 0");
      $(el).css("transform", "rotate(0deg)");
    }
    console.log("Spin 720 + " + d + " degrees");
    // Animate Rotation of Element
    // Two full spins and then land on Random Degree
    $(el).animate({
      deg: 720 + d
    }, {
      duration: 3600,
      step: function(now, tween) {
        $(this).css({
          transform: 'rotate(' + now + 'deg)'
        });
      }
    }, function() {
      console.log("Complete Spin.", $(el).css("transform"));
    });
    // Calculate Slice Index (1 - 12)
    $.each(slices, function(k, o) {
      if (d >= o.start && d <= o.end) {
        i = k;
      }
    })
    console.log("Deg: " + d, "Index: " + i);
    return i;
  }

  function spinWheel() {
    //MAXIMUM SPINS CODE
    if (spinCount >= $("select[name='frm1_nbspin']").val()) {
      alert("No more Spins left");
      $("#frm1_submit").attr("disabled", true);
      return false;
    }
    spinCount++;
    //CODE FOR SPINNING THE WHEEL HERE...
    console.log("Spin #" + spinCount);
    console.log(spin(".circle"));
  }

  $("form").submit(function(event) {
    event.preventDefault();
    spinWheel();
  });
});

JSON type object only has parse and stringify methods, but I want to access the objects data

I have a project with NestJS, Typescript and Typeorm. I’m working with the following class Entity

class Event {
user: string,
createdAt: Date,
type: string,
data: JSON
}

In one of my methods I’m making a query to get some events, but I want to access just a few properties of the data attribute because the object has a lot information I don’t really need. The problem is that when I try to access the json, for example: receivedEvent.data.myProperty typescript tells me that this property is not available in type JSON. The only solution I can think of is changing the type of the data attribute to a string and parse it to json after the query, but I want to know if there is any other solution to this. This is the code I’m using to query the events:

async getLogs(loanId: string): Promise<Event[]> {
    const events = await this.eventRepository.find({
      select: ['createdAt', 'user', 'type', 'data'],
      where: {
        type: In([
          'early_payoff',
        ]),
        data: Raw(
          /* istanbul ignore next */
          () => 'data->"$.GUID" = :id',
          { id: loanId },
        ),
      },
      order: {
        id: 'DESC',
      },
    });

    console.log(events);

    
    return events.map(e=>{
      /// This is where my problem is
      const json: any = {"withdrawReason": e.data.withdrawReason}
      return {...e, data: json}
    });
  }

Anagram Javascript

Question with below code.
If I’m decreasing the object value and when it comes to zero how it is satisfying this condition if(!obj1[letter]) because letter still exist in obj, its value is just going down.

function validAnagram(a, b){
if(a.length !== b.length){
    return false;
}
if(a.length === 0 && b.length === 0 ){
    return true;
}
    let obj1 = {};

  // add whatever parameters you deem necessary - good luck!
    for(let i= 0; i<a.length; i++){
        if(obj1[a[i]]>0){
            obj1[a[i]]++
        }else{
                   obj1[a[i]] = 1;
        }
 

        
    }
    for(let i =0; i<b.length; i++){
        let letter = b[i];
        if(!obj1[letter]){
            return false
        } else {
            obj1[letter]--
        }
    }
    return true;
}



validAnagram('aza', 'zaz')

jquery document with not selector

I have some search fields on a page. Upon pressing ‘enter’ anything in these fields will then get filtered on for a dataset that’s displayed on a table.

$("document").on('keyup', (e) => {
    if (e.keyCode === 13) {
        searchAndDraw();
    }
});

My issue is that I have a table #myTable with some textareas in tds . Hitting ‘enter’ inside a textarea also triggers the search as the table is inside the document.

How can I apply this keyup event to the doc but exclude #myTable?

I tried $("document:not(#tliId)").on('keyup'... but that does not work.

Discord bot to kick users based on role

Good Afternoon,

first off I apologize for my lack of knowledge when it comes to Java Script. I am trying to fill a need for one of our servers without exactly knowing how 😀 The end goal is to kick a user once they received a specific role called “Inactive”.

Figure i’d start with creating a bot that kicks a user if you ‘kick @username’. These are the files I have:

Config.json:

{
"token": "(mytoken, which i'm obviously not posting :D)"
}

Index.js:

// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.once('ready', () => {
    console.log('Ready!');
});

client.on('message', message => {

    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'kick'){
        client.commands.get('kick').execute(message, args);
        }

});

client.login(token);

package.json:

{
  "name": "kickbyrole",
  "version": "1.0.0",
  "description": "Bot to kick based on discord role",
  "main": "index.js",
  "author": "Tri",
  "dependencies": {
    "@discordjs/builders": "^0.12.0",
    "@discordjs/rest": "^0.3.0",
    "discord-api-types": "^0.28.0",
    "discord-prefix": "^3.0.0",
    "discord.io": "^2.5.3",
    "discord.js": "^13.6.0",
    "winston": "^3.6.0"
  },
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "license": "ISC"
}

kick.js:

module.exports = {
    name: 'kick',
    description: "This command kicks a member!",
    execute(message, args){
        const target = message.mentions.users.first();
        if(target){
            const memberTarget = message.guild.members.cache.get(target.id);
            memberTarget.kick();
            message.channel.send("User has been kicked");
        }else{
            message.channel.send("You couldn't kick that member");
        }
    }
}

I can “node .” to initiate it without error. My bot shows online.. but nothing happens when I try to !kick @username.

Two asks.. a) what am I missing for my bot to work and b) what do I need to change for it to kick based off user role? So like ‘kick @role’

Appreciate all your time and help!

Cheers

Tri

Validations using if else and hasClass statements in Cypress

I am trying to validate the set of titles for a component. Below is my Cypress code snippet:

it('Validate the titles of all the tiles', () => {
    cy.get('.bms-scoreboard__game-tile')
      .each(($el) => {
        if($el.hasClass('bms-scoreboard__game-tile--cancelled')) {
            $el.get('.bms-scoreboard__game-tile-status--cancelled')
               .invoke('text')
               .then((text) => {
                  expect(text).equals('Cancelled')
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--pre-game')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                    const gameTime = text.split(" ").pop()
                    expect(['AM', 'PM']).to.include(gameTime)
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--final')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                   const finalTitle = text.trim()
                   expect(finalTitle).to.be.oneOf(['Final','Final (OT)'])
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--ongoing')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                   const ongoingTitle = text.trim()
                   expect(ongoingTitle).equals('Ongoing')
               })
        }
    })
})

But I get an error message: ‘Cannot read properties of undefined (reading ‘invoke’)’.

It works fine if I try it with only if block.

How can you efficiently update the fill of GeoJson polygons in MapboxGL?

I’m building an application that will render a map with a large GeoJSON set (around 3MB). The map is a choropleth, and the different GeoJSON polygons are meant to be colored differently depending on the data that they “contain.”

The problem I’m running into is that I’m unsure how to separate the GeoJSON (e.g. polygon data) from the actual data. Let’s say we set the data like this (or as Mapbox recommends, just via the URL to a data source):

const { data } = await axios.post(sourceUrl, settings);
map.current.addSource("states", {
  type: "geojson",
  data,
}

The underlying data in this map will need to update frequently with user interaction. However, right now the GeoJSON contains both the data for the polygons (coordinates) and the properties (the data itself).

For instance, the user might click a checkbox, or type in a search parameter. This currently makes a GET to our DB, which runs a query and returns the new data. We could return a new GeoJSON object with this data added inside of it and call a .getSource("source").setData(newData) will all of the new GeoJSON, but that would be terribly inefficient. The polygons aren’t changing, only the data they contain is.

I’ve looked into data-driven styling, but that doesn’t appear to be what I need either. Our underlying data set for the map is far too large to be crammed into a single GeoJSON layer, we can’t transfer hundreds of MBs over the network in order to apply data-driven styles on the client.

How can we render GeoJSON polygons to the map just once, and then update their fill colors depending on how a different data set is changed?