Add class to an input when its focused, and remove it when isnt focused

I’m trying to add the class “.contact__form-input–focused” to the input that is focused from a form.

I’m trying to do that adding an event listener to every input, and then if it has the class already delete that class from the classlist.

//INPUT ANIMATION
const input = document.querySelectorAll("contact__form-input");

function addClass(input) {
  input.classList.add("contact__form-input--focused");
}

function removeClass(input) {
  input.classList.remove("contact__form-input--focused");
}

for (let i = 0; i < input.length; i++) {
  if (item[i].classList.contains("contact__form-input--focused")) {
    item.addEventListener("focus", addClass(input[i]));
  } else {
    item.addEventListener("blur", removeClass(input[i]));
  }
}
.contact__form {
  display: flex;
  flex-direction: column;
}

.contact__form-input {
  border: none;
  border-bottom: .1rem solid rgba(0, 0, 0, .12);
  font-size: var(--medium-font-size);
  margin: 0;
  padding: 4px 0;
  width: 100%;
  background: 0 0;
  text-align: left;
  color: inherit;
}

.contact__form-input--focused {
  /*some animations here*/
}
<form class="contact__form" method="POST">
  <label class="contact__form-label">
            <span>Name</span>
            <input class="contact__form-input" name="Name" type="text" autocomplete="name" required>
          </label>
  <label class="contact__form-label">
            <span>Phone number</span>
            <input class="contact__form-input" name="Phone number" type="tel" autocomplete="tel" required>
          </label>
  <label class="contact__form-label">
            <span>Message</span>
            <input class="contact__form-input" type="text" required>
          </label>
  <button class="contact__form-button">Send</button>
</form>

ReactJS Update child component after API call returns

So I have a simple reactJS app that contains a app.js with a HomePage.js

