React Native and React Native Web- document is not defined error

I am trying to create a currency converter app. I am trying to create 2 dropdowns for selecting currencies. During that, I figured out that the library I am using, “react native material dropdown”, does not work on web. This is the Error that I am getting with react native material dropdown on web:
screenshot of error

So, I added react native web to my app and used the docs to add the following 2 lines of code to the react native app:

AppRegistry.registerComponent('App', () => App);
AppRegistry.runApplication('App', {rootTag: document.getElementById('react-root')});

This is my entire “App.js”:

import React from 'react';
import {
  View,
  StyleSheet,
  TextInput,
  Text,
  TouchableOpacity,
  AppRegistry
} from 'react-native';
import { Header } from 'react-native-elements';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import {Dropdown} from 'react-native-material-dropdown';

export default class App extends React.Component {
  constructor() {
    super();
  }

  render() {
    return (
      <SafeAreaProvider>
        <View style={styles.appContainer}>
          <Header
            backgroundColor={'#2CC779'}
            centerComponent={{
              text: 'Currency Converter',
              style: {
                color: '#fff',
                fontSize: 20,
              },
            }}
          />
          <Text style={{ marginTop: 20 }}>Enter currency to convert from:</Text>


          <Text style={{ marginTop: 50 }}>Enter currency to convert to:</Text>
          

          
        </View>
      </SafeAreaProvider>
    );
  }
}

const styles = StyleSheet.create({
  appContainer: {
    flex: 1,
    backgroundColor: '#18C6C9',
  },
  currencyInput: {
    marginTop: 50,
    width: '80%',
    alignSelf: 'center',
    height: 40,
    textAlign: 'center',
    borderWidth: 4,
    outline: 'none',
  },
  convertButton: {
    width: '50%',
    height: 55,
    alignSelf: 'center',
    padding: 10,
    margin: 100,
  },
  convertButtonText: {
    textAlign: 'center',
    fontSize: 30,
    fontWeight: 'bold',
  },
});

AppRegistry.registerComponent('App', () => App);
AppRegistry.runApplication('App', {rootTag: document.getElementById('react-root')});

This is my “package.json”:

{
  "dependencies": {
    "expo-constants": "~12.1.3",
    "@expo/vector-icons": "^12.0.0",
    "react-native-paper": "4.9.2",
    "react-native-elements": "*",
    "react-native-safe-area-context": "3.3.2",
    "react-native-material-dropdown": "*"
  }
}

But now, after that, expo is saying that “document is not defined”: screenshot of second error

What do I do next and how should I proceed?
(P.S. Keep in mind that this is inside an online Expo environment in the Snack editor)

Dynamic routes in react router v6

Please how do I match the coinId in this code, I’m using react router version 6, and it’s not delivering.

<Routes>
  <Route path='/crypto/:coinId element={<Crypto details />} />
</Routes>

Please I’d really appreciate your help, the code above is from version 5

How to modify the JavaScript code so that it works on the new structure of links?

  // Start Current Link (ACTIVE MENU LINK)
  jQuery(document).ready(function () {
    jQuery(".navigation > li").click(function () {
      jQuery(".navigation > li").removeClass("current");
      jQuery(this).addClass("current");
    });
    var loc = window.location.href;
    jQuery(".navigation > li").removeClass("current");
    jQuery(".navigation > li > a").each(function () {
      if (loc.indexOf(jQuery(this).attr("href")) != -1) {
        jQuery(this).closest("li").addClass("current");
      }
    });
    // The Below Code for fix current active dropdown when choose sub link from the dropdown menu
    jQuery(".navigation > .dropdown").click(function () {
      jQuery(".navigation > .dropdown").removeClass("current");
      jQuery(this).addClass("current");
    });
    var loc = window.location.href;
    jQuery(".navigation > .dropdown > ul > li").removeClass("current");
    jQuery(".navigation > .dropdown > ul > li > a").each(function () {
      if (loc.indexOf(jQuery(this).attr("href")) != -1) {
        jQuery(this).closest(".dropdown").addClass("current");
      }
    });
  });
