Uncaught (in promise) ReferenceError: then is not defined at HTMLButtonElement.onboardButton.onclick (app.js:90:11)

Running an async function on click onboardButton.onclick = async () to prompt Metamask wallet login and once the user logs in I run an spinner and load some additional info for the user, but I get an uncaught not defined error on the async function at the then section

Code section follows:

onboardButton.innerText = "Connect MetaMask!";
spinner.classList.add('hidden');
notConnected.classList.remove('hidden');
notConnected.classList.add('show-not-connected');
onboardButton.onclick = async () => {

      // CODE RUNS OK UNTIL HERE, IT LOADS METAMASK POP-UP
  await window.ethereum
    .request({
      method: "eth_requestAccounts",
    });
      // CODE BREAKS HERE, USER CAN INPUT PASSWORD AND CONNECT ITS METAMASK, IT FINISHES CONNECTION, I GET ACCOUNT ADDRESS BACK AND SLICE OK, BUT APP BREAKS.
      then(function (accts) {
      onboardButton.innerText = `✔ ...${accts[0].slice(-4)}`;
      notConnected.classList.remove('show-not-connected');
      notConnected.classList.add('hidden');
      spinner.classList.remove('hidden');
      onboardButton.disabled = true;
      window.address = accts[0];
      accounts = accts;
      window.contract = new web3.eth.Contract(abi, contractAddress);
      loadInfo();
    });
};

}
};

Not able to connect to the express server

I am trying to connect to the express server in which I was able to connect earlier but now am no longer able to connect getting this error “crbug/1173575, non-JS module files deprecated.”

import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import morgan from "morgan";
import userRouter from "./routes/user.js"


const app = express();

app.use(morgan('dev'));
app.use(express.json({limit: "30mb", extended: true}));
app.use(express.urlencoded({limit: "30mb", extended: true}));
app.use(cors());

app.use("/users",userRouter); //http://localhost:5000/users/signup

const MONGODB_URL = "mongodb+srv://alish:<removedThePassword>@cluster0.ksifo.mongodb.net/tour_db?retryWrites=true&w=majority"

const port  = 5000;

mongoose
  .connect(MONGODB_URL)
  .then(() => {
      app.listen(port, () => {
          console.log(`server running on port ${port}`)
      })
  }).catch(error => {
      console.log(`${port} did not connect`)
  })

How can I conditionally render this component based on whether or not there is data in localstorage?

I want MyList to render whatever is in localStorage (works great), however when there is nothing in local storage and I render the component, it renders empty. I would like to have a placeholder there for when that occurs. How can I best do that?

const MyList = ({setDrinks}) => {
    const setMyList = () => {
        let parsedData = JSON.parse(localStorage.getItem('favoriteDrinks'))
        setDrinks(parsedData)
    }

    return (
        <div>
            <button className="my-list" onClick={setMyList}>My List</button>
        </div>
    )
}

export default MyList

Reactjs Empty State when Page Load

API: https://developers.themoviedb.org/

const [searchQuery, setSearchQuery] = useState();
const [searchResults, setsearchResults] = useState([]);

    const getSearchResults = () => {
      baseService.get(`/search/multi?api_key=${API_KEY}&language=en-US&query=${searchQuery}`)
      .then(data=>setsearchResults(data.results))
  }

  useEffect(() => {
    getSearchResults()
    console.log(searchResults)
  }, [searchQuery])