The HomePage.js need to display some data for me that I fetch trough an await API.get method from amplify. ( : https://docs.amplify.aws/lib/restapi/fetch/q/platform/js/ )
The API.get method triggers the .then response and then gives me exactly the correct array with item that I want.

Now I want to render those items on my HomePage.js, which is a functional component.

My app.js looks like this (ignore the token stuff, this is another problem i need to solve) :

import React, { useState } from "react";
import logo from './logo.svg';
import './App.css';
import Amplify, { API, Auth } from 'aws-amplify';
import { withAuthenticator , Link } from "@aws-amplify/ui-react";
import '@aws-amplify/ui-react/styles.css';
import { Button } from '@aws-amplify/ui-react';
import Appbar from "../src/components/Appbar/Appbar";
import Homepage from './components/Homepage/Homepage';

// let user;
let user = {}; 
let userName = "placeholder";
// let pageLoaded = false;
let passArray;
let zorgSearchData;

function App() {

  callApi();
  async function callApi() {
    user = await Auth.currentAuthenticatedUser()
    const token = user.signInUserSession.idToken.jwtToken
    userName = user.username;
    const requestData = {
      headers: {
        Authorization: token
      }
    }


    zorgSearchData = await API
    .get('caresyncapi' , '/items/zorgsearch/' + userName)
    .then(response => {
      console.log("resp!")
      console.log(response);
      passArray = response;
    })
  }

  return (
      <div className="App">
        <Appbar/>
        {<Homepage passedArray={passArray} />}

    </div>
    );  
  }


export default withAuthenticator(App);

The API.get calls and the .then prints out the exact response I want. I pass passArray as a prop to HomePage.js which (i think and am probably wrong) should update with the new data. The problem is when the .then is called there is no change in the Homepage.js . The props I retrieve in Homepage.js is always undefined. I think this is because the API is async and retrieves the prop after I pass it for the first time. But how do I update this? Anyway, my Homepage.js looks like this:

import React, { useState } from 'react';
import "./homepage.css";
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import { Typography } from '@material-ui/core';

const useStyles = makeStyles((theme) => ({
    formControl: {
      margin: theme.spacing(1),
      minWidth: 120,
    },
    selectEmpty: {
      marginTop: theme.spacing(2),
    },
  }));

const Homepage = ({props}) =>{
    const classes = useStyles();
    const [age, setAge] = useState(''); 
    console.log(props);


    function handleChange (event) {
        console.log(event.target.value); 
        // console.log({passedData})
        //setAge(event.target.value);
    };

    return (
        <>
            <Typography variant="h1">{`Welcome,username`}</Typography>
                <FormControl variant="outlined" className={classes.formControl}>
                    <InputLabel id="demo-simple-select-outlined-label">Age</InputLabel>
                    <Select
                    labelId="demo-simple-select-outlined-label"
                    id="demo-simple-select-outlined"
                    value={age}
                    onChange={handleChange}
                    label="Patienten"
                    >
                        {/* {this.state.searchData.map(x=> <MenuItem >{x.PatientNaam}</MenuItem>)} */}
                        <MenuItem value="">
                            <em>None</em>
                        </MenuItem>
                        <MenuItem value={10}>Ten</MenuItem>
                        <MenuItem value={20}>Twenty</MenuItem>
                        <MenuItem value={30}>Thirty</MenuItem>
                    </Select>
                </FormControl>
            <div className="homepage-container">
                <div className="homepage-text-container">
                    <h1 className="welcome-message">Hello, {props}</h1>
                    <p>lorem ipsum</p>
                </div>
                <div className="chart-container">
                    <div className="chart-1">
                        <h3>Chart 1</h3>
                        <div className="chart"></div>
                        <p>More text....</p>
                        <p></p>
                    </div>
                </div>
            </div>
        </>
    )
}



export default Homepage

As you can see I am also trying to fill the select form with my array names, but I think I can figure that out as long as I have a valid array. I tried different methods of the handleChange and passing props, but nothing seems to work.

TL;DR : I have a app.js which calls an async get function, this returns a valid object I use. The problem is I pass this object array to Homepage.js ( {} ) before the async method returns a value. So the array is always undefined in Homepage.js

Can someone point me in the right way? Do I need to force a change? Is there a way to pass the prop again? Is there something I can do in the handleChange method? I can access the .then method, do I need to do something from there? Simply updating the variable doesn’t seem enough.

Thanks in advance! Sorry for the ramble im new to reactJS and I am trying to solve this problem after a few beers.

how to close the sidebar when clicking outside?

I’m a noobie at programing. I’m currently making a simple shop website for a project in class. I’m currently struggling with how to make it work.

This is my complete style sheet

     <style>
        .open{
            cursor: pointer;
            background-color: black;
            text-align: center;
            padding: 5px;
            font-size: 40px; 
        }
        
        .open i {
            color: white;
            height: 50px;
            width: 50px;
        }
        
        #Sidenav {
            height: 100%;
            width: 0px; 
            position: fixed;
            z-index: 1; 
            top: 0; 
            left: 0; 
            background-color: black;
            overflow-x: hidden; 
            transition: 0.5s; 
        }
        
        .logo {
            margin: 20px 0 0 0; /* top right down left */
            width: 75%;
            padding-bottom: 10px;
            border-bottom: 1px solid white;
        }
        
        .logo img {
            margin: 0;
            height: 100px;
            width: 100px;
            
        }
        
        .sidenav ul {
            margin: 0 0 0 12.5%;/* top right down left */
            padding: 0;
            width: 75%;
            list-style: none;
        }
          
        .sidenav ul li a {
            text-decoration: none;
            color: black;
            position: relative;
        }
        
        .sidenav ul li{
            margin: 10px 0 10px 0; /* top right down left */
            background-color: white;
            border-radius: 20px;
            text-align: center;
            line-height: 30px;
            font-size: 20px;
        }
    </style>

All of HTML codes are working fine

<body>
    <span class="open" onclick="OpenNav()"><i class="fas fa-bars"></i></span>/* My button */

    <nav id="Sidenav" class="sidenav">
            
            <center>
                <div class="logo">   
                    <<img src="#" alt="logo"/>
                <div>
            </center>
            
            <ul>
                <li><a href="#">All Items</a></li>
                <li><a href="#">Smartphones</a></li>
                <li><a href="#">Appliances</a></li>
                <li><a href="#">PC Components</a></li>
                <li><a href="#">Software</a></li>
                
                <li><a href="#">My Cart</a></li>
                <li><a href="#">Account</a></li>
                <li><a href="#">Shop Inventory</a></li>
                <li><a href="#">Login</a></li>
            </ul>
        </nav>
    
    <h1>Content
    <div id="main">
        
    </div>

The function OpenNav() work fine as well, but when I put the Closenav function I can’t click on anything else.

    <script>
        function OpenNav() {
          document.getElementById("Sidenav").style.width = "250px";
        }

        document.onclick = function(Closenav){
           if(Closenav.target.id !== 'Sidenav'){
              document.getElementById("Sidenav").style.width = "0px";
           };
        };
    </script>