ul {
  list-style: none;
}
a {
  text-decoration: none;
}
.main-menu .navigation {
  display: flex;
  align-items: center;
  position: relative;
}
.main-menu .navigation > li {
  padding: 39.5px 0;
  margin: 0 15px;
  z-index: 2;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
.main-menu .navigation > li.current > a {
  color: #da2c46;
}
.main-menu .navigation > li.current > a::before {
  -webkit-transform: scale(1, 1);
  -moz-transform: scale(1, 1);
  -ms-transform: scale(1, 1);
  -o-transform: scale(1, 1);
  transform: scale(1, 1);
}
.main-menu .navigation > li:first-child {
  margin-left: 0;
}
.main-menu .navigation > li:last-child {
  margin-right: 0;
}
.main-menu .navigation > li > a {
  color: #222222;
  /* color: #ffffff; */
  position: relative;
  display: flex;
  font-weight: 600;
  opacity: 1;
  z-index: 1;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
.main-menu .navigation > li > a::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 1px;
  background-color: #da2c46;
  bottom: -3px;
  left: 0;
  -webkit-transform: scale(0, 0);
  -moz-transform: scale(0, 0);
  -ms-transform: scale(0, 0);
  -o-transform: scale(0, 0);
  transform: scale(0, 0);
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
.main-menu .navigation > li > a::after {
  content: "";
  position: absolute;
}
.main-menu .navigation > li > a:hover {
  color: #da2c46;
}
.main-menu .navigation > li > a:hover::before {
  -webkit-transform: scale(1, 1);
  -moz-transform: scale(1, 1);
  -ms-transform: scale(1, 1);
  -o-transform: scale(1, 1);
  transform: scale(1, 1);
}
.main-menu .navigation > li > ul {
  position: absolute;
  left: inherit;
  top: 100%;
  width: 250px;
  z-index: 100;
  display: none;
  opacity: 0;
  visibility: hidden;
  background-color: #ffffff;
  -webkit-transform: translateY(30px);
  -moz-transform: translateY(30px);
  -ms-transform: translateY(30px);
  -o-transform: translateY(30px);
  transform: translateY(30px);
  -webkit-box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  -moz-box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  -ms-box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  -o-box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  -webkit-transform-origin: top;
  -moz-transform-origin: top;
  -ms-transform-origin: top;
  -o-transform-origin: top;
  transform-origin: top;
  -webkit-transition: all 2s ease-in-out;
  -moz-transition: all 2s ease-in-out;
  -ms-transition: all 2s ease-in-out;
  -o-transition: all 2s ease-in-out;
  transition: all 2s ease-in-out;
}
.main-menu .navigation > li > ul > li {
  position: relative;
  width: 100%;
  padding: 11px 30px;
  border-bottom: 1px solid #eeeeee;
}
.main-menu .navigation > li > ul > li > a {
  position: relative;
  display: block;
  padding: 6px 0px;
  line-height: 24px;
  text-transform: capitalize;
  color: #222222;
  text-align: left;
  transition: all 500ms ease;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
}
.main-menu .navigation > li > ul > li > a:hover {
  color: #da2c46;
}
.main-menu .navigation > li.dropdown:hover > ul {
  display: block;
  visibility: visible;
  opacity: 1;
  -webkit-transform: translateY(0);
  -moz-transform: translateY(0);
  -ms-transform: translateY(0);
  -o-transform: translateY(0);
  transform: translateY(0);
  -webkit-transition: all 2s ease-in-out;
  -moz-transition: all 2s ease-in-out;
  -ms-transition: all 2s ease-in-out;
  -o-transition: all 2s ease-in-out;
  transition: all 2s ease-in-out;
}
.main-menu .navigation > li.dropdown .dropdown-btn {
  position: absolute;
  right: -32px;
  top: 66px;
  width: 34px;
  height: 30px;
  text-align: center;
  font-size: 18px;
  line-height: 26px;
  color: #3b3b3b;
  cursor: pointer;
  display: none;
  z-index: 5;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <nav class="main-menu navbar-expand-md me-auto navbar-light">
        <div class="collapse navbar-collapse show" id="navbarSupportedContent">
            <ul class="navigation">
                <li><a href="/">Home</a></li>
                <li><a href="/about-us.html">About</a></li>
                <li class="dropdown"><a href="/services.html">Services</a>
                    <ul>
                        <li><a href="/finance-consulting.html">Finance
                                Consulting</a>
                        </li>
                        <li><a href="/tax-management.html">Tax Management</a></li>
                        <li><a href="/economic-planning.html">Economic Planning</a></li>
                        <li><a href="/strategy-thinking.html">Strategy Thinking</a></li>
                        <li><a href="/market-analysis.html">Market Analysis</a></li>
                        <li><a href="/content-optimize.html">Content Optimize</a></li>
                    </ul>
                </li>
                <li><a href="/pricing.html">pricing</a></li>
                <li class="dropdown"><a href="/blog.html">Blog</a>
                    <ul>
                        <li><a href="/blog-details.html">Blog details</a></li>
                        <li><a href="/404.html">Error 404 Page</a></li>
                        <li><a href="/privacy-policy.html">Privacy Policy</a></li>
                    </ul>
                </li>
                <li><a href="/contact.html">Contact</a></li>
            </ul>
        </div>
    </nav>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   
</body>

</html>

Hello
I got this javascript code by searching (its function is to add and remove active class to ‘li’ class for the open page) and it executed as is.
Now, I am working on an html site and the link was “localhost/index.html”
And the code was working good on this format
and because I want to remove the “index.html” link so that it shows the main without adding index.html, I switched home link from “index.html” to “/” and added “/” before each page link as shown in the html structure, and the result was that the class “current” stayed on the home link and also added to the open page, meaning when you open about us page for example you will find the css effects of the class “current” is enabled on it and on the home page link
I tried to modify the javascript code so that the job works on the new link, which is local only, without adding /index.html, but I don’t know
I hope you will help me and tell me how to write the code so that it achieves the functions required of it
With thanks

Use a Google Script to display a dynamic dropdown menu in a HTML form Google Sheet Doc

I need help with my first Google Script. I have a dropdown menu that displays a list of items from my Google Sheets doc which works perfectly.

The first menu displays a list of media types which removes any duplicates and sorts them out alphabetically. I’m now trying to add another dropdown menu that’s dynamic so when the user selects a media type, only the brands for that media type show. Once the user selects from the second menu, I want the price to appear at the bottom of the form that matches the media type and brand.

enter image description here

First dropdown menu (this is working perfect)

function getColors() { 
  const sheet = SpreadsheetApp.openById("123456").getSheetByName("Vinyl-Prices");

  const colName = 'Media Type';
  const colNum = getColorColNumByName(colName);
  if (colNum === null) {
    Logger.log('Column ' + colName + ' was not found!');
    return [];
  }

  const firstRow = 2;
  const lastRow = sheet.getLastRow();

  // get all values from column
  const columnData = sheet.getRange(firstRow, colNum, lastRow).getValues().flat();

  // filter values on duplicates
  return columnData.filter((el, i) => i === columnData.indexOf(el) && el !== '').sort()
}

function getColorColNumByName(colName, row = 1) {
  const sheet = SpreadsheetApp.openById("123456").getSheetByName("Vinyl-Prices");
  
  const [data] = sheet.getRange(row, 1, row, sheet.getLastColumn()).getValues();
  const col = data.indexOf(colName);

  // adding 1 because column nums starting from 1
  return col === -1 ? null : col + 1;
}

That works as it should.

I now have 2 scripts for the second part of the form. The first displays the list of brands but it’s not linked to the first menu meaning every brand shows whether it matches or not.

Here:

function getFruits(color) { 
  const sheet = SpreadsheetApp.openById("123456").getSheetByName("media Costs");

  const colName = 'Brand';
  const colNum = getFruitColNumByName(colName);
  if (colNum === null) {
    Logger.log('Column ' + colName + ' was not found!');
    return [];
  }

  const firstRow = 2;
  const lastRow = sheet.getLastRow();

  // get all values from column
  const columnData = sheet.getRange(firstRow, colNum, lastRow).getValues().flat();

  // filter values on duplicates
  return columnData.filter((el, i) => i === columnData.indexOf(el) && el !== '').sort()
}

The second script works as it should but it doesn’t do other stuff that I need it to do such as list the items in alphabetical order or allow me to select the column by name.

function getFruits(color) { 
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Vinyl Costs");
  var getLastRow = sheet.getLastRow();
  var return_array = [];
  for(var i = 2; i <= getLastRow; i++)
  {
      if(sheet.getRange(i, 1).getValue() === color) {
        return_array.push(sheet.getRange(i, 2).getValue());
      }
  }


  return return_array;  
}

Finally ,I need the form to display the price at the bottom based on what media and brand was selected. I have attached my html for but why can’t I figure the second form out and add the price at the end, this is simple stuff.

HTML form

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
    function GetFruit(color) 
    {
    
    google.script.run.withSuccessHandler(function(ar) 
    {

    console.log(ar);
    
    fruit.length = 0;
    
    let option = document.createElement("option");
    option.value = "";
    option.text = "";
    fruit.appendChild(option);
    
    ar.forEach(function(item, index) 
    {    
      let option = document.createElement("option");
      option.value = item;
      option.text = item;
      fruit.appendChild(option);    
    });
    
    }).getFruits(color);
    
    };
  </script>  
  </head>
  <body>
    <h1>Web App Dependent Drop Down</h1>
    <?var url = getUrl();?>
    <form method="post" action="<?= url ?>" >
      <label style="font-size: 20px" >Name</label><br>
      <input type="text" name="name" style="font-size: 20px" /><br><br>
      
      <label style="font-size: 20px" >Colors</label><br>
      <select name="color" style="font-size: 20px" onchange="GetFruit(this.value)" >
      <option value="" ></option>
      <? for(var i = 0; i < colors.length; i++) { ?>      
      <option value="<?= colors[i] ?>" ><?= colors[i] ?></option>
      <? } ?>
      </select><br><br>
      <label style="font-size: 20px" >Fruit</label><br>
      <select name="fruit" id="fruit" style="font-size: 20px" >
      </select><br><br>
      <label style="font-size: 20px" >Blank - Price will got here</label><br>
      <select name="fruit2" id="fruit2" style="font-size: 20px" >
      </select><br><br>
      <input type="submit" name="submitButton" value="Submit" style="font-size: 20px" /> 
      <span style="font-size: 20px" ><?= message ?></span>      
    </form>
  </body>
</html>

why styles don’t apply on dangerouslySetInnerHTML

i need to render some styled jsx tags in my component by using useTranslation hook and dangerouslySetInnerHTML, those tags are stored in a json file , i found that dangerouslySetInnerHTML work’s fine but don’t apply tailwind styles for each tag,

json file:

{
   "about-text":"<div className='text-blue px-5'><p>Text ...</p</div>",
}

inside componenets:

<div className="p-10">
<div
   dangerouslySetInnerHTML={{
      __html: t('about-text'),
    }}
   />
</div>

React- ContectApi

Getting empty array in useContext in section component initially due to which the section component is empty .Please help me fix this.

//this is my context component


export const Products = createContext();

export const ProductContext = (props) => {
  const [state, setState] = useState([]);
  useEffect(async () => {
    try {
      const res = await fetch("https://demo7303877.mockable.io");
      const items = await res.json();
      console.log(items);
      // console.log(items.products);
      setState(items);
    } catch (err) {
      console.log(err);
    }
  }, []);

  return (
    <Products.Provider value={[state, setState]}>
      {props.children}
    </Products.Provider>
  );
};

//getting empty array initially in state
//this is section component

import React, { useContext, useState } from "react";
import { Products } from "../Context/ProductsContext";

function Section() {
  const [state, setState] = useContext(Products);
console.log (state) //this return an empty array initially

return (
    <div>
      {state.length > 1 &&
        state.products.map((p) => {
          return <p> {p.brand}</p>;
        })}
    </div>
  );
}

export default Section;

can i use same show/hide button on 2 different sections or divs

I’m attempting to use the same ID, but it’s not working. I duplicated the script and added an extra character to make it unique, but it didn’t work. Also, when I show the hidden columns (“I am using bootstrap 5 col grid”), the images display inline, and I want them to match the grid. I altered the display value in the script, and tried many other values, but none of them work; they all display inline.Last question, if you look at my code, I’m using a down arrow png just to make it look nice, but when you click it, the show less button displays the same png icon, which is logical, but I want to change it to another png that shows an up arrow, but I’m not sure how to do it. I figured out how to change the color of the show less button, but not the image/icon arrow.Thank you very much for any assistance.

 function toggleText() {
  var showMoreText = document.getElementById("more");  
  var buttonText = document.querySelector("#moreButton p");
  
  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-column-group";
    buttonText.innerHTML = "Show More";    
    buttonText.classList.remove('less')
  } else {
    showMoreText.style.display = "table-column-group";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less')
  }
}
.pink{
    color: #FF7B5F;
  }

  #more {
    display: none;
}

  #moreButton{
    background-color:transparent;
    border-color: transparent; 
   }


   .less{
       color: #FF7B5F;
   }
