How to connect Firebase to a Node.JS project?

Initially developed an application without NodeJS. But then I connected Node.JS, because I need to take all the collections in the database using listCollections(). Before connecting Node Firebase, I initialized in the Firebase.js file. Now I have added Node.JS and made the firebase-admin connection as shown in the example. But when starting the server, the error is FirebaseAppError: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services. How t

// server.js

const express = require("express");
const admin = require("firebase-admin");
const db = admin.firestore();
const app = express();
const PORT = 3000;

app.use(express.static("public"));

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));

db.listCollections()
  .then((snapshot) => {
    snapshot.forEach((snaps) => {
      console.log(snaps["_queryOptions"].collectionId); // LIST OF ALL COLLECTIONS
    });
  })
  .catch((error) => console.error(error));

// firebase.js

const firebaseConfig = {
  apiKey: "...",
  authDomain: "..",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "...",
  appId: "...",
  measurementId: "...",
};

firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();

o properly connect Firebase?

Bit.io randomly terminating connecting with node.js

Bit.io randomly terminates connecting with node.js.
When I try to run the following code my node.js works fine for a few minutes but then randomly crashes and gives the error listed at the bottom of this page. I have tried to fix this but I am stuck. Don’t know if it’s a problem with bit.io or with me. Thanks!!

Code:

const { Client } = require('pg');

const client = new Client({
    user: 'procces.env.USER',
    host: 'db.bit.io',
    database: 'procces.env.DATABASE',
    password: 'procces.env.PASSWORD',
    port: 5432,
    ssl: true,
});
client.connect();

client.query('SELECT * FROM "HPI_AT_state" limit 10;', (err, res) => {
    console.table(res.rows);
})

Error:

node:events:491
      throw er; // Unhandled 'error' event
      ^

Error: Connection terminated unexpectedly
    at Connection.<anonymous> (node_modules/pg/lib/client.js:132:73)
    at Object.onceWrapper (node:events:627:28)
    at Connection.emit (node:events:513:28)
    at TLSSocket.<anonymous> (node_modules/pg/lib/connection.js:107:12)
    at TLSSocket.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1359:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on Client instance at:
    at Client._handleErrorEvent (node_modules/pg/lib/client.js:319:10)
    at Connection.<anonymous> (node_modules/pg/lib/client.js:149:16)
    at Object.onceWrapper (node:events:627:28)
    [... lines matching original stack trace ...]
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

My code expected value shows different than npm expected value

I tried writing the code in separate file in VS code. At my other file, when I tried to call the function findTheOldest(people) in the browser, it displayed the name Ray. This is expected value of the npm test. So I copied all the previous code to my real test code file. As I ran the npm test on this file, the expected value shown is Carly ? What ?? Why is the value displayed different now ? As far as I concern, everything in the code is the same but now it shows different expected value ? Is this right ?

const people = [
  {
    name: "Carly",
    yearOfBirth: 1942,
    yearOfDeath: 1970,
  },
  {
    name: "Ray",
    yearOfBirth: 1962,
    yearOfDeath: 2011,
  },
  {
    name: "Jane",
    yearOfBirth: 1912,
    yearOfDeath: 1941,
  },
]

let oldestPeople = people.sort(function(a,b) {
  const aFirstPerson = a.yearOfDeath - a.yearOfBirth;
  const bSecondPerson = b.yearOfDeath - b.yearOfBirth;

  if (aFirstPerson > bSecondPerson) {
    return -1;
  } else {
    return 1;
  }
})

const findTheOldest = function(people) {
  return people[0];
}

findTheOldest(people);

// Do not edit below this line
module.exports = findTheOldest;

———Below is the NPM test code ———-

const findTheOldest = require('./findTheOldest')

describe('findTheOldest', () => {
  test('finds the oldest person!', () => {
    const people = [
      {
        name: "Carly",
        yearOfBirth: 1942,
        yearOfDeath: 1970,
      },
      {
        name: "Ray",
        yearOfBirth: 1962,
        yearOfDeath: 2011,
      },
      {
        name: "Jane",
        yearOfBirth: 1912,
        yearOfDeath: 1941,
      },
    ]
    expect(findTheOldest(people).name).toBe('Ray');
  });

Passing data between child components in React

My goal is to use an onClick function in one of my components, and pass that data to another component (end goal is that in the other component called Playlist, it updates an array with the id of the clicked item).

I am just not sure how to pass the information between child components

My main component (app.jsx) looks like this

  const mainCards = Data.map(card => {
    return(
      <MainCard 
          key={card.id}
          id={card.id}
          image={card.url}
          title={card.title}
          playbutton={card.playbutton}
          addbutton={card.addbutton}
      />
    )
  })
  const sideCards = SideData.map(card => {
    return(
      <SideCard 
        image={card.sideurl}
        key={card.id}
        title={card.sidetitle}
        playbutton={card.playbutton}
        addbutton={card.addbutton}
      />
    )
  })
  return (
    <div className="App">
      <Navbar />
      <Header />
      <Playlist />
      <CardContainer />
      <div className="maincards">
          {mainCards}
      </div> 
      <div className="sidecards">
        {sideCards}
      </div>
    </div>
  )
}

export default App

The component where I am using onClick (MainCard.jsx)


    const handleAdd = (id) => {
        console.log(id)
    }
    return(
        <div className="mainCardObject">
            <div className="cardObj">
                <img src={props.image} className ="mainCardImage"/>
                <img src={props.playbutton} className="playbutton"/>
                <img src={props.addbutton} onClick={() => handleAdd(props.id)} className="addbutton" />
            </div>
        </div>
    )
}