</body>

Why quick sort is always slower than bubble sort in my case?

They use same array:

QUICK SORT Time: 3159 miliseconds (array length 10K)

Bubble SORT Time: 1373 miliseconds (array length 10K)

I’m trying to compare time of the sorting using quick and bubble sort algoritms. I use the array with 10K different random numbers sorted in random order for both functions. But for some reason bubble sort is always sort array faster than quick sort, even if average time complexity of bubble sort is worse than average time complexity of quick sort. Why bubble sort algorithms slower than quick sort algorithm in my case? (I tried different lengths of array, from 10 to 10K)

Thats my quick sort function

let quickSort = (arr) => {
    if (arr.length <= 1) {
        return arr
    }
    const pivot = arr[0]
    const rest = arr.slice(1);
    let left = [],
        right = [];
    rest.forEach(el => el > pivot ? right = [...right, el] : left = [...left, el]);
    return [...quickSort(left), pivot, ...quickSort(right)];
}

And that’s my bubble sort function

let bubbleSort = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        for (let s = i + 1; s < arr.length; s++) {
            if (arr[s] < arr[i]) {
                let a = arr[i];
                arr[i] = arr[s]
                arr[s] = a;
            }       
        }
    }
    return arr
}

add an active class to one of my elements and select only the relevant parent

In my menu I would like to add an active class to one of my elements: li.nav-item
and this only if the child item: ul.nav-collapse.li has the active class.

for this I made a script that works but it adds the active class to all elements: li.nav-intem

I would like it to select only the relevant parent: li.nav-item
which contains the active class ul.nav-collapse.li.active

JS

$('ul.nav-collapse li').each(function(){
    if($(this).hasClass('active')) {
        $(this).parent().parent().parent().parent().find('li.nav-item').addClass("active");
    }
});



HTML

<ul>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu1">
            <p>My Folder</p>
        </a>
        <div class="collapse" id="submenu1">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder">
                        <span class="sub-item">SubFolder</span>
                    </a>
                </li>
                <li class="active">
                    <a href="SubFolder2">
                        <span class="sub-item">SubFolder2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu2">
            <p>My Folder2</p>
        </a>
        <div class="collapse" id="submenu2">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder2">
                        <span class="sub-item">SubFolder2</span>
                    </a>
                </li>
                <li class="">
                    <a href="SubFolder2_2">
                        <span class="sub-item">SubFolder2_2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu3">
            <p>My Folder2</p>
        </a>
        <div class="collapse" id="submenu3">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder3">
                        <span class="sub-item">SubFolder3</span>
                    </a>
                </li>
                <li class="">
                    <a href="SubFolder3_2">
                        <span class="sub-item">SubFolder3_2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
</ul>

I would like something like this

<ul>
    <li class="nav-item active">
        <a class="" data-toggle="collapse" href="#submenu1">
            <p>My Folder</p>
        </a>
        <div class="collapse" id="submenu1">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder">
                        <span class="sub-item">SubFolder</span>
                    </a>
                </li>
                <li class="active">
                    <a href="SubFolder2">
                        <span class="sub-item">SubFolder2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu2">
            <p>My Folder2</p>
        </a>
        <div class="collapse" id="submenu2">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder2">
                        <span class="sub-item">SubFolder2</span>
                    </a>
                </li>
                <li class="">
                    <a href="SubFolder2_2">
                        <span class="sub-item">SubFolder2_2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu3">
            <p>My Folder2</p>
        </a>
        <div class="collapse" id="submenu3">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder3">
                        <span class="sub-item">SubFolder3</span>
                    </a>
                </li>
                <li class="">
                    <a href="SubFolder3_2">
                        <span class="sub-item">SubFolder3_2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
</ul>

any idea?

Await is only valid in async functions and the top level bodies of modules? [duplicate]

I am running a migration script in sequelize:

    let sort = 10;

return await queryInterface.sequelize.transaction(async (transaction) => {
  await Promise.all(
    sortedHolidays.map((holidayName) => {
      sort += 10;
      await Model.Holiday.update({ sort }, { where: { holidayName }, transaction });
    })
  );
});

I defined all my functions async, and awaiting all the functions, why am i getting this error of :
Await is only valid in async functions and the top level bodies of modules?

Rock Paper Scissors Prompt To Ask for Decision to run the game

Hello StackOverflow Community,