<html>

<head>
 <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
 </head>
 
 <body> 
 <container>
 <div id="startpoint"></div>
            <div id="more">
            <div class="clients BRANDING col-6 col-md-4 col-lg-3 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://www.wrappixel.com/demos/ui-kit/wrapkit/assets/images/team/t3.jpg" width="150" alt="Logo">
                  <figcaption class="product-desc"><P>text</P></figcaption>
                  <figcaption class="product-desc2"><h4>text</h4></figcaption>
                </figure>
              </a>
            </div>
            
            <div class="clients BRANDING col-6 col-md-4 col-lg-3 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://www.wrappixel.com/demos/ui-kit/wrapkit/assets/images/team/t3.jpg" width="150" alt="Logo">
                  <figcaption class="product-desc"><P>text</P></figcaption>
                  <figcaption class="product-desc2"><h4>text</h4></figcaption>
                </figure>
              </a>
            </div>
          </div>
          <button onclick="toggleText()" id="moreButton">
           <p class="pink">Show More</p> 
           <img class="more" src="./images/downarrow.png" alt="">
          </button>
          </div>
        </div>  
        <section class="team text-center bg-dark py-1">
        
              <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  </container>
  
        </body>
        </html>
        

Discord.js Bot Error: TypeError: voice_channel.join is not a function (Discord.js V13.6.0)

