Destructuring Class methods loses (this) context [duplicate]

i’m wondering if it’s possible to destructure the properties/methods from an instance of a class or function while maintaining scope across the destructured variables without having to use call() every time i need that method? For example:

class Pearson {}

Pearson.prototype.speak = function speak(){
  return this.sayHi
};

Pearson.prototype.speakOutLoud = function speakOutLoud(){
  return this.speak().toUpperCase()
};

const pearson = Object.assign(new Pearson(), {sayHi:"hi!!"});

const {speak, speakOutLoud} = pearson;

speak.call(pearson) // hi!!
speakOutLoud.call(pearson) // HI!!

I want to avoid the call() because i have a bunch of methods, and i want to know if exist any cleaver solution to this.

Some questions about css (animation)

so here is the code https://codepen.io/Dobrodeetel/pen/ZEaqVap.

This code partially repeats what I have on the site. therefore questions about why it is so – unnecessary.
It works like this – click on any line – an additional line appears with a table inside (you can remove it if you click again on the same line) in which there is a line when you click on which another internal table will appear (which is also removed when you click again).

Have a few questions:

1 – if you look at the third table, you can see the row overlap (css hover).
the question itself is how to do the same only for the first table (it is possible for the second one as well)?
i.e. write something like

.table_blur tbody:hover tr:hover td {
  background: #8981ce85;
  text-shadow: none;
}

as commented out in table_blur on line 32, the line with the second table will overlap. I need to make sure that such rows (with tables inside) are NOT repainted.
I was offered an option that is also at the end of table_blur (line 37) but it does not work

2 – there is this code https://codepen.io/Dobrodeetel/pen/ExXEemr.
It’s about opening animation. how to apply such animation to my tables?
also found this code http://jsfiddle.net/1rnc9bbm/4/. which works without js at all? Well, of course I need when pressed.

So – how to attach a similar animation to the May version? that is, opening and closing until the disappearance?
I really don’t care how it works. just because my table is built right away – the code with the active class does not work.

Also how to make animation relative to width? as you can see, the third table greatly stretches the ENTIRE table (on my site it’s the same and can’t be changed in any way, since the number of columns is different). how to make a stretch animation?

That’s all. the answer to any question will greatly reduce my work)

Tabulator removeFilter doe not remove the filter No matching filter type found, ignoring: like

I am trying to remove the filter which I thought will be the easiest part of the whole tabulator but it seems to be like am missing some core things here. Below is my code which is pretty straightforward.

btn.onclick = function () {
var FilterToRemove = $(btn).closest('p').text();        // Finds the closest P tag
console.log(FilterToRemove);
var filters = table.getFilters();
filters = filters.flat();
for (let j=0; j<filters.length;j++){
  AlreadyAppliedFilter=filters[j]['value'];
  console.log(filters[j]);
  console.log(typeof(filters[j]['type']));

  if(AlreadyAppliedFilter==FilterToRemove){
    table.removeFilter("filename",filters[j].type,filters[j]['value']);
    console.log(FilterToRemove);
    console.log("Removed");
  }
};

};

but am always getting this error

Filter Error – No matching filter type found, ignoring: like

The problem is whenever I get the type of my filter from getFilters the type of “type” is a string but tabulator expects it to be an object.

any help would be highly appreciated. Thanks 🙂

in Next Js why is index.js file is rendering 2 times giving a div twice on the website

I was trying to build a simple e-commerce website with nextjs + redux + tailwind

the problem is
In this the last 2 p tag are repeated

i think the problem is with ssr in nextjs
indexjs is rendered one time on server side and on client side too
i don’t know if getInitialProps would solve this issue.
i tried using class components in _app.js and adding getInitialProps into it
didn’t work doe.

my /index.js is like

import React from "react";
import { NavbarContainer } from "../components/Navbar/Navbar.container";
import {
  Box,
} from "@chakra-ui/react";
const Home = () => {
  return (
    <>
      <Box className="">
        <NavbarContainer/>
        <Box spacing={3} className="btmList"> iainicback</Box>
        <Box spacing={3} className="btmList"> iainicback</Box>
      </Box>
    </>
  );
};

export default Home;

my _app.js is like