I have been studying JavaScript for about 3 days give or take and I have created a rock paper scissor “game” that runs but only with the player decision is added to the code. I wanted to fix this instead so that an prompt alert pops up to ask “Pick Rock, Paper, Scissor Now” and have the game use that input as the deciding factor to who will win. I have ran the code that I have provided and ended up this error:

 a internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module 'readline-sync'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/tmp/zUokdwLcHz.js:1:20)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3) 

I tried reviewing my spelling and ()/;/, to make sure that they are all correct and I feel like they are. I am sure this is an easy fix so thank you in advance you if you can guide me the correct way.

Here is the code:

const userInput = prompt("What will you shoot")
userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
  return userInput;

} else {
  console.log("Error!");
}

const ComputerChoice = () => {
  const randomNumber = Math.floor(Math.random() * 3)
  if (randomNumber === 0) {
    return "rock";
  } else if (randomNumber === 1) {
    return "paper";
  } else {
    return "scissors";
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return "Tie, please try again";
  } else if (userChoice === "paper" && computerChoice === "rock") {
    return "Player wins";
  } else if (userChoice === "scissors" && computerChoice === "Paper") {
    return "Player wins";
  } else if (userChoice === "rock" && computerChoice === "scissors") {
    return "Player wins";
  } else if (userChoice === "bomb") {
    return "Player wins"
  } else {
    return "Computer Wins"
  }
}

const playGame = () => {
  const userChoice = getUserChoice('')
  const computerChoice = ComputerChoice()
  console.log("you threw a " + userChoice);
  console.log("The computer threw a " + computerChoice);

  console.log(determineWinner(userChoice, computerChoice));
}

playGame();

save and update twitch followings. Javascript

I would like the usernames from user x, which are followed by person x. if I use my function “secondFunction ()” then it adds each new person individually in square brackets. I’m slowly becoming desperate, I want to use the function to add users manually, update followers and remove duplicates. So far it has always overwritten the existing users for me. I was now at the point where they are added and not overwritten. I hope and ask for your help 🙂
I once uploaded the code to jsfiddle so as not to make it too crowded ^^

https://jsfiddle.net/jwqh46xy/

my “con.json” looks like this:

user 5, 6 & 7 would be the ones that were newly added

{
  "applicationid": "123456",
  "token": "123456",
  "access_token": "123456",
  "twitch": {
    "userX": [
      "user1",
      "user2",
      "user3",
      [
        "user5"
      ],
      [
        "user6"
      ],
      [
        "user7"
      ]
    ],
    "user1": [
      "user1",
      "user2",
      "user3",
      [
        "user5"
      ],
      [
        "user6"
      ],
      [
        "user7"
      ]
    ],
    "otherData": {
      "Anything": "value",
      ...
    },
    ...
  }
}

Many thanks in advance

Can anyone explain to me why escaping numbers n Regular Expressions causes an error

I am writing some code for someone and wanted to show them different ways they could count the no of times a character/no occur in a longer string using both IEnumerable and RegEx however I have found that when I am trying to count the no of times a number occurs in a string none of my methods work despite me converting the no into a literal character first. However trying to use a variable and the cast methods does not work e.g:

char chr = '2'; // works fine

So this literal works however all the other ways which I need to be able to use on variables such as converting an int variable into a char with either (char)no or Convert.ToChar(no) doesn’t work for some reason.

I am sure there is a simple reason but I cannot seem to crack it.

This is my code, the reason there are two methods using RegEx is that I was testing the best way to count special characters such as dots . in a string with C#.

I didn’t know whether it was best to just RegEx.Escape any variable being passed in to my count method or whether I needed to check first whether it needed to be escaped before doing so or just leaving the character alone.

The code calling the test functions is below, the reason I am using a static class to log out the errors is I am just adding this method into a bigger project to do the test quickly and all the HelperLib class is used for is logging with adding a date stamp next to each line, debugging, setting up system wide settings on load and so on…

private void TestCode()
{
    this.HelperLib.LogMsg("IN TestCode - Run Tests on numbers");

    string word = "22.2.34.3";
    int no = 2;
    // char chr = (char)(no); // converting a variable which I need to do doesn't work
    char chr = Convert.ToChar(no) // doesn't work
    // char chr = '2'; // when we do it as a literal it works

    // correct amount of 2 (as a char) in the string should be 3 but we get 0 for each attempt
    int a = word.CountChars(chr);
    HelperLib.LogMsg("Use IEnumerable.Count; There are " + a.ToString() + " occurrences of " + chr.ToString() + " in " + word);

    int b = word.CountChars2(chr);
    HelperLib.LogMsg("RegEx.Escape all chars; There are " + b.ToString() + " occurrences of " + chr.ToString() + " in " + word);

    int c = word.CountChars3(chr);
    HelperLib.LogMsg("Test for special char first before escaping; There are " + c.ToString() + " occurrences of " + chr.ToString() + " in " + word,);

    return;
}