I have been following a tutorial by CodeLyon on how to create a Discord music bot. After following it step by step when he tests the bot at the end of the video, it works fine, whereas when I try and test my bot, I am given this error in the terminal.

TypeError: voice_channel.join is not a function

Has this function changed in a new version of Discord.js? There have been a couple of times where I’ve had to Google a broken function to find the updated code as the tutorials are just over a year old, though this time I can’t find anything.

Here is a snippet of the code which is giving me the TypeError, I’ve scanned through the SourceBin he provided in the description but it appears that I’ve coded everything correctly, as well as installed all the packages provided in the video.

//Establish a connection and play the song with the video_player function.
try {
    const connection = await voice_channel.join(); //Error is on this line
    queue_constructor.connection = connection;
    video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
    queue.delete(message.guild.id);
    message.channel.send('There was an error connecting...');
    throw err;
}
} else {
    server_queue.songs.push(song);
    return message.channel.send(`**${song.title}** added to queue!`);
}

How can you dynamically switch SignalR hubs

I have 2 hubs that live on 2 different servers. Ideally I would like my series of webpages to connect to attempt to connect to 1 of these hubs, then if it fails switch to the other hub. Is this possible at all.

I can’t use the traditional method to connecting to the hub like so:

<script id="hubScript" src="IP:port/signalr/hubs"></script>
    $.connection.hub.url = SIGNALR_HUB_SERVER_1;
    srv = $.connection.tcpHub;

