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!

Chart js does not display when a variable is used as part of the array

the script below displays a chart using chart js.

<script>
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];

    var yValues = [55, 49, 44, 24, 15];

var barColors = ["red", "green","blue","orange","brown"];

new Chart("myChart", {
  type: "bar",
  data: {
    labels: xValues,
    datasets: [{
      backgroundColor: barColors,
      data: yValues
    }]
  },
  options: {
    legend: {display: false},
    title: {
      display: true,
      text: "World Wine Production 2018"
    }
  }
});
</script>

But I need to replace the numbers with variables that have already been assigned numbers in the document. The chart disappears when I do this as shown below

I replaced this above

var yValues = [55, 49, 44, 24, 15];

with this

var yValues = [$tto_app, $a_rel, $monthly_exp, $cumm_exp];

Please how can I fix this?

Sending files via axios to backend

I have a problem with sending the mp3 file using axios to the backend, everything seems fine when I do console logs on the front, everything is in it, unfortunately on the backend the file field is empty (not null not undefined, just empty).

front console log:
enter image description here

backend console log:
enter image description here

API:

const API = axios.create({baseUrl: 'http://localhost:5000'})


API.interceptors.request.use((req) => {
    if (localStorage.getItem('profile')) {
        req.headers.Authorization = `Bearer ${JSON.parse(localStorage.getItem('profile')).token}`;
    }

    return req;
})
export const addSong = (newSong) =>  API.post('/songs', newSong);

backend

export const addSong = async (req, res) => {
  const song = req.body;


  console.log(song)


  const newSong = new Song({...song, creator: req.userId, createdAt: new Date().toISOString()});

  try {
    await newSong.save();
    res.status(201).json(newSong);
  } catch (error) {
    res.status(409).json({ message: error.message });
  }
};

Matter.js multiple sprites/textures when using poly-decomp in ESM

I am building a simple prototype 2D physics collider editor web app where the problem can be easily recreated.
Tool runtime: https://phys-ed.glitch.me/
With code: https://glitch.com/edit/#!/phys-ed?path=script.js

When I try to use poly-decomp.js to decompose the collider shape (tick ‘Decompose’ checkbox) the resulting body in matter.js has multiple sprites/textures, one per decomposed polygon I guess.

I am using vanilla ESM with no compile step so I wonder if this is a limitation/bug in the libraries which don’t have native ESM support as far as I know or if I am missing some step as I haven’t used poly-decomp.js previously.

Most pertinent code is likely here:
https://github.com/joegaffey/phys-ed/blob/main/script.js#L158
and here:
https://github.com/joegaffey/phys-ed/blob/main/script.js#L188

how to call direct parent’s function by child? [duplicate]

I have three components: ComponentA, ComponentB and Home (Home is the component parent). I want to call a function contains in ComponentA using a button that is inside of ComponentB.

const ComponentA= () => {
  const hello=()=>{
    console.log("hello");
  }
  return <></>
})

const ComponentB= () => {
  const callComponentAFunction=()=>{
   // I need call "hello()" from ComponentA
  }
  return 
   <>
    <button onClick={callComponentAFunction}>Call function from ComponentA</button>
   </>
})

const Home= () => {
 return 
  (<>
   <ComponentA>
     <ComponentB />
   </ComponentA>
   </>)
 })

How can I call hello() function (inside of ComponentA) from ComponentB?

Validate and secure WebSocket data

I have a WebSocket server written in javascript and send data to it from my CSharp application. Now I ask myself how can I make sure that these are correct and not faked. I thought I could do something with hash values but I don’t know how to do that. Does anyone have an idea or code example

is there a way to fluidly calculating total sales using JS with Django

I’m looking for a way to take the information being entered into a database and not only calculate the overall total for a year but also calculate the total for individual months. I’m using Django and Javascript.

The Django View:

@login_required
def proposal_signed(request):
    prop = Proposal.objects.all().order_by('proposal_approved_date')

    return render(request, 'client/proposal_signed.html', {
        'prop': prop,
    })

The HTML and JS:

{% extends 'client/base.html' %}

{% block content %}
    <br>
    <div class="jumbotron jumbotron-fluid">
        <div class="container">
            <div class="text-center">
                <h1 class="display-4"> Sales For Signed Proposals </h1>

            </div>
        </div>
    </div>

    <head>
        <style>
            table {
                font-family: arial, sans-serif;
                border-collapse: collapse;
                width: 100%;
            }

            td, th {
                border: 1px solid #dddddd;
                text-align: left;
                padding: 8px;
            }

            tr:nth-child(even) {
                background-color: #dddddd;
            }
        </style>
        <title></title>
    </head>

    <div class="container">

    <table id="countit">
            <tr>
                <th><strong>Approval Date:</strong></th>
                <th><strong>Job Type:</strong></th>
                <th><strong>Address:</strong>
                <th><strong>Client:</strong></th>
                <th><strong>Bid/Job Total:</strong></th>

            </tr>
            {% for item in prop %}
                 {% if item.proposal_approved_date %}

                    <tr>
                        <td>{{ item.proposal_approved_date }}</td>
                        <td>{{ item.client.requested_service }}</td>
                        <td>{{ item.client.work_site_address }}</td>
                        <td>{{ item.who_to_bill_name }}</td>
                        <td class="count-me">{{ item.client.invoice_set.get.bill_amount }}</td>
                    </tr>

                {% endif %}
            {% endfor %}

        </table>

    <script language="javascript" type="text/javascript">
            var tds = document.getElementById('countit').getElementsByTagName('td');
            var sum = 0;
            for(var i = 0; i < tds.length; i ++) {
                if(tds[i].className === 'count-me') {
                    sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
                }
            }
            document.getElementById('countit').innerHTML += '<tr><td><strong>Total:</strong></td><td>' + sum + '</td></tr>';
        </script>
    

    </div>

    <br>
    <br>