import App from "next/app";
import { Provider } from "react-redux";
import { store } from "../redux";
import React from "react";
import "../styles/globals.css";
import { extendTheme } from "@chakra-ui/react";
import { Chakra } from "../styles/Chakra";

// 2. Extend the theme to include custom colors, fonts, etc
const colors = {
  brand: {
    900: "#1a365d",
    800: "#153e75",
    700: "#2a69ac",
    200: "#384d",
  },
};

const theme = extendTheme({ colors });

const MyApp = (props) => {

    const { Component, appProps } = props
    return (
      <Provider store={store}>
        <Chakra theme={theme} cookies={appProps?.cookies}>
          <Component {...appProps} />
        </Chakra>
      </Provider>
    );
  
}

export default MyApp

this is my folder structure

Simple & Native react-d3-library Bar chart example

I had been investigating throug videos/content and I couldn’t find a complete example about How-To build a simple Bar chart with “react-d3-library”, all I could find was about getting D3 code and convert it to React. Even those guides were unhelpful.

Thanks in advance…

This is a very simple component implementation of react-d3-library to display a Bar chart but something is missing and I don’t know what it is. It doesn’t crash but simply doesn’t show anything.

What is missing? (The code does not follow good practices with the purpose to be simple and basic pursuit an educational goal)

import React, { useEffect, useState } from 'react'
import axios from 'axios'
import rd3 from 'react-d3-library'
import './App.css';

const BarChart = rd3.BarChart;

function App() {
  const [state, setState] = useState({d3: ''})
  
  useEffect(() => {

    (async () => {
      let data = {}
      data.width = 500;
      data.height = 750;
      data.margins = {top: 20, right: 10, bottom: 0, left: 10}
      data.yAxisLabel = 'Y VALUE';
      data.ticks = 10;
      data.barClass = 'barChart';
      data.dataset = []
      const response = await axios(`https://apidatos.ree.es/es/datos/demanda/evolucion?start_date=2022-01-01T00:00&end_date=2022-03-06T23:59&time_trunc=day`)
      const values = response.data.included[0].attributes.values
      values.forEach(item => (data.dataset.push({label: item.datetime.split("T")[0],value:item.value})))
      console.log("values",values)
      console.log("data.dataset",data.dataset)
      setState({d3:data})
    })()
  
  },[])

  return (
    <div className="App">
      <header className="App-header">
        {
          Object.keys(state.d3).length
            ? <BarChart data={state} />
            : "null"
        }
      </header>
    </div>
  );
}

export default App;

How to delete duplicate copies on mapping element counter?

I am trying to create a little project where I can count the number of elements in an array. This part I have already done. My question is how can I fix a counting problem? I’m using a mapping method to get my element occurrence counter, but I want to put the data into an array. The only way I know how is to take the data from the mapping with .get. They way I’m doing it is by using this first part here:

let winners = [1, 2, 3, 2];
let nullArray = [];
let mode = new Map([...new Set(winners)].map(
    k => [k, winners.filter(t => t === k).length]
));
for (let n in winners) {
    nullArray.push(mode.get(winners[n]));
    console.log(nullArray);
}

However, this will *n push matches. Like, if you have l=[1,2,2], because l[1]=2, and l[2]=2, they will be pushed into the nullArray as 2, however, it will also push l[2] and l[1] as the values are different. If you have three matches, it would duplicate 3 times, and so on. To counter this, I tried making a detector that would calculate when the same numbers in the nullArray are from the same copy but in a different order. To do this, I used the code I have below (combined with the original code)

let winners = [1, 2, 3, 2];
let nullArray = [];
let mode = new Map([...new Set(winners)].map(
    k => [k, winners.filter(t => t === k).length]
));
for (let n in winners) {
    nullArray.push(mode.get(winners[n]));
    console.log(nullArray);
}
for (let num in nullArray) {
    for (let c in nullArray) {
        if (nullArray[num] === nullArray[c] && winners[num] === winners[c]) {
            nullArray.splice(num, 1);
        }
        console.log(nullArray);
    }
}

However, whenever I try this, the specific output on this array is [2,2]. How could I make a general solution that will eliminate all duplicate copies, only leaving a single copy of the number count (which in the case of [1,2,3,2], I would want nullArray=[1,2,1] as an output)

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```