since I don’t know which hub I will be connecting to, or which hub will be alive.

Example of code that I have tried for reference

   if (document.head.getElementsByTagName("script").item(i).src == SIGNALR_HUB_SERVER_1 + "/hubs") {
        $.connection.hub.url = SIGNALR_HUB_SERVER_1;
   }
   else if(document.head.getElementsByTagName("script").item(i).src == SIGNALR_HUB_SERVER_2 + "/hubs") {
        $.connection.hub.url = SIGNALR_HUB_SERVER_2;
   }

When I try and connect using this code I get the error: “Error loading hubs. Ensure your hubs reference is correct”. This is because my script tag that contains the url is not the same as the url that I am trying to connect to.

Clicking button changes View in .NET/MVC web app

I’m very new to .Net development, and I’m working on a ticket. The goal is that when the user clicks a button, they’ll be redirected to another page on our website (that i have to create)- this new page will have the same header/footer/css but different elements in the body.

my question is: how do i go about creating this? do i need a new method in the controller to return a new view? Do i need a new JS file?

There’s so many different parts to .NET and i’m struggling to understand where the code goes

any advice would be much appreciated!!

Allocate Shares Following Instruction List

Below is the coding question:

Assuming I bought 165 shares at the following rate:

Number of shares Price per share
23 2.5
47 2.54
45 2.56
50 2.6