And the methods I am using are in an Extensions class so I can just add them to strings.

public static int CountChars(this string value, char letter)
{
    int count = value.Count(ch => ch == letter);
    return count;
}

public static int CountChars2(this string value, char letter)
{
     // if the letter is a special char then escape it otherwise leave it alone
     string re = (letter.IsSpecialChar()) ? Regex.Escape(letter.ToString()) : letter.ToString();                           
     int c = Regex.Matches(value, re, RegexOptions.IgnoreCase).Count;
     return c;
 }

public static int CountChars3(this string value, char letter)
{
    // escape all characters passed in, in case its a special character               
    string re = Regex.Escape(letter.ToString());
    int c = Regex.Matches(value, re, RegexOptions.IgnoreCase).Count;
    return c;
}

// test to see if we need to escape a character that is a special character in RegEx
public static bool IsSpecialChar(this char letter)
{
    char[] x = { '.', '\', '+', '*', '?', '[', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', ':', '-', '#' };
    bool ret = (x.Contains(letter)) ? true : false;
    return ret;
}

And the debug I get back is below…

10/12/2021 23:11:28 - IN TestCode - Run Tests on numbers;
10/12/2021 23:11:28 - Use IEnumerable.Count; There are 0 occurrences of 2 in 22.2.34.3;
10/12/2021 23:11:28 - RegEx.Escape all chars; There are 0 occurrences of 2 in 22.2.34.3;
10/12/2021 23:11:28 - Test for special char first before escaping; There are 0 occurrences of 2 in 22.2.34.3;

So I can count letters including special characters used in RegEx like dots without a problem but when it comes to numbers even converting them to a character first doesn’t seem to work and I am stuck to why this is occurring as a literal ‘2’ works but a variable converted to a Char doesn’t.

Also when using JavaScript, as I have a test page for testing expressions before using them in whatever language I need, I have found that escaping every character doesn’t work when it comes to numbers OR special characters for example with the same string “22.2.34.3” when I try 2 it return 0 matches but just 2 returns 3 with this code:

// returns 0
var value = "22.2.34.3";
re = "2"; // tried with double \ and triple \
var exp = new RegExp(re,"gi");
var no = value.match(exp)||[];
alert("NO OF MATCHES " + no.length);

// returns 3
var value = "22.2.34.3";
re = "2";
var exp = new RegExp(re,"gi");
var no = value.match(exp)||[];
alert("NO OF MATCHES " + no.length);

What does a single escaping backslash next to a digit mean to the RegEx machine as it works with letters except special RegEx characters like d or w however I thought by escaping those characters it would mean they would be treated like literals not special characters (digit, word char) etc?

Therefore in JavaScript what would I need to do to count the number of a single no in a longer number e.g “2” in “22.2.34.3” OR count the number of character “d” in a string like “does it matter don’t do it” as a single escape string doesn’t work with the code I am using shown above (or a double/triple backslash)??

Any help in understanding this would be appreciated. Thanks.

How to get Async code to actually wait for the function to finish executing before continuing [duplicate]

What I’m trying to do

I’m still new to working with asynchronous code, I’m trying to do something basic, but I’m not seeing what’s missing here.

So I have this function that gets all orders from Firestore.

getAllOrders() = async () => {
    var orderArray = []

    this.firestore.collection('orders')
      .where('status', '==', status) 
      .where('createdAt', '>=', start)
      .where('createdAt', '<=', end)
      .get()  
      .then(snapshot => {              
        snapshot.forEach(docs => {
            orderArray.push(docs.data())
        })
        console.log(orderArray); //outputs the orders correctly
        return orderArray;
       }).catch(error => {
        console.log(error)
       })
}

I want to call getAllOrders to get the orders and output them to the console. I tried the 2 following methods to get the orders to print. Both output undefined.

Method 1

const onSubmit = async () => {
    props.firebase.getAllOrders().then((orders) => {
        console.log(orders);
    })
}

Method 2

const onSubmit = async () => {
    const orders = await props.firebase.getAllOrders()
    console.log(orders)

}

The first thing that is outputted is undefined and then the correct order array, so the await is not working. I know I’m missing something to get this to work. What should I change it to make it work?

In Angular, how would you move a component in the dom?

Started to learn Angular, so this might have a simple answer 🙂

Without getting to code specific. I’m looking for help, getting in the right direction.

Working on a little shoppinglist application.
The point is, when you found something at the grocery store, you click on the item and it move down in a “found items region of the page”
click and move below image

atm. the blue components are actually just buttons in the template, but could be anything really.
They are instances of a “grocery component”, that are nested within a “shopping list” component, build with an ngFor.

In my head it would make sense to work with a single array and filter on that.
I’ve tried that, and it sort of works, but I can’t get it to move once the initialization is done.
so somehow when I click on a grocery component, I need to tell the shopping list component to move this down in the “grocery found” part of the dom. or vice versa if you want to move it back up.

Any hits or comments would be helpful.

javascript – react material ui pupulate table using API

I am trying to populate the StickyTable template in react. I am not seeing anyhting in my console log but an empty array.

Is there anything obvious that I am missing in my code? I cannot seem to figure out where I am going wrong with this and perhaps a second pair of eyes could help me.

I know my backend is working properly but there is something going wrong on this frontend code

export default function StickyHeadTable() { 
    const rows = useState( [
      createData(1, "fruit ID", 'fruitId'),
      createData(2, "fruit Name", 'fruitName'),
      createData(3, "Fruit Price", 'fruitPrice'),

    ]);

    const [dataRows] = useState([]);
    const [data, setData] = useState("");
  
  useEffect(() => {
     
    (async () => {
    fetch(SERVER_URL + "fruits/")
    .then((response) => response.json())
    .then(rowData => {
      // fruits: responseData
      const data= dataRows.map((a) => {
        const dataRows = [];
        this.state.rows.forEach((a, i) => {
          dataRows.push(createData(a.FruitId, a.fruitType, a.fruitPrice));
      });
      })
      console.log("rows", dataRows);
    })

  })();
});

  return (
    <Paper sx={{ width: "100%", overflow: "hidden" }}>
      <TableContainer sx={{ maxHeight: 440 }}>
        <Table stickyHeader aria-label="sticky table">
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell
                  key={column.id}
                  align={column.align}
                  style={{ minWidth: column.minWidth }}
                >
                  {column.label}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row) => {
              return (
                <TableRow
                  hover
                  role="checkbox"
                  tabIndex={-1}
                  key={row.Attribute}
                >
                  {columns.map((column) => {
                    const value = row[column.id];
                    return (
                      <TableCell key={column.id} align={column.align}>
                        {column.format && typeof value === "number"
                          ? column.format(value)
                          : value}
                      </TableCell>
                    );
                  })}
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </Paper>
  );
}

How to Get Data From One Array of Objects into another in Array of Objects in TypeScript

I have a get request in a component that returns a response

  getPaymentIntents():Observable<Payment>>{
    const url: string = 'https://store.com//payments';

    return this.http.get<Payment>>
    (url);
  }

The response data looks something like this (the “Payment” type)

[
    {
        "id": "pi_3K4B432423dqM1gTYncsL",
        "amount": 2000,
        "amount_capturable": 0,
        "amount_received": 0,
        "application": null,
        "canceled_at": null,
        "cancellation_reason": null,
        "created": 1638911287,
        "currency": "usd",
        "customer": "cus_KjDBkdsaHIT6AN"
},
    {
        "id": "pi_3K4BW7EE9YQoA1qM1gTYncsL",
        "amount": 1000,
        "amount_capturable": 0,
        "amount_received": 0,
        "application": null,
        "canceled_at": null,
        "cancellation_reason": null,
        "created": 1638913687,
        "currency": "usd",
        "customer": "cus_KjDBkxEVHIT6AN"
}
]

I want this data to be in a “Material Table” https://material.angular.io/components/table/overview

But I only want it to display a subset of the data. (In the future I will want to combine another response’s data into the table as well)

The type I want to pass to the table as a dataSource is this

export interface OrderToProcess{
  Id: string,
  Amount: number,
  Currency: string
}

How do I go about converting one type into the other, I’ve tried filter() map() object.entries() and I’m sure I’m not using them right but none seem to do what I am after.

Thanks for any help!