return ( 
    <Container>
            <TextField  color="primary" label="Search for anything" size="small" onChange={(e) => setSearchQuery(e.target.value)}/>
              {searchResults && searchResults.map((search,key) => (
                <span key={key}>{search?.title}</span>
              ))}
            </Container>

baseservice.js is like that

import { API_URL } from "./config"
export const baseService = {
    get: async (url) => {
        let response = [];
        await fetch(API_URL+url, {
        })
            .then((res) => res.json())
            .then((data) => {
                response = data
            })
        return response;
    }
  }

1.Picture is when page load.
enter image description here

2.Picure is when entry search term.
After the entry search:

Nodejs: Exec from child_process returns bin/sh: 1: command not found but works when writing manually in terminal?

Using Node.js to automatically execute command in the terminal on raspberry pi, tho it wont work with exec(command). It outputs bin/sh: 1: command not found when trying to catch the output. But the command works when writing the command manually in the terminal?

Why is that?


async function run_command_fuel() {
    const command = "weconnect-cli PASSWORDINFORMATION get /vehicles/SECRETNUM/domains/fuelStatus/rangeStatus/primaryEngine/remainingRange_km";
   
    let returnval = 0;

    let child = exec(command);


    await new Promise((resolve, reject) => {
        child.stdout.on('data', function(data) {
            console.log('stdout: ' + data);
            returnval = data;
            console.log(returnval);
            resolve();
        });
        child.stderr.on('data', function(data) {
            console.log('stderr: ' + data);
            reject();
        });
        child.on('close', function(code) {
            console.log('closing code: ' + code);
        });
    })

    return returnval;

}

Turn a array of object with a nested object inside into a new array with values from the nested object

I am trying to turn a array that exists of objects with a nested array inside it into a new array that consist of the values inside the nested array separately(Might sound very complicated but example show very clear)

What I have:

const values = [{
    geometry: {
      "coordinates": [11.4828, 59.1264],
      "Type": "point"
    },
    properties: {
      Region: "Oklahoma",
      sales: {
        donuts: {
          2005: 5,
          2006: 8,
          2007: 10
        },
        apples: {
          2005: 10,
          2006: 8,
          2007: 10
        }
      }
    }
  },
  {
    geometry: {
      "coordinates": [9.4828, 76.1264],
      "Type": "point"
    },
    properties: {
      Region: "Texas",
      sales: {
        donuts: {
          2005: 8,
          2006: 0,
          2007: 7
        },
        apples: {
          2005: 7,
          2006: 9,
          2007: 4
        }
      }
    }
  }
]
const filterValue = "donuts"

What My goal is:

newValues =[{geometry: {"coordinates": [11.4828, 59.1264],"Type":"point"},properties:{Region: "Oklahoma",value:5,time:2005}},{geometry: {"coordinates": [11.4828, 59.1264],"Type":"point"},properties:{Region: "Oklahoma",value:8,time:2006}},{geometry: {"coordinates": [11.4828, 59.1264],"Type":"point"},properties:{Region: "Oklahoma",value:10,time:2007}} AND SO ON FOR ALL THE values that are in const donuts/filter for each value. Could also switch out value for donuts if that is easier
}
]

What I have tried so far:

const newObject = []
values.map((value)=>{
  console.log(value.properties.sales.donuts)
  for (var key in value.properties.sales.donuts) {
        if (value.properties.sales.donuts.hasOwnProperty(key)) {
            newObject.push({...value,value.properties:{[key]:value.properties.sales.donuts[key]})
        }
    }
})
console.log(newObject)

MongoDB & Prisma: unilateral M to N relation

Is there a way to make an unilateral m-to-n relation or must both collections have each other’s ids? I’m trying to do something like:

model Country {
  id              String    @id @default(auto()) @map("_id") @db.ObjectId
  name            String    @unique
  users           User[]
}

model User {
  id              String    @id @default(auto()) @map("_id") @db.ObjectId
  userName        String    @unique
  countryIds      String[]  @db.ObjectId
  countries       Country[] @relation(fields: [countryIds], references: [id])
  // ....
}

But prisma is making me add another field to Country to store the users ids… Like this:

model Country {
  id              String    @id @default(auto()) @map("_id") @db.ObjectId
  name            String    @unique
  userIds         String[]  @db.ObjectId
  users           Player[]  @relation(fields: [userIds], references: [id])
}

I dont need that data and it’s not logically needed. Is there any way to bypass that? Any workaround?

How to ignore escape characters in string.length javascript?

I have a NodeJS script that finds the longest string in a list, then appends spaces to make all other strings the same length. I have a problem, because I am using Chalk to color certain strings. The escape codes chalk produces are long, and when I get the length of 2 strings, let’s say one is let 1 = chalk.greenBright("test") which its length should be 4, but it returns 14, and we have the other variable let 2 = "lorem ipsum" which its length should be 11. When I call .length, 1 is bigger than the other therefore causing this issue: (using E as space)

lorem ipsumEEE
test

Instead of the intended result:

lorem ipsum
testEEEEEEE

find/filter an object nearest to two values already stored in an unsorted array object using two separadynamic values – JavaScript

I could not find the question related to this and was unable to search it on SO also. I am a new to SO and programming. I am trying to solve a problem where

Sample data,
enter image description here

I have two numbers, and I want to find/filter an object nearest to two values already stored in an unsorted array object as fast as i can.

let num1 = 29.213345400732432,
num2 = 76.121253431021421

I want to match num1 value in key2 and num2 value in key3 as closest as possible combined and it should match with key3: 28.6667, key4:77.2167 and then it should return the corresponding object.

Can anyone help me in this. I am unaware of programming and SO rules. So, please help me to solve this problem

Mobile menu links not working when using Googlebot user agent and prerender

I’m using the open-source discourse forum software -latest version.

Since the “app” serves googlebot a (very stripped-down) non-javascript version I decided to use prerender.io to render the pages and instead serve Googlebot an HTML version (of the JS)

It’s looking good but if you try the URL in chrome and change the user-agent (chrome dev tools) to Google smartphone you’ll notice the menu (3 dashes on top right) will not work.

Example Url-discourse

It’s also happening on the main site (which is not Discourse) – and it’s the same issue. The mobile menu doesn’t work. Example URL -main site from main site

If you change the user-agent back to default the mobile menus will work fine. Its when you use the Googlebot useragent that you’re getting the prerender.io version

Since starting to use the prerender.io service I noticed the bots overly visiting the home page and almost barely crawling the menu links. This would explain why.

My question: Is there any CSS or JS (not sure I can add custom JS to discourse) to fix this on both sites?

Running nextjs development mode with CSP and “style-src” with nonce

I’m not able to get nextjs development mode running with “style-src” CSP active. Currently i have only 2 errors left, but these impact my development flow:

enter image description here

I think this 2 errors would be the styling for error display in development mode and the refresh spinner.

is there a way to fix this (adding nonce or something). I want to have the same CSP for development as for production to not produce CSP errors after build. (ie. using inline style somewhere). If i have to use “unsafe-inline” for development i will not be notified until changes are build and deployed.

Using __webpack_nonce__ also doesn’t help.

Javascript input event listener broken?

I’m working on a unit conversion app as part of a course and I’m confused with the “input” event listener working only once. When I open the page, or I refresh the page, when I first type into my input element the function works properly and displays the initial value. Subsequent inputs properly display, but the result remains the same and sometimes even stays at 0 requiring another refresh.

Here is my code:

HTML:
<!DOCTYPE html>
<html>
    <head>
        <title>Unit Conversion Tool</title>
        <link rel="stylesheet" href="styles.css">
        <script src="index.js" defer></script>
    </head>
    <body>
        <div class="container">
            <div id="top-side">
                <h3>Metric/Imperial unit conversion</h3>
                <input id="input-el" inputmode="numeric" placeholder="Enter value here" min="0">
            </div>
            <div id="bot-side">
                <div>
                    <h4>Length (Meter/Feet)</h4>
                    <p id="lresult">
                        0 meters = 0.000 feet | 0 feet = 0.000 meters
                    </p>
                </div>
                <div>
                    <h4>Volume (Liters/Gallons)</h4>
                    <p id="vresult">
                        0 liters = 0.000 gallons | 0 gallons = 0.000 liters
                    </p>
                </div>
                <div>
                    <h4>Mass (Kilograms/Pounds</h4>
                    <p id="mresult">
                        0 kilos = 0.000 pounds | 0 pounds = 0.000 kilos
                    </p>
                </div>
            </div>
        </div>
    </body>
</html>


JAVASCRIPT:
////// HTML Elements
const inputEl = document.getElementById("input-el")
const Lresult = document.getElementById("lresult")
const Vresult = document.getElementById("vresult")
const Mresult = document.getElementById("mresult")

////// Ratios for conversion
const metricLratio = 3.28084
const metricVratio = 0.264172
const metricMratio = 2.20462
const imperialLratio = 0.3048
const imperialVratio = 4.54609
const imperialMratio = 0.453592

////// Getting conversion results first so I can use the toFixed method
let metricLresult = inputEl.value * metricLratio
let metricVresult = inputEl.value * metricVratio
let metricMresult = inputEl.value * metricMratio
let imperialLresult = inputEl.value * imperialLratio
let imperialVresult = inputEl.value * imperialVratio
let imperialMresult = inputEl.value * imperialMratio

////// Functions
inputEl.addEventListener("input", function() {
    
    Lresult.textContent = `${inputEl.value} meters = ${metricLresult.toFixed(3)} feet | ${inputEl.value} feet = ${imperialLresult.toFixed(3)} meters`

    Vresult.textContent = `${inputEl.value} liters = ${metricVresult.toFixed(3)} gallons | ${inputEl.value} gallons = ${imperialVresult.toFixed(3)} liters`

    Mresult.textContent = `${inputEl.value} kilos = ${metricMresult.toFixed(3)} pounds | ${inputEl.value} pounds = ${imperialMresult.toFixed(3)} kilos`
})

As I mentioned, subsequent inputs into the field properly update the inputEl.value and it displays okay, but the various results I wish to display remain the same.

Am I dumb or something?

Why does the browser not see the elements of my array? [duplicate]

So I’m a high school student trying to make a project, with an API integrated.
In short, i have to get the prices of bitcoin from the last 24 hours and the time when the currency was worth that amount, so that i can make a graph out of it (the y coordinates are determined by the price, the x is determined by the time). I do that with the help of this CryptoCompare api. This gives me the time and the prices.
I tried using fetch to get the json, and i managed to do that part, console.log returned it and everything went smoothly.
My only problem is, that for some reason the browser does not see the values pushed in with the function, it only sees the ones i determine before.
Please forgive me if it’s a stupid question, but i am still a beginner and i have wasted a lot of energy trying to figure it out.

This is the Html and Javascript i use, is from W3shcools

var xValues = [1, 2, 3, 4, 5, 6];
var yValues = [];

function GetData(array, parameters) {
  FillArray(parameters).then((data) => {
    for (let i = 0; i < 25; i++) {
      array.push(data[i]);
    }
  })
}

GetData(xValues, "data.Data.Data[i].time");
GetData(yValues, "(data.Data.Data[i].open + data.Data.Data[i].close)/2")
console.log(xValues);
console.log(yValues);


function FillArray(parameters) {
  var array = [];
  return fetch("https://min-api.cryptocompare.com/data/v2/histohour?fsym=BTC&tsym=USD&limit=24")
    .then((result) => {
      if (!result.ok) {
        throw Error
      }
      return result.json();
    })
    .then((data) => {
      for (let i = 0; i <= 24; i++) {
        array.push(eval(parameters));
      }
      return array;
    })
}

new Chart("myChart", {
  type: "line",
  data: {
    labels: xValues,
    datasets: [{
      fill: false,
      lineTension: 0,
      backgroundColor: "rgba(0,0,255,1.0)",
      borderColor: "rgba(0,0,255,0.1)",
      data: yValues
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: 38000,
          max: 40000
        }
      }],
    }
  }
});
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>

<body>

  <canvas id="myChart" style="width:100%;max-width:600px"></canvas>
  <script src="main.js">
  </script>

</body>

</html>

Here is the response i get:
As you can see, the the firs numbers set by me are visible, the rest aren’t.
When i log the full array, i can see the numbers, but i cant use them.
Can someone explain what I did wrong?
Maybe some other suggestions?2