Allocate the 165 shares using the following instruction:

  • 50 shares to account1,
  • 53 shares to account2,
  • 17 shares to account3,
  • 45 shares to account4.

All of the account must be allocated based on “Lowest Price First Top to Bottom”

I’ve gotten this far with it:

let shares = [
    { numOfShares: 23, price: 2.5 },
    { numOfShares: 47, price: 2.54 },
    { numOfShares: 45, price: 2.56 },
    { numOfShares: 50, price: 2.6 },
  ];
  let allocate = [
    { numToAllocate: 50, name: "account1" },
    { numToAllocate: 53, name: "account2" },
    { numToAllocate: 17, name: "account3" },
    { numToAllocate: 45, name: "account4" },
  ];

  for (let eachAllocate of allocate) {
    let num = eachAllocate.numToAllocate;
    let numOfShares = 0;
    for (let eachShare of shares) {
      num -= eachShare.numOfShares;
      if (num > 0)
        console.log(
          `Account: ${eachAllocate.name}, Quantity Assigned: ${eachShare.numOfShares}, trade price: ${eachShare.price}`
        );
      if (num <= 0) {
        console.log(
          `Account: ${eachAllocate.name}, Quantity Assigned: ${
            num + eachShare.numOfShares
          }, trade price: ${eachShare.price}`
        );
        numOfShares = parseInt(num * -1);
        console.log(numOfShares);
        break;
      }
    }
  }

Output:

Account: account1, Quantity Assigned: 23, trade price: 2.5
Account: account1, Quantity Assigned: 27, trade price: 2.54
20
Account: account2, Quantity Assigned: 23, trade price: 2.5
Account: account2, Quantity Assigned: 30, trade price: 2.54
17
Account: account3, Quantity Assigned: 17, trade price: 2.5
6
Account: account4, Quantity Assigned: 23, trade price: 2.5
Account: account4, Quantity Assigned: 22, trade price: 2.54
25

So here my problem is, I am not quite sure how to enforce it so each time I go through eachAllocate it doesn’t start from beginning, it continues from where it’s left off.. So 20, 17, 6, 25 are numbers where it’s left off from previous allocation…

Access JavaScript filter function in object of functions: Cannot read properties of undefined (Vuex store)

The problem in my vuex store index.js:

I want to filter an array with another array. If I access the filter function in its object I get an:

TypeError: Cannot read properties of undefined (reading 'includes')
    at aspect_ratio (index.js?9101:72:1)

I have all my filter functions in an object like this:

export const filter_functions = {
  form_factor_landscape: (obj) => {
    return obj["Form Factor"] === "Landscape";
  },
  form_factor_portrait: (obj) => {
    return obj["Form Factor"] === "Portrait";
  },
  aspect_ratio: (obj) => state.current_features.includes(obj["Aspect Ratio"]),
};

In my getters I want to access the aspect_ratio filter like this:

export const getters = {
  filtered_items(state) {
      const filteredArray = [...state.allHandhelds].filter(
        filter_functions[state.current_sort]
      );
      return filteredArray.filter(filter_functions.aspect_ratio);
    } 
  },
};

my state is like this:

export const state = () => ({
  current_sort: "all_handhelds",
  current_features: ["a", "b", "c"],
  allHandhelds: [],
});

My thoughts:

It seems like there is some problem with accessing the object with the filter functions. Or more precisely accessing the current_features array from the state.

Strangely if I just take the filter function outside the object and directly embedd it everything works. Like this:

return filteredArray.filter((obj) => state.current_features.includes(obj["Aspect Ratio"]));

Any idea what I’m doing wrong?

How can i add new elements at the beggining while i am scrolling?

I have this code where when i am scrolling down i am appending new elements

<div class="card-container">
        <div class="card show">First card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
</div>

JS

const cards = document.querySelectorAll('.card');
const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
        entry.target.classList.toggle('show', entry.isIntersecting);
    })
})

const lastCardObserver = new IntersectionObserver(entries => {
    const lastCard = entries[0];
    if(!lastCard.isIntersecting) return
    loadNewCards();
    lastCardObserver.unobserve(lastCard.target);
    lastCardObserver.observe(document.querySelector('.card:last-child'));
}, {rootMargin: '200px'})