export default MainCard

and the component I wish to pass information to (nothing inside, as I dont know where to start)

    return(
        <div className="playlistContainer">
            <ul>
                <li></li>
            </ul>
        </div>
    )   
}
export default Playlist```

Recreate Number.toString(nn) in pure javascript

I’m trying convert a number into string using nn base. Basically, trying re-create Number.toString(nn)

Here is the code I have so far which produces incorrect result:

const baseData = "0123456789abcdef";
for(let i = 0; i < 257; i += 8)
{
  console.log(i, "expected:", i.toString(16), "| actual:", toBase(i, 16));
}

function toBase(n, radix)
{
  let result = "";
  const count = ~~(n / radix);
  for(let i = 0; i < count; i++)
  {
    result += baseData[~~(i % radix)];
  }
  result += baseData[~~(n % radix)];
  return result;
}
.as-console-wrapper{top:0;max-height:unset!important;overflow:auto!important;}

There must be some kind of formula for this…

Any suggestions?

How can I pass url parameter for a linkedin share url?

I want to do something like this :
<a href='https://www.linkedin.com/sharing/share-offsite/?url=https://www.xyz_website.com?id=123'> Share on LinkedIn </a>

But the link that is created in linkedin post is creating link to https://www.xyz_website.com?id= and omitting 123.

Is there a way have the parameter in link correctly ?

bootstrap Carousel buttons don’t work and indicators don’t show

I am basically trying to recreate a bootstrap carousel with indicators but in my code I cannot see the indicators and the previous/next buttons don’t work. I have found an alternate solution that I could adapt here but I would like to understand where mine goes wrong, as it’s pretty much copy-pasted from Bootstrap’s site. HTML and CSS Below:

/* Define our custom colors */
:root{
  --livingcoral: #FC766AFF;
  --stormgray: #B0B8B4FF;
  --forestbiome: #184A45FF;
  --sagegreen: #567572FF;
  --marsala: #964F4CFF;
  --granitegray: #696667FF;
  --blacksteel: #080706;
  --paper: #EFEFEF;
  --goldleaf: #D1B280;
  --silver: #594D46;
}

/* Boilerplate CSS for box sizing and body */
* {
  box-sizing: border-box;
}

body{
  background-color: var(--paper);
  font-family: Georgia, Times, Courier;
  color: var(--blacksteel);
}

/* Top Bar including opacity transition */
#welcome {
  color: var(--paper);
  text-align: center;
  background-color: var(--blacksteel);
  font-family: Courier, Times, Georgia;
  transition: opacity 0.5s;
  cursor: default;
  /* background-image: url("BlueBuilding.jpg") */
}

#welcome:hover{
  opacity: 0.7;
}

/* Top left personal quote, including transition when hovering */
#top-left-motivation{
  text-align: left;
  color: var(--silver);
  overflow: hidden;
  cursor: default;
}

.quote, .text {
  display: block;
  overflow: hidden;
  transition: opacity 0.8s ease-in-out;
}

.quote{
  height: auto;
  width: auto;
  opacity: 1;
}

.text{
  height: 0;
  width: 0;
  opacity: 0;
}

#top-left-motivation:hover .quote{
  height: 0;
  width: 0;
  opacity: 0;
}
#top-left-motivation:hover .text{
  height: auto;
  width: auto;
  opacity: 1;
  font-style: italic;
}


/* Top right list including link hover effects */
#top-right-list{
  text-align: right;
  font-family: Georgia;
}

.list-inline-item{
  text-align: right;
  margin-left: 15px;
}

.info-link{
  color: var(--silver);
  transition: color 0.3s, border 0.3s, padding 0.3s;
}

.info-link:link { text-decoration: none; }

.info-link:visited { text-decoration: none; }

.info-link:hover {
  color: var(--goldleaf);
  text-decoration: none;
  cursor: pointer;
  border-top: 1px solid var(--goldleaf);
  border-bottom: 1px solid var(--goldleaf);
  /* background-color: lightskyblue; */
  /* border-radius: 2px; */
  padding: 4px 5px 5px 5px;
}

.info-link:active {
  text-decoration: none;
  color: brown;
}

/* personalt statement formatting */
#personal-statement{
  text-align: center;
  font-family: Georgia;
  /* color: #327c9c; */
}

#maincarousel{
  margin: 100px 100px 100px 100px;
  padding: 50px 50px 50px 50px;
  background-color: var(--silver);
  border-radius: 5px;
  color: var(--paper);
}


/* Special thanks to W3Schools for the
timeline tutorial: https://www.w3schools.com/howto/howto_css_timeline.asp */
/* Container around content */
.timeline {
  position: relative;
  max-width: 1400px;
  margin: 0 auto;
}

/* Uncomment if you want the circles on the timeline */
.timeline::before {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: var(--paper);
  border: 2px solid var(--blacksteel);
  border-radius: 50%;
  z-index: 2;
  left: calc(50% - 7px);
  top: 0;
}

.timeline::after {
    content: '';
    position: absolute;
    width: 6px;
    background-color: var(--blacksteel);
    top: 2px;
    bottom: 0px;
    left: 50%;
}

.container-timeline {
  padding: 10px 40px;
  position: relative;
  background-color: inherit;
  width: 50%;
}

/* For Javascript to hide/reveal elements on scroll */
.container-timeline {
  visibility: hidden;
  opacity: 0;
  transition: all 0.5s ease-in-out;
}

.container-timeline.show{
  transform: none;
  visibility: visible;
  opacity: 1;
}

.left-side {
  left: 0;
}

.right-side {
  left: 50%;
  text-align: right;
}

/* Add lines to the left container (pointing right) */
.left-side::before {
  content: " ";
  height: 2px;
  position: absolute;
  top: 30px;
  width: 40px;
  z-index: 1;
  right: 0px;
  background: var(--blacksteel);
}

/* Add lines to the right container (pointing left) */
.right-side::before {
  content: " ";
  height: 2px;
  position: absolute;
  top: 30px;
  width: 40px;
  z-index: 1;
  left: 0px;
  background: var(--blacksteel);
}

/* Fix the circle for containers on the right side */
.right-side::after {
  left: -9px;
}

/* The actual content */
.content-timeline {
  padding: 20px 30px;
  position: relative;
  border-radius: 6px;
  border: 1px solid var(--blacksteel);
}

.left-side .content-timeline {
  background: linear-gradient(45deg, rgba(209,178,128,1) 0%, rgba(89,77,70,1) 51%, rgba(8,7,6,1) 100%);
}

.right-side .content-timeline {
  background: linear-gradient(225deg, rgba(209,178,128,1) 0%, rgba(89,77,70,1) 51%, rgba(8,7,6,1) 100%);
}

/* format the timeline boxes */
.timeline-heading{
  color: var(--paper);
  font-family: Courier;
}
.left-side .timeline-heading{
border-image-slice: 1;
border-bottom: 1px solid;
border-image-source: linear-gradient(225deg, rgba(209,178,128,1) 0%, rgba(89,77,70,1) 51%, rgba(8,7,6,1) 100%);
}
.right-side .timeline-heading{
  border-image-slice: 1;
  border-bottom: 1px solid;
  border-image-source: linear-gradient(45deg, rgba(209,178,128,1) 0%, rgba(89,77,70,1) 51%, rgba(8,7,6,1) 100%);
}

.timeline-text{
  color: var(--paper);
  font-family: Georgia;
  text-decoration: bold;
}


/* Media queries - Responsive timeline on screens less than 600px wide */
@media screen and (max-width: 600px) {
  /* Place the timelime to the left */
    .timeline::after {
      left: 25px;
    }

    .timeline::before {
      left: 18px;
    }

  /* Full-width containers */
  .container-timeline {
    width: 100%;
    padding-left: 70px;
    padding-right: 25px;
  }

  /* Make sure that all lines are pointing leftwards */
  .container-timeline::before {
    left: 30px;
  }

  /* Make sure all circles are at the same spot */
  .left-side::after, .right-side::after {
    left: 15px;
  }

  /* Make all right containers behave like the left ones */
  .right-side {
    left: 0%;
  }
}
<!DOCTYPE html>

<html lang="en">
    <head>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <link href="styles.css" rel="stylesheet">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>work exp.</title>
    </head>
    <body class="workexp">
        <h1  id="welcome">
            Work experience.
         </h1>
         <div class="container-fluid" id="head">
             <div class="row justify-content-md-center">
                 <div class="col" id="top-left-motivation">
                     <span class="quote">Personal Quote.</span>
                     <span class="text">Transition text</span>
                 </div>
                 <div class="col" id="top-right-list">
                     <ul class="list-inline">
                         <li class="list-inline-item"><a class="info-link" href="index.html" class="">Home.</a></li>
                         <li class="list-inline-item"><a class="info-link" href="aboutme.html">About me.</a></li>
                         <li class="list-inline-item"><a class="info-link" href="contact.html">Contact.</a></li>
                     </ul>
                 </div>
             </div>
         </div>
         <div id="maincarousel" class="carousel slide" data-ride="carousel">
            <ol class="carousel-indicators">
              <li data-target="#maincarousel" data-slide-to="0" class="active"></li>
              <li data-target="#maincarousel" data-slide-to="1" class=""></li>
              <li data-target="#maincarousel" data-slide-to="2" class=""></li>
            </ol>
            <div class="carousel-inner" role="listbox">
                <div class="carousel-item active text-center p-4">
                     <p>lorem ipsum (imagine longer text)</p>
                </div>
                <div class="carousel-item text-center p-4">
                    <p>lorem ipsum v2 (imagine longer text)</p>
                </div>
                    <div class="carousel-item text-center p-4">
                    <p>lorem ipsum v2 (imagine longer text)</p>
                </div>
            </div>
            <a class="carousel-control-prev" href="#maincarousel" role="button" data-slide="prev">
              <span class="carousel-control-prev-icon" aria-hidden="true"></span>
              <span class="sr-only"></span>
            </a>
            <a class="carousel-control-next" href="#maincarousel" role="button" data-slide="next">
              <span class="carousel-control-next-icon" aria-hidden="true"></span>
              <span class="sr-only"></span>
            </a>
          </div>
    </body>
</html>

Also JSfiddle here https://jsfiddle.net/j9skLwye/2/

Any help appreciated.

debounced term design not working once I moved to a class component

I have the following issue with this codebase at https://github.com/codyc4321/dividends_ui on branch raise_term_state_to_main_component. I am trying to raise the state of ‘term’ from just the search bar up to the main search page component on the homepage. I have the following code working on branch main which is a functional component fully contained in SearchBar. On main if the user is typing into the search it will not run a search until he has stopped typing for 2 seconds:

SearchPage.js:

import React from ‘react’;

import SearchBar from ‘./SearchBar’;
import AllDividendsDisplay from ‘./dividend_results_display/AllDividendsDisplay’;
import DividendResultsDisplay from ‘./dividend_results_display/DividendResultsDisplay’;

import axios from 'axios';

const HOST = process.env.REACT_APP_HOSTNAME
const PROTOCOL = process.env.REACT_APP_PROTOCOL
const PORT = process.env.REACT_APP_PORT
const BASE_URL = PROTOCOL + '://' + HOST + ':' + PORT


class SearchPage extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      no_search_term: true,

      recent_searches: ['wba'],

      dividends_data: {
        current_price: '',
        recent_dividend_rate: '',
        current_yield: '',
        dividend_change_1_year: '',
        dividend_change_3_year: '',
        dividend_change_5_year: '',
        dividend_change_10_year: '',
        all_dividends: [],
        name: '',
        description: '',
      }
    }
  }

  updateStateData = (key, value) => {
    const data = this.state.dividends_data;
    data[key] = value;
    this.setState({data});
  }

  addSearchTerm = (term) => {
    const data = this.state.recent_searches;
    if (!data.includes(term)) {
      data.push(term)
      this.setState({data});
    }
  }

  addResponseKeys = (keys, response) => {
    keys.map((key) => {
      this.updateStateData(key, response.data[key]);
    });
  }

  clearData = () => {
    this.setState({
      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    });
  }

  runStockInfoSearch = async (term) => {
    console.log("running search")

    // clear old data
    this.clearData();

    if (term) {
      this.setState({loading: true})
      this.setState({no_search_term: false})

      this.addSearchTerm(term);

      const dividends_api_url = BASE_URL + '/dividends/' + term
      console.log("hitting url to search- ", dividends_api_url)

      axios.get(dividends_api_url, {})

        .then(response => {

          const RESPONSE_KEYS = [
            'current_price',
            'current_yield',
            'recent_dividend_rate'
          ]
          RESPONSE_KEYS.map((key) => {
            this.updateStateData(key, response.data[key]);
          });

          this.updateStateData('all_dividends', response.data['all_dividends'].reverse());

          const YEARS_CHANGE = [1, 3, 5, 10];
          YEARS_CHANGE.map((year) => {
            const key = 'dividend_change_' + year.toString() + '_year';
            this.updateStateData(key, response.data[key]);
          });

          this.addResponseKeys(['name', 'summary', 'sector'], response);

          this.setState({loading: false})
        })
        .catch(err => {
          console.log(err);
        })
    } else {
      this.setState({no_search_term: true})
    }
  }

  renderMainContent() {
    if (this.state.no_search_term === true) {
      return (
        <div className="ui active">
          <div className="ui text">Search for info about a stock</div>
        </div>
      )
    }
    if (this.state.loading === true) {
      return (
        <div className="ui active dimmer">
          <div className="ui text loader">Loading</div>
        </div>
      )
    } else {
      return (
        <DividendResultsDisplay data={this.state.dividends_data}/>
      )
    }
  }

  renderRecentSearches() {
    return this.state.recent_searches.map((term) => {
      return (
        <button style={{marginRight: '10px'}}>{term}</button>
      )
    })
  }

  render() {
      return (
        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          {this.renderRecentSearches()}
          <div className="ui segment">
            {this.renderMainContent()}
          </div>
        </div>
      )


    if (this.state.loading === true) {
      return (
        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <div className="ui segment">
            <div className="ui active dimmer">
              <div className="ui text loader">Loading</div>
            </div>
          </div>
        </div>
      )
    } else {
      return (
        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <DividendResultsDisplay
            data={this.state.dividends_data}
          />
        </div>
      )
    }
  }
}



export default SearchPage;

SearchBar.js:

import React, {useState, useEffect} from 'react';


const SearchBar = ({runSearch}) => {
  const defaultStock = 'wba';

  const [term, setTerm] = useState(defaultStock);
  const [debouncedTerm, setDebouncedTerm] = useState(defaultStock)

  const onFormSubmit = (event) => {
    event.preventDefault();
  }

  useEffect(() => {
    const timerId = setTimeout(() => {
      setDebouncedTerm(term);
    }, 800);

    return () => {
      clearTimeout(timerId);
    };

  }, [term]);

  useEffect(() => {runSearch(term)}, [debouncedTerm]);


  return (
    <div className="ui segment">
      <form onSubmit={onFormSubmit} className="ui form">
        <div className="field">
          <label>Stock search</label>
          <input
           type="text"
           value={term}
           onChange={(e) => setTerm(e.target.value)}
           />
        </div>
      </form>
    </div>
  );
}


export default SearchBar;

.env:

REACT_APP_HOSTNAME=localhost
REACT_APP_PROTOCOL=http
REACT_APP_PORT=8000

My attempt at moving the state up to the main component is not working. I didn’t want search bar to actually run the search because I now needed buttons to be able to update the term and run a new search:

SearchPage.js:

import React from 'react';

import SearchBar from './SearchBar';
import AllDividendsDisplay from './dividend_results_display/AllDividendsDisplay';
import DividendResultsDisplay from './dividend_results_display/DividendResultsDisplay';

import axios from 'axios';

const HOST = process.env.REACT_APP_HOSTNAME
const PROTOCOL = process.env.REACT_APP_PROTOCOL
const PORT = process.env.REACT_APP_PORT
const BASE_URL = PROTOCOL + '://' + HOST + ':' + PORT


class SearchPage extends React.Component {

  debounceTimerId = undefined;

  constructor(props) {
    super(props);
    this.state = {
      term: 'wba',
      debouncedTerm: 'wba',
      timerId: undefined,

      loading: false,
      no_search_term: true,

      recent_searches: ['wba'],

      dividends_data: {
        current_price: '',
        recent_dividend_rate: '',
        current_yield: '',
        dividend_change_1_year: '',
        dividend_change_3_year: '',
        dividend_change_5_year: '',
        dividend_change_10_year: '',
        all_dividends: [],
        name: '',
        description: '',
      }
    }
  }

  // clearDebounceTimer() {
  //   if (this.debounceTimerId) new Promise(function(resolve, reject) {
  //     clearTimeout(this.debounceTimerId);
  //     this.debounceTimerId = undefined;
  //   });
  // }

  clearDebounceTimer() {
    if (this.state.timerId) new Promise(function(resolve, reject) {
      clearTimeout(this.state.timerId);
      this.state.timerId = undefined;
    });
  }

  componentDidUpdate(previousProps, previousState) {
    if (this.state.term !== previousState.term) {
    // if (this.state.debouncedTerm !== previousState.debouncedTerm) {
      this.clearDebounceTimer();

      this.state.timerId = setTimeout(() => {
      // this.debounceTimerId = setTimeout(() => {
        this.setState({debouncedTerm: this.state.term})
      }, 2500)
    }

    if (this.state.debouncedTerm !== previousState.debouncedTerm) {
      this.runStockInfoSearch(this.state.term);
    }
  }

  componentWillUnmount() {
    // clearTimeout(this.state.timerId);
    clearTimeout(this.debounceTimerId);
  }

  onTermUpdate = (term) => {
    this.setState({term: term})
  }

  updateStateData = (key, value) => {
    const data = this.state.dividends_data;
    data[key] = value;
    this.setState({data});
  }

  addSearchTerm = (term) => {
    const data = this.state.recent_searches;
    if (!data.includes(term)) {
      data.push(term)
      this.setState({data});
    }
  }

  addResponseKeys = (keys, response) => {
    keys.map((key) => {
      this.updateStateData(key, response.data[key]);
    });
  }

  clearData = () => {
    this.setState({
      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    });
  }

  runStockInfoSearch = async (term) => {
    console.log("running search")

    // clear old data
    this.clearData();

    if (term) {
      this.setState({loading: true})
      this.setState({no_search_term: false})

      this.addSearchTerm(term);

      const dividends_api_url = BASE_URL + '/dividends/' + term
      console.log("hitting url to search- ", dividends_api_url)

      axios.get(dividends_api_url, {})

        .then(response => {

          const RESPONSE_KEYS = [
            'current_price',
            'current_yield',
            'recent_dividend_rate'
          ]
          RESPONSE_KEYS.map((key) => {
            this.updateStateData(key, response.data[key]);
          });

          this.updateStateData('all_dividends', response.data['all_dividends'].reverse());

          const YEARS_CHANGE = [1, 3, 5, 10];
          YEARS_CHANGE.map((year) => {
            const key = 'dividend_change_' + year.toString() + '_year';
            this.updateStateData(key, response.data[key]);
          });

          this.addResponseKeys(['name', 'summary', 'sector'], response);

          this.setState({loading: false})
        })
        .catch(err => {
          console.log(err);
        })
    } else {
      this.setState({no_search_term: true})
    }
  }

  renderMainContent() {
    if (this.state.no_search_term === true) {
      return (
        <div className="ui active">
          <div className="ui text">Search for info about a stock</div>
        </div>
      )
    }
    if (this.state.loading === true) {
      return (
        <div className="ui active dimmer">
          <div className="ui text loader">Loading</div>
        </div>
      )
    } else {
      return (
        <DividendResultsDisplay data={this.state.dividends_data}/>
      )
    }
  }

  renderRecentSearches() {
    return this.state.recent_searches.map((term) => {
      return (
        <button onClick={() => this.onTermUpdate(term)} style={{marginRight: '10px'}}>{term}</button>
      )
    })
  }

  render() {
    console.log("term in higher state: ", this.state.term);
    return (
      <div className="ui container" style={{marginTop: '10px'}}>
        <SearchBar
          runSearch={this.runStockInfoSearch}
          term={this.state.term}
          onTermUpdate={this.onTermUpdate}/>
        {this.renderRecentSearches()}
        <div className="ui segment">
          {this.renderMainContent()}
        </div>
      </div>
    )
  }
}

export default SearchPage;

SearchBar.js:

import React, {useState, useEffect} from 'react';


const SearchBar = ({runSearch, onTermUpdate, term}) => {

  const onFormSubmit = (event) => {
    event.preventDefault();
  }

  return (
    <div className="ui segment">
      <form onSubmit={onFormSubmit} className="ui form">
        <div className="field">
          <label>Stock search</label>
          <input
           type="text"
           value={term}
           onChange={(e) => onTermUpdate(e.target.value)}
           />
        </div>
      </form>
    </div>
  );
}


export default SearchBar;

In this attempt in a class component after 2 seconds of typing searches will just continuously run after each key pressed, instead of waiting 2 seconds after typing has stopped. I can probably rewrite it as a function but I would prefer to keep the higher component a class for cleanness and ease of reading the code. Thank you for any help

enter image description here

Element stuck in foreach

Basically I have an object dataToSend, if the value I am uploading is a scale ( //scales ), it will add this scale to the createValues array. However I have a condition after (under //file), basically my scale is stuck in the foreach, although it is not going into the condition. I would like the scales to leave the foreach if it does not go into the condition, therefore it has nothing to do in it. I want the scales to go straight to :

console.log('dataToSend', dataToSend);
    return dataToSend;
export const convertBeforeSync = (el, lang, projectId) => {

    const dataToSend = {
        projectId,
        gridId: el.TableId,
        createValues,
        links: {
            compositions: [],
            traceability: [],
            reverseCompositions: [],
            externalDocuments: [],
        },
    };
    //scales
    if (values?.Scales) {
        const output = values?.Scales.map((value) => {
            return {
                field: value.ScaleId,
                value: value.Id,
            };
        });
        dataToSend.createValues = [...dataToSend.createValues, ...output];
        console.log('he', dataToSend);
    }

    //File

    dataToSend.createValues.forEach(function (item) {
        
        if (item.field.startsWith('FLD_STR_') && typeof item.value === 'object') {
            const newCreateValue = {
                field: item.field,
                fileName: item.value.fileName,
                value: item.value.value,
            };
            dataToSend.createFileValue = newCreateValue;
            dataToSend.createValues = dataToSend.createValues.filter(
                (el) => typeof el.value !== 'object'
            );
        }
        
    });

    console.log('dataToSend', dataToSend);
    return dataToSend;
};


addEventListener(‘click) not triggering when button is clicked

Goal: Clicking on the button opens a link in a new page.
Issue: eventListener not triggering when button is clicked

Button element:

<button type="button" class="btn oe_stat_button o_field_widget o_readonly_modifier"></button>

Event listener:

const mainButton = document.querySelector('.btn.oe_stat_button.o_field_widget.o_readonly_modifier');
mainButton.addEventListener('click', () => window.open(linkConfig,'_blank'));

I have verified that my button is well assigned to the mainButton and found in the DOM.
I have verified that the value assigned to container is found in the DOM.

Whole code:

setTimeout(linkToSupplier, 3000);

function linkToSupplier() {

        const container = document.querySelector('[data-id^="product.supplierinfo_"]').innerText;
        const supplierContent = document.querySelector('[title="Supplier"]');
        
    function linkConfig(supplierLink) {

        supplierContent.innerText = '';
        const link = document.createElement("a")

        // Create txt
        const txt = document.createTextNode("Vist Website ")

        //append txt to anchor element
        link.appendChild(txt)

        // set the innerText
        link.title = "Visit Website ";
        link.target = 'target="_blank"';

        // set the href property
        link.href = supplierLink;

        // get text to add link to
        const mainButton = document.querySelector('.btn.oe_stat_button.o_field_widget.o_readonly_modifier');
        mainButton.outerHTML = `<button type="button" class="btn oe_stat_button o_field_widget o_readonly_modifier"></button>`;
        mainButton.addEventListener('click', () => window.open(linkConfig,'_blank'));
    }

    window.addEventListener('hashchange', () => setTimeout(linkToSupplier, 1000));

    if (container.includes('Google')) {
        linkConfig('https://google.com/');
    }
}

Boostrap hamburger menu won’t collapse on button click nor on item choosen

Everything worked(navbar collapsed on item chosen from navbar or button click), I must have changed something and now it doesn’t. Please help. Does some workaround exist like collapsing through Javascript?

<template>
 <nav v-if="auth.authenticated" class="navbar navbar-expand-lg navbar-light" :style="{backgroundColor:getColor()}">
      <div class="container-fluid">
        <button class="navbar-toggler collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown"
          aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="icon-bar top-bar"></span>
          <span class="icon-bar middle-bar"></span>
          <span class="icon-bar bottom-bar"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavDropdown" @focusin="toggleMenu" :style="{backgroundColor:getColor()}">
          <ul class="navbar-nav">
            <li class="nav-item active" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown">
              <a @click="this.$router.push('/')"  href="" class="nav-link nav-link-ltr">Order now</a>
            </li>
            <li class="nav-item" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown">
              <a @click="this.$router.push('/')" href=""  class="nav-link nav-link-ltr">My orders</a>
            </li>
             <li class="nav-item" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown">
              <a class="nav-link nav-link-ltr" href="#">Top offers</a>
            </li>
             <li class="nav-item" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown">
              <a class="nav-link nav-link-ltr" href="#">New offers</a>
            </li>
            <li class="nav-item" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown">
              <a class="nav-link  nav-link-ltr" href="#">About us</a>
            </li>
             <li class="nav-item" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown">
              <a class="nav-link nav-link-ltr" href="#">Subscribe</a>
            </li>
            <span v-if="auth.authenticated">
              <a @click="logout" class="btn btn-info my-2 my-sm-0 mr-2 p-1" href="#">Logout</a>
            </span>
          </ul>
        </div>
        <a class="navbar-brand ms-auto" href="#">
          <img id="logoNav" alt="navbar logoNav" src="@/assets/logo-main.svg" />
        </a>
      </div>
  </nav>
</template>

React + React query Pagination only re-render on window focus

I am using React-Query with react, Now I am trying to do pagination but the component only renders on window focus. It is illustrated in the following video,

Illustration

Here we can see that the component only re-renders only after the window focus on how to fix that. Below is the code for the components,

The Query Hook,


// To get all the chats Details
export const useGetChats = ({
  userId,
  jwt,
  params,
}: {
  userId: number;
  jwt: string;
  params: {
    perPage: number;
    page: number;
    sortBy: string;
  };
}) => {
  // Query Key
  const queryKey = ['users', userId, 'chats'];

  // Response
  type ResponseType = IChat[];

  // Fetcher
  const fetcher = async () => {
    const QueryUrl = `/api/v1/users/${userId}/chats?perPage=${params.perPage}` +
    `&page=${params.page}&sortBy=${params.sortBy}`
    return await axios.get<ResponseType>(QueryUrl, {
      headers: { Authorization: `Bearer ${jwt}` }
    });
  };

  // Query
  return useQuery(queryKey, fetcher, { keepPreviousData: true });
};

The Chat View (List the chats),

interface IChatViewProps extends HTMLAttributes<HTMLDivElement> {
  setSortBy   : (shortBy: "name" | "createdAt" | "updatedAt") => void;
  sortBy      : "name" | "createdAt" | "updatedAt";
  isFetching  : boolean;
  onPrev?     : () => void;
  onNext?     : () => void;
  hasPrev     : boolean;
  hasNext     : boolean;
  chats       : IChat[] | null;
  onDelete?   : (chat: IChat) => void;
  onOpen?     : (chat: IChat) => void;
  onEdit?     : (chat: IChat) => void;
}


// Chat View
export default function ChatView({
  isFetching,
  setSortBy,
  sortBy,
  hasPrev,
  hasNext,
  chats,
  onPrev,
  onNext,
  onDelete,
  onOpen,
  onEdit,
}: IChatViewProps) {
  // sort change handler
  const handleSortChange = (event: SelectChangeEvent<"name" | "createdAt" | "updatedAt">) => {
    setSortBy(event.target.value as typeof sortBy);
  }

  // if chats are loading
  if (chats === null) {
    return <CircularProgress sx={{margin: "auto"}}/>;
  }

  // select Component for the sortBy
  const SelectSort = (
    <FormControl sx={{ m: 1, minWidth: 120 }} size="small">
      <InputLabel id="sort-by-label">Sort By</InputLabel>
      <Select
        onChange={handleSortChange}
        labelId="sort-by-label"
        value={sortBy}
        label="Sort By"
        id="sort-by-select"
      >
        <MenuItem value={"createdAt" as typeof sortBy}>
          Created At
        </MenuItem>
        <MenuItem value={"name" as typeof sortBy}>
          Name
        </MenuItem>
        <MenuItem value={"updatedAt" as typeof sortBy}>
          Updated At
        </MenuItem>
      </Select>
    </FormControl>
  )

  // chats component to render
  const UserChats = chats.map((chat: IChat) => {
    return (
      <React.Fragment>
        <HorizontalBar
          onDelete={onDelete}
          onOpen={onOpen}
          chat={chat}
          onEdit={onEdit}
        />
        <ChatDivider />
      </React.Fragment>
    );
  });

  // fetching status
  const Fetching = isFetching ? (
    <CircularProgress
      sx={{margin: "8px auto 0 7px"}}
      size={"1rem"}
    />
  ) : (
    null
  );

  // render
  return (
    <ChatViewWrapper>
      <Header>
        <Title>Your Chats List</Title>
        {Fetching}
        <Sort>{SelectSort}</Sort>
      </Header>
      <Body>
        {UserChats.length === 0 ? (
          <NoChats>No Chats</NoChats>
        ) : (
          UserChats
        )}
      </Body>
      <Footer>
        <Button disabled={!hasPrev || isFetching}
          variant="outlined"
          onClick={onPrev}
        >
          Prev
        </Button>
        <Button disabled={!hasNext || isFetching}
          variant="outlined"
          onClick={onNext}
        >
          Next
        </Button>
      </Footer>
    </ChatViewWrapper>
  );
}

The Dashboard,


export default function Dashboard() {
  // sort by state
  const [sortBy, setSortBy] = useState<"name" | "createdAt" | "updatedAt">("name");

  // page number
  const [pageNumber, setPageNumber] = useState<number>(1);

  // user details
  const user: IUser | null = useSelector(selectUser);

  // jwt token
  const jwt: string | null = useSelector(selectJwt);

  // if no user throw
  if (!user || !jwt) {
    throw new Error("No User found");
  }

  // chats for the dashboard
  const {
    isPreviousData : isPrevData,
    isError,
    data,
    error,
    isFetching,
  } = useGetChats({
    userId: user.userId,
    jwt: jwt,
    params: {
      page: pageNumber,
      perPage: 5, // it is a constant
      sortBy: sortBy,
    },
  });

  // if error throw
  if (isError) {
    throw new Error("Error in getting chats: " + error);
  }

  // Header Link
  const link = data ? data.headers["link"] : undefined;

  // on prev handler
  const onPrev = () => {
    setPageNumber(Math.max(pageNumber - 1, 0));
  }

  // on next handler
  const onNext = () => {
    if (!isPrevData && link?.includes("next")) {
      setPageNumber(pageNumber + 1);
    }
  };

  // body
  const Body = () => (
    <DashboardWrapper>
      <UserView
        onDelete={() => null}
        onEdit={() => null}
        user={user}
      />
      <ChatView
        onDelete={() => null}
        onOpen={() => null}
        onEdit={() => null}
        isFetching={isFetching}
        setSortBy={setSortBy}
        sortBy={sortBy}
        onPrev={onPrev}
        onNext={onNext}
        hasPrev={pageNumber > 1}
        chats={data?.data || null}
        hasNext={!isPrevData && link?.includes("next") || false}
      />
    </DashboardWrapper>
  );

  return (
    <React.Fragment>
      <Header />
      <Body />
      <Footer />
    </React.Fragment>
  );
}

I removed Css and some stuff But the complete code is available at github Thank You

How to assign Firebase queries to an array or variable in JS and HTML

I’m trying to fetch my firebase database using a function but for some reason I cannot assign the output to a variable. Please help
I tired a for loop and pushing into an array but nothing works
I tried adding a return statement and that didn’t work

My Code

function LeaderboardScreen(){
      InsertData();
      ReadData();
}
function ReadData(){
      const readRef = ref(db, "users/");
      onValue(readRef,(snapshot) =>{
        const data = snapshot.val();
        console.log(data)
        
        
      
      })             
    }

Deploying Nodejs Express js App on heroku

I’m trying to deploy my app on heroku, but I’m always getting this error

2022-08-11T12:49:12.131468+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2022-08-11T12:49:12.131469+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
2022-08-11T12:49:12.131470+00:00 app[web.1]: errno: -111,
2022-08-11T12:49:12.131470+00:00 app[web.1]: code: 'ECONNREFUSED',
2022-08-11T12:49:12.131470+00:00 app[web.1]: syscall: 'connect',
2022-08-11T12:49:12.131471+00:00 app[web.1]: address: '127.0.0.1',
2022-08-11T12:49:12.131471+00:00 app[web.1]: port: 3306,
2022-08-11T12:49:12.131471+00:00 app[web.1]: fatal: true
2022-08-11T12:49:12.131472+00:00 app[web.1]: }
2022-08-11T12:49:12.131494+00:00 app[web.1]:
2022-08-11T12:49:12.131494+00:00 app[web.1]: Node.js v18.7.0

Could anybody help me solve this problem?
This is the server.js

const express = require('express')
const app = express()

app.set('view engine', 'ejs')

const filterByDateRouter = require('./routes/filterByDate');
const filterByLogsRouter = require('./routes/filterByLogs');
const mainPageRouter = require('./routes/index'); 

app.use("/filterByDate", filterByDateRouter)
app.use("/filterByLogs", filterByLogsRouter)
app.use("/",mainPageRouter)
app.use(express.static(__dirname + '/public/css'))
app.use(express.static(__dirname + '/public/js'))


app.listen(process.env.PORT || 3000)

this is the database connection:

var connection = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  connectionLimit:10,
  database: process.env.DB_NAME,
});

I’m using clearMYSQL from heroku to deploy my database, and all the fields saved in the .env are right