{% endblock %}

This gives me the table with the values and the grand total for the items in the Bid/Job Total on the bottom but I could use some help with breaking it down by month and year. The amount per month is flexible.

Thank you for any help, Dace

Dependency injection question / small example problem

Can simple vanilla dependency injection, such as modules exporting a function that expects an object of dependencies fix the below problem of helper files trying to share their helper functions with each other? Thanks.

index.js

const { sumEvens } = require("./math");

const nums = [1, 2, 1, 1, 2];

console.log(sumEvens(nums));

math.js

const { removeOdds } = require("./filters");

const isEven = (n) => n % 2 === 0;

const sumEvens = (nums) => removeOdds(nums)
  .reduce((sum, n) => sum + n, 0);

module.exports = {
  isEven,
  sumEvens
}

filters.js

const { isEven } = require("./math");

const removeOdds = (nums) => nums.filter((n) => isEven(n));

module.exports = {
  removeOdds
}

TypeError: isEven is not a function, I think because of some circular requiring?

Uncaught TypeError: Cannot read properties of undefined (reading ‘target’) & (reading ‘value’)

After JQuery Version Upgrades to 3.5.0 from 2.14, I am receiving the following error, but I did not fully understand what the problem is,there is radio = event.target The error I received in the definition of Cannot Read Properties of Undefined (Reading ‘target’)
Anyone can you help me solve?
*

var testMethod = {
    testSubMethod: function (event) {
    
        var radio = event.target;
        var isMultiInput = $('#MultipleInputYes').is(':checked');

        if (isMultiInput) {
            $('.divMultiInput').removeClass("dp-none");

            $('.divMinMaxVal').addClass("dp-none")
            $('#divMinMaxDate').addClass("dp-none")

            $('#divRgxWarnMsg').addClass("dp-none")

            $('#minValueInpt').val('');
            $('#maxValueInpt').val('');

            $('.divInputValUpper').addClass("dp-none");
            $('[name=ValueType]').val('');
            $('#inputValueTypeSelect').removeClass('required');
            $('#inputValueTypeSelect').removeClass('customError');

        }
        else if (!isMultiInput || radio.value == undefined) {
            $('.divMultiInput').addClass("dp-none");

            $('.divMinMaxVal').removeClass("dp-none");
            $('#divMinMaxDate').removeClass("dp-none");
            $('#divRgxWarnMsg').removeClass("dp-none")

            $('.divInputValUpper').removeClass("dp-none");
            $('[name=ValueType]').val('1');
            $('#inputValueTypeSelect').addClass('required');

            $('#divWarnMsg').css("display", "inherit");
            $('#placeHolderInpt').val('');
            $("#maskInpt").select2("val", "");

            if (radio.value == 'false') {
                $('#divInputValueType').prop('disabled', false);
                $('#divInputValueType').attr('style', '');
            }

            $('#htmlEditorDiv').css("display", "inherit");
            $('#useMultiLineDiv').css("display", "inherit");

            $("#Tags").tagit("removeAll");
        }
    },
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div class="radio radio-success">
<input type="radio" id="MultipleInputYes" value="true" name="IsMultiInput" onchange="testMethod.testSubMethod(this)">
<label for="MultipleInputYes"> Yes</label>
</div>

<div class="radio radio-success">
<input type="radio" id="MultipleInputNo" value="false" checked="checked" name="IsMultiInput" onchange="testMethod.testSubMethod(this)">
<label for="MultipleInputNo">No</label>
</div>

Create React App. Loading code split from dependency

I have a component library that I want to work with create-react-app style apps.

This component library is being built with webpack and it has a dependency on a WASM module which is being built with wasm_pack.

In the component library, I dynamically import the required wasm library. This produces a code split in the component library and webpack creates an index.js file and a separate file for the code split, call it spec.js as expected.

When I try to import this library in create-react-app however, it attempts to load /static/js/spec.js when the dynamic import code is hit, but nothing is served from that endpoint.

How do you get CRA to simply grab and host the split.js file from the component library?

I have played around with the output.publicPath variable in the webpack config for the component library but that seems to simply change where CRA is trying to pull the spec.js file from.

Do I need to specify something in the package.json file for the component library to include both the main js file and the split file?

For reference the dynamic import code within the component library is

import { useEffect, useState } from 'react'

export const useValidator = () => {
  const [validator, setValidator] = useState<any>(null)
  const [validatorReady, setValidatorReady] = useState<boolean>(false)
  const [error, setError] = useState<any | undefined>(undefined)

  useEffect(() => {
    let f = async () => {
      try {
        console.log("attempting to import wasm")
        const wasm = await import( /*webpackChunkName:"spec"*/ '@maticoapp/matico_spec');
        console.log("gotWasm ", wasm)
        setValidator(wasm)
        setValidatorReady(true)
      } catch (err) {
        setError(`failed to load wasm: ${err}`)
        console.log("unexpected error in load wasm ", err);
      }
    };
    f();
  }, []);
  return { validator, validatorReady, error }
}

the webpack setup for the component library has the entry and output set as

const config = {
  entry: "./src/index.ts",
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath:"auto",
    filename: "index.js",
    library: {
      name: "matico_components",
      type: "umd"
    },
  },

and to handle the WASM import I have this in the component library webpack

  experiments: {
    asyncWebAssembly: true
  },

and I am using react-app-rewired on the CRA to also load in the WASM files.

Also just to note that the actual code split file ends up getting called something else. Just using spec.js here as an example.

Start and Crashed

I can turn on the app normally, but when I go to use it, it stops, no idea what the problem might be.

Logs:

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Stopping process with SIGKILL
Process exited with status 137
State changed from starting to crashed