const cardContainer = document.querySelector('.card-container');
function loadNewCards() {
    for(let i = 0;i < 10;i++) {
        const card = document.createElement('div');
        card.textContent = 'new card';
        card.classList.add('card');
        card.classList.add(`card-${i}`);
        observer.observe(card);
        cardContainer.append(card);
    }
}

cards.forEach(card => {
    observer.observe(card);
})

lastCardObserver.observe(document.querySelector('.card:last-child'))

EVERYTHING WORKS FINE

but i need now when i am at the beggining at the element which is on the viewport, while i scroll up
to add new elements so to detect that i am scrolled to the first element in the viewport

How can i do that

Displaying current value of order (checkbox problem)

I have a problem with my Formik and checkbox. I wanted to display the current value of the order which te checked values would determine. The problem is that when I tried to either call function sumProducts or addChecked inside Formik there:

{(values) => {
                    
  sumProducts(values.values.checked)

it doesn’t work correctly. It seems like it multiplies the original price * 3.
Anyway I wouldn’t like to use sumProducts immedietaly, because at first I wanted to determine whether I unchecked or checked the checkbox. That’s why I created the addChecked function, but when after checking if the value is being checked or unchecked and wanting to call the function sumProducts inside addChecked I have error that I went into infinite loop/renders.

import { Formik,Field,Form,ErrorMessage } from 'formik';
import React, {useState} from 'react';
import {v4 as uuidv4 } from 'uuid';
import {connect} from "react-redux";
import {Order} from "../../ducks/orders/OrderInterfaces";
import {addOrder} from "../../ducks/orders/OrderActions";
import {RootStore} from "../../ducks/RootReducer";
import {Product} from "../../ducks/products/ProductsInterfaces";
import {User} from "../../ducks/users/UserInterfaces";

interface OrdersFormProps {
    addOrder: (order: Order) => void,
    products: Product[],
    users: User[]

}

const ProductsForm = ({addOrder, products, users}: OrdersFormProps) => {

    interface OrdersFormValues {
        id: string,
        client: string,
        checked: Array<string>

    }

    const initialValues: OrdersFormValues = {
        id: uuidv4(),
        client: '',
        checked: [],

    }

    const handleSubmit = (values: OrdersFormValues) => {
        console.log(values)
      // addOrder(values)
    }
    const [checked,setChecked] = useState<string[]>([])
    const [currentPrice,setCurrentPrice] = useState(0)

    const addChecked = (prod: string) => {
        checked.find(product => product === prod) ? checked.filter(product => product !== prod)
            : setChecked(prev => [...prev,prod])
        //sumProducts(checked)
    }
    const sumProducts = (prod: Array<string>) => {
        const sum = prod.reduce((acc,curr) => {
            const currProduct = products.find(product => product.id === curr)
            if (currProduct) {
                return acc+currProduct.price
            }
            return acc
        }, 0)
        setCurrentPrice(currentPrice => currentPrice+sum)
    }
    return (
        <div>
            <Formik
                initialValues={
                    initialValues
                }
                onSubmit={(values, {resetForm}) => {handleSubmit(values); resetForm({values: undefined})}}
                enableReinitialize={true}>
                {(values) => {
                    //sumProducts(values.values.checked)
                    return (
                        <Form>
                            <label htmlFor="client">Client:
                                <Field name="client" as="select">
                                    <option disabled value="">(select a client)</option>
                                    {users && users.map(user => (
                                        <option value={user.id} key={user.id}>{user.firstName} {user.lastName}</option>
                                    ))}
                                </Field>
                                {products && products.map(product =>
                                    <label>
                                        <Field type="checkbox" name="checked" value={product.id} key={product.id} /> {product.name}
                                    </label>
                                )}
                            </label>
                            <button type="submit">
                                Submit
                            </button>
                        </Form>
                )}}

            </Formik>
            <p>Current price of order: {currentPrice}</p>

        </div>
    );
};

const mapStateToProps = (state: RootStore) => {
    return {
        products: state.products.products,
        users: state.users.users
    }

}

const mapDispatchToProps = {
    addOrder
}

export default connect(mapStateToProps,mapDispatchToProps)(ProductsForm);