Rendering a new input filed for a specific task in ReactJs

I am tryin’ to build the Ecommerece admin dashboard by myself, and I am facing some challenges.
I want to add a product into the products table, but this product is having variants (for e.g. a cloths product has size and color variants). so The only way to add a variant is by adding a product menu itself.

I have a variant name input field that describes the name for the specific variant (for e.g. the color) and I have a variant type input field that describes the type of color (for e.g. red, green, yellow..etc).
I want to render the input field from the user perspective in order to maintain the perfect user experience.

so to add a variant I will have to add its name in this field:

variant name

then after writing the variant name, another input field will pop up which is the description for that variant name (one variant may have more than one type)

variant type

the problem is how to do this process of adding types for the user, in other words, how to render the input fields depending on the need of the user for variant names.

and after the user clicked the SAVE button, I want to extract the variants in a javascript object like this:

"variants": [
{
"id": "1",
"type": "color",
"name": "اللون",
"variants": [
{
"id": "11",
"name": "white",
"label": "#FFFFFFFF"
},
{
"id": "12",
"name": "black",
"label": "0xFF000000"
},
{
"id": "13",
"name": "red",
"label": "FFCC0000"
},
{
"id": "14",
"name": "blue",
"label": "2986cc"
}
]
},

I wrote this code this far.

import { Field, Form, Formik } from 'formik';
import React, { useEffect, useState } from 'react';

const VariantsTable = () => {
 

  const variantsVals = {};
  return (
    <>
      <Formik
        initialValues={{
          variantName: '',
        }}
      >
        {({ values }) => (
          <div>
            <Form>
              <div className="mb-4  content-center">
                <h5>Product details</h5>
                <Field
                  className="shadow appearance-none border rounded w-full py-2 px-3 mt-4 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                  name="variantName"
                  type="text"
                  placeholder={'Variant Name'}
                />
                {values.variantName && (
                  <Field
                    className="shadow appearance-none border rounded w-full py-2 px-3 mt-4 mr-8 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    name="variantType"
                    type="text"
                    placeholder={'Variant type'}
                  />
                )}
                {values.variantType && (
                  <Field
                    className="shadow appearance-none border rounded w-full py-2 px-3 mt-4 mr-8 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    name="variantType"
                    type="text"
                    placeholder={'variant type'}
                  />
                )}
              </div>
              <button
                className="bg-buttonsColor hover:bg-maincolor text-black font-bold py-2 px-4 rounded focus:outline-none  focus:shadow-outline"
                type="submit"
                onClick={() => {
                  variantsVals['variantName'] = values.variantName;
                  variantsVals['variantType'] = values.variantType;
                  variantsVals['id'] = 1;

                  console.log(values);
                }}
              >
                save
              </button>
            </Form>
          </div>
        )}
      </Formik>

export default VariantsTable;

I hope I find some helpful answers because I am really stuck at this point.
Thanks in advance.

Publish a site created with Gatsby using FileZilla

I have a website created with Gatsby and the hosting is Tophost. Is it possible to publish the site via FileZilla?
I have already tried but all javascript file transfers fail on FileZilla.Is this a solvable problem or is it not possible to use FileZilla to publish sites created with Gatsby?

Prevent jump to top on anchor click

I’m trying to prevent the page jump when clicking on a link.

function anchorClick() {
    e.preventDefault();
    id = window.location.hash.substring(1);
    $('.map_tabs').attr("style", "display:none");
    
    if ( $('.map_tabs#' + id).length ) {
        $('.map_tabs#' + id).attr("style", "display:block");
    } else {
        $('.page-link#contact-us').attr("style", "display:block")
        $('.page-link#contact-us h2').text(id + ' Coming Soon');
    }
}   

$(document).ready(anchorClick);
$(document).on("click", "#mybase" , anchorClick);   

I’ve tried adding e.preventDefault() but it’s not stopping the page jump.

Disable scrolling on preloader

is there a way to disable the user to scroll if the preloader is active? So to disable the body from scrolling.

It would be amazing if you could help me.

Here is my code atm:

<div id="preloader"></div>

#preloader{
    background: #000 url(images/preloader.gif) no-repeat center center ;
    background-size: 15%;
    height: 100%;
    width: 100vw;
    z-index: 100000;
    position: fixed;
}

var loader = document.getElementById("preloader");

window.addEventListener("load", function(){
    loader.style.display = "none";
})

Embedding Event Listeners in Instances of a Class – javascript

I’m trying to embed an event listener in instantiations of a class and then when a button associated with any particular instance is pressed it updates the corresponding instance’s totalWalksTaken properties on a button click. I could not get it working so instead I added a listener that compared the button’s instance-related ID with all generated instances. I’m going to use this code example for students learning javascript so for their sake and mine, I’d like to know, a) if and how embedding in the event listener in the Pet class is possible; b) if doing so is preferable to other approaches; c) any issues that might arise in doing it as it is below (provided I used unique identifiers for each instance to attach to the button id). Thanks!

https://codepen.io/olmansju/pen/jOGXxqL

    class Pet {
  constructor(name, petType, breed, weight, weightUnit, dob, owner, alive, imageURL){
    this.name = name;
    this.petType = petType; 
    this.breed = breed;
    this.weight = weight; 
    this.weightUnit = weightUnit; 
    this.dob = dob;
    this.owner = owner;
    this.alive = alive;
    this.imageURL = imageURL;
    this.totalWalksTaken = 0;
    this.dateEntered = new Date(); 
  }
  takePetForWalk(){
    this.totalWalksTaken +=1;
    console.log(`let's take ${this.name} for walk #${this.totalWalksTaken}`);
    return this;
  }
  updatePet(){
    document.getElementById(this.owner).innerHTML = `<img src=${this.imageURL} width="400"> <br>Meet <b>${this.name}</b>, a ${this.breed} who has gone on ${this.totalWalksTaken} walks!<button class="button" id=${this.name}>Take ${this.name} on a walk... </button>`;
    return this;
  }
}

const petOne = new Pet("Daisy", "dog", "shiba inu mix", 44, "lbs", "10-MAY-2018", "Justin", "alive",
                          "https://www.petguide.com/wp-content/uploads/2015/07/carolina-dog.jpg");

const petTwo = new Pet("Rhoda", "dog", "boston terrier", 21, "lbs", "10-NOV-2015", "Nick", "alive",
                          "https://www.akc.org/wp-content/uploads/2017/11/Boston-Terrier-MP.jpg");

const petThree = new Pet("Tikka", "dog", "poodle", 71, "lbs", "10-APR-2016", "Theresa", "alive",
                          "https://www.k9ofmine.com/wp-content/uploads/2018/01/types-of-poodles-2.jpg");

petOne.takePetForWalk().takePetForWalk();
petOne.takePetForWalk();

const petArray = [petOne, petTwo, petThree]; 

petArray.forEach(function(pet){
  addPetToDisplay(pet);
  console.log(pet.name);
  });
  
document.addEventListener('click', function(event){
  console.log(event.target.id);
  if (event.target.id === "submitPet"){
    buildNewPetObjectFromSubmittedForm();
    event.preventDefault();
  } else {
  petArray.forEach(function(pet){
    if (pet.name === event.target.id) {
      pet.takePetForWalk().updatePet();
    }
  })
  }
})

function buildNewPetObjectFromSubmittedForm(){
  let petName = document.forms[0].querySelector('input[name="petname"]').value;
  let petType = document.forms[0].querySelector('select[name="animalType"]').value;
  let breed = document.forms[0].querySelector('input[name="breed"]').value;
  let weight = document.forms[0].querySelector('input[name="weight"]').value;
  let units = document.forms[0].querySelector('select[name="units"]').value;
  let dob = document.forms[0].querySelector('input[name="dob"]').value;
  let owner = document.forms[0].querySelector('input[name="owner"]').value;
  let status = document.forms[0].querySelector('select[name="status"]').value;
  let imageURL = document.forms[0].querySelector('input[name="imageURL"]').value;
  let nextPet = new Pet(petName, petType, breed, weight, units, dob, owner, status, imageURL);
  addNewPetToPetArray(nextPet);
  addPetToDisplay(nextPet);
  resetPetForm(nextPet.name);
}

function addNewPetToPetArray(petObject){
  petArray.push(petObject);
  console.log("petArray length is now:", petArray.length);
}

function addPetToDisplay(newPet){
  console.log("newPet object passed pet name of:", newPet.name);
  document.getElementById("objects").innerHTML += `<div class="pets" id=${newPet.owner}><img src=${newPet.imageURL} width="400"> <br>Meet <b>${newPet.name}</b>, a ${newPet.breed} who has gone on ${newPet.totalWalksTaken} walks!<button class="button" id=${newPet.name}>Take ${newPet.name} on a walk... </button></div><br>`;
  console.log("added to display:", newPet.name);
}

function resetPetForm(addedPetName){
  document.getElementById("addPetForm").reset(); 
  updatePetIngestionStatus(addedPetName);
}

function updatePetIngestionStatus(petName){
  document.getElementById("statusUpdate").innerHTML = `*${petName} has been added below!`;
}

Using Tailwind CSS with esbuild – the process

What does it mean to use a plugin to a bundler to perform some work, I mean I have no experience with bundlers whatsoever yet and I wanted to learn about that by creating a “professional” workflow with esbuild and tailwindcss with react, typescript and all the goodies and I am stuck on connecting tailwind css to the eslint and the rest.
I know that to run tailwind css the necessary lib to make it work is postcss, I have followed the tailwind css docs which says

npm install -D tailwindcss
npx tailwindcss init

It says nothing about postcss so I assume that esbuild should be reponsible for it, I assume that is has to bedone via plugin, there are two:

https://github.com/karolis-sh/esbuild-postcss
npm i postcss esbuild-postcss -D

and

https://github.com/martonlederer/esbuild-plugin-postcss2
npm i -D esbuild-plugin-postcss2

Instalation process of the first one includes postcss and the second one does not, hovewer the second one seems to be newer and kind of “on top of” the first one.
The problem is none of them is working… this is my esbuild config:


    const { build } = require("esbuild");
    
    build({
      publicPath: "http://127.0.0.1:7000/",
      entryPoints: ["src/app.tsx", "src/app.css"],
      outdir: "public",
      // external: ["react", "react-dom"], comented out -throws error cannot use import statement outside a module
      loader: {
        ".png": "file",
        ".jpg": "file",
        ".jpeg": "file",
        ".svg": "file",
        ".gif": "file",
      },
      assetNames: "assets/[name]-[hash]", //-[hash]
      chunkNames: "chunks/[name]-[hash]",
      entryNames: "[dir]/[name]", //-[hash]
      splitting: true,
      format: "esm",
      minify: true,
      bundle: true,
      sourcemap: "external",
      // target: ["es2020", "chrome58", "firefox57", "safari11", "edge16", "node12"],
      pure: ["console.log"],
      resolveExtensions: [".tsx", ".ts", ".jsx", ".js", ".css", ".json"],
      inject: ["./process-shim.js", "./react-shim.js"],
      // watch: {
      //   onRebuild(error, result) {
      //     if (error) console.error("watch build failed:", error);
      //     else console.log("watch build succeeded:", result);
      //   },
      // },
    }).catch((error) => {
      console.error(`Build error: ${error}`);
      process.exit(1);
    });

and this is my package.json file:


    {
      "name": "real-world-app",
      "version": "1.0.0",
      "description": "this is not a package",
      "main": "src/app.js",
      "scripts": {
        "build": "node ./esbuild.config.js",
        "watch": "npm run build -- --watch",
        "start": "npm run css && node ./esbuild.serve.js -w ",
        "lint": "eslint --fix --debug --cache",
        "test": "jest",
        "css": "npx tailwindcss -i ./src/app.css -o ./public/app.css"
      },
      "keywords": [
        "conduit"
      ],
      "license": "ISC",
      "repository": {
        "type": "git",
        "url": "https://github.com/dziekonskik/real-world-app"
      },
      "dependencies": {
        "esbuild": "^0.14.2",
        "esbuild-darwin-64": "^0.14.2",
        "react": "^17.0.2",
        "react-dom": "^17.0.2"
      },
      "devDependencies": {
        "@babel/preset-env": "^7.16.5",
        "@babel/preset-react": "^7.16.5",
        "@babel/preset-typescript": "^7.16.5",
        "@testing-library/dom": "^8.11.1",
        "@testing-library/jest-dom": "^5.16.1",
        "@testing-library/react": "^12.1.2",
        "@testing-library/user-event": "^13.5.0",
        "@types/jest": "^27.0.3",
        "@types/react": "^17.0.37",
        "@types/react-dom": "^17.0.11",
        "@typescript-eslint/eslint-plugin": "^5.6.0",
        "@typescript-eslint/parser": "^5.6.0",
        "esbuild-serve": "^1.0.1",
        "eslint": "^8.4.1",
        "eslint-plugin-jest": "^25.3.0",
        "eslint-plugin-react": "^7.27.1",
        "eslint-plugin-testing-library": "^5.0.1",
        "jest": "^27.4.4",
        "ts-jest": "^27.1.2",
        "typescript": "^4.5.4"
      }
    }

As a development server i use package esbuild serve. When I run the css command i get kind of an output, hovewer it is more like css reset that the whole tailwind, and when I run npm run build as an output I get the copied directives

@tailwind base;
@tailwind components;
@tailwind utilities;

about which also my VScode is complaining with warnings I do not know what to do with them.
Would you please explain how should I understand this entire process of bundling and using plugins on this example? What am i missing?
Thanks a lot

How to blink specific row for 2 times using Vue.js & Vuetify?

After creating a record, I showed an alert green message if API returns 200 OK, and red otherwise. Right now, it is working perfectly I used Vuex + Vuetify Snackbar.

this.notifcationData = {
    color: 'green',
    text: campaign.name + ' - deleted successfully !'
}



<v-snackbar timeout="1000" v-model="notification" absolute top :color="notifcationData.color" outlined right>
    <strong>
        {{ notifcationData.text }}
    </strong>
</v-snackbar>

enter image description here

I want to improve the UX one more notch. I would like to blink that specific row for 1 sec (2 times).

I know I have access to the campaign.name

How do I achieve that in Vue.js ?

How can I make a Horizontal scrolling nav bar that also works with mobile

So I have a website about the NBA and the problem is there is 30 teams in the NBA. When I make a nav bar it takes up half the page because there is 30 teams lol. How can I make a nav bar that scrolls horizontally to the right so just more teams keep popping up as your scroll. I also need it to work for mobile version so I need this nav bar to be responsive. Thank you very much.

How to manage multiple max and min numbers of an array in JavaScript

What is the best way to approach this?

I have an array:

tiers = [
    {800, 1000},
    {600, 799},
    {400, 599},
    {0, 399}
]

These represent the min and max value for each tier.
The user can then change any of the min/max values except 1000 and 0 respectively.

  • The values for each tier should respect the corresponding values.
    For example, if I change 799 to 798, then in the above tier 800 will change to 799.

  • The values cannot overlap. Example: if 799 (max) is reduced to 600(min), it should stop at 601, then the above tier should be 602. It would be nice if each corresponding tier changed, but it is not necessary a simple return false would work.

I have tried a few different things, but I am unable to encompass all the variations. Seems like a simple little puzzle, but I can’t figure it out.

Privacy prompt on Safari because of browser geolocation

if ( navigator.userAgent.match(/Android/i)
  || navigator.userAgent.match(/webOS/i)
  || navigator.userAgent.match(/iPhone/i)
  || navigator.userAgent.match(/iPad/i)
  || navigator.userAgent.match(/iPod/i)
  || navigator.userAgent.match(/BlackBerry/i)
  ) {

  var success = function(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    if (!navigator.cookieEnabled || getCookie('geolocation')) {
      return false;
    }

    var data = { action: 'geolocate', latitude: latitude, longitude:longitude };
    $.ajax({
        type: 'POST',
        url: '/wp-admin/admin-ajax.php',
        data: data,
        dataType: 'text',
        beforeSend: function (request) {
          request.withCredentials = false;
        }
    });
  }
  

  if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success, null);
  }
} 

I have this code for browser geolocation, and lately on iOS I keep getting prompted for allowing the tracking of my location on Safari. On other devices like Android, this doesn’t happen. I have it set up as a GTAG and it triggers on every page. Now, I think it is because the backend ajax creates a cookie, but the cookie isn’t set fast enough for the next page load to not trigger the privacy notification, but I was wondering if there’s another way to prevent this notification from showing on Safari.

how do I use “this” on an component function in react?

I need to call this.getFact from the Animal component, but using this raises TypeError: this is undefined

import './App.css';
import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fact: '',
    }
  }

  getFact(endpoint) {
    fetch(endpoint)
      .then(response => response.json())
      .then(data => {
        this.setState({
          fact: data.text,
        });
      })
  }

  Animal(props) {
    return (
      <div>
        <h1>{props.name}</h1>
        <button onClick={() => this.getFact(props.endpoint)}>get a {props.name.toLowerCase()} fact</button>
      </div>
    )
  }

  render() {
    return (
      <div className="App">
        <div>
          <p>{this.state.fact}</p>
        </div>
        <div className="animals">
          <this.Animal name="Dog" endpoint="https://some-random-api.ml/facts/dog" />
          <this.Animal name="Cat" endpoint="https://some-random-api.ml/facts/dog" />
          <this.Animal name="Bird" endpoint="https://some-random-api.ml/facts/dog" />
          <this.Animal name="Otter" endpoint="https://some-random-api.ml/facts/dog" />
        </div>
      </div>
    );
  }
}

export default App;

Need help avoiding the forced reflow

Hallo i have this problem with my code that it is creating a forced reflow when the clock hits 24:00. The code is supposed to send a ajax request to a esp32 at start to retrieve som temperture reading and the send a request for a single value each minute, but it crashes at 24:00.

I am not that experienced in web applications so i need help fixing it. My code can be seen here.

<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://code.highcharts.com/highcharts.js"></script>
  <style>
    h2 {
      font-family: Arial;
      font-size: 2.5rem;
      text-align: center;

    }
  </style>
</head>
<p id="demo"></p>
<body>
  <h2>DASH BOARD</h2>
  <div id="chart-temperature" class="container"></div>
  <p id="demo"></p>
  <p id="demo2"></p>
</body>
<script>
var Json;
var d = new Date();
var h = d.getHours();
var c = d.getMinutes();
var chartT = new Highcharts.Chart({
  chart:{
    renderTo : 'chart-temperature',
    type: 'line',
    zoomType: 'x',
    panning: true,
    panKey: 'shift'
  },
  tooltip: {
  dateTimeLabelFormats: {
    millisecond: "%A, %b %e, %H:%M"
  }
},
  title: { text: 'temperature' },
  series: [{
    name: 'TEMP1',
    showInLegend: true,
    connectNulls: true,
    data: [],
    color: '#FF0000'
  }, {
     name: 'TEMP2',
     connectNulls: true,
    data:[],
    color: '#4572A7'
  },
  {
     name: 'TEMP3',
     connectNulls: true,
    data:[],
    color: '#000000'
  },
  {
     name: 'TEMP4',
     connectNulls: true,
    data:[],
    color: '#0000FF'
  },
  {
     name: 'TEMP5',
     connectNulls: true,
    data:[],
    color: '#6600FF'
  }],

  plotOptions: {
    line: { animation: false,
      dataLabels: { enabled: true }

    },
  },
  xAxis: { type: 'datetime',
    dateTimeLabelFormats: { second: '%H:%M:%S' },
    min: Date.UTC(0,0,0,h,c-120,0), tickInterval: 30*60*1000, max: Date.UTC(0,0,0,h,c,0)
  },
  yAxis: {
    title: { text: 'Temperature (Celsius)' },
    //title: { text: 'Temperature (Fahrenheit)' }
  },
  credits: { enabled: false }
});
Highcharts.setOptions({
    time: {
        useUTC: true
    }
});
function loadall(){
  var z
  var m;
  var tid;
  var y1;
  var y;
  var just;
    var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      if(chartT.series[0].data.length == 0){
        y1 = this.responseText;
        y = JSON.parse(y1);
        just = y.temp1.length;
      for (let i = 0; i < just; i++) {
         tid = Date.UTC(0,0,0,h,(c-i),0);
         z = just-i-1;
            chartT.series[0].addPoint([tid, y.temp1[z]], true, false, false);
            chartT.series[1].addPoint([tid, y.temp2[z]], true, false, false);
            chartT.series[2].addPoint([tid, y.temp3[z]], true, false, false);
            chartT.series[3].addPoint([tid, y.temp4[z]], true, false, false);
            chartT.series[4].addPoint([tid, y.temp5[z]], true, false, false);
          }
           }
            }
             }
    xhttp.open("POST", "TEMP", true);
    xhttp.send();
  }
  function Load(serie,sensor,tid){
    var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        var y = parseFloat(this.responseText);
    if (this.readyState == 4 && this.status == 200) {
            if(chartT.series[0].data.length > 120) {
        chartT.series[serie].addPoint([tid, y], true, false, false);
      } else {
        chartT.series[serie].addPoint([tid, y], true, true, false);
      }
          }
           }
    xhttp.open("GET", sensor, false);
    xhttp.send();
  }
loadall();
  setInterval(function(){
    d = new Date();
    h = d.getHours();
    c = d.getMinutes();
    chartT.xAxis[0].update({
        max: Date.UTC(0,0,0,h,c,0),
        min: Date.UTC(0,0,0,h,c-120,0)
    });
    Load(0,"temp1",Date.UTC(0,0,0,h,c,0));
    Load(1,"temp2",Date.UTC(0,0,0,h,c,0));
    Load(2,"temp3",Date.UTC(0,0,0,h,c,0));
    Load(3,"temp4",Date.UTC(0,0,0,h,c,0));
    Load(4,"temp5",Date.UTC(0,0,0,h,c,0));
  }, 60000);

</script>
</html>

The things that is happening in the consol can be seen here.

(index):119 XHR finished loading: POST "http://192.168.1.111/TEMP".
loadall @ (index):119
(anonymous) @ (index):136
(index):100 [Violation] 'readystatechange' handler took 8260ms
[Violation] Forced reflow while executing JavaScript took 1564ms
favicon.ico:1 GET http://192.168.1.111/favicon.ico 500 (Internal Server Error)
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
[Violation] 'setInterval' handler took <N>ms
(index):123 [Violation] 'setInterval' handler took 196ms
(index):123 [Violation] 'setInterval' handler took 106ms
(index):123 [Violation] 'setInterval' handler took 131ms
(index):123 [Violation] 'setInterval' handler took 125ms
(index):123 [Violation] 'setInterval' handler took 138ms
(index):137 [Violation] 'setInterval' handler took 1445ms
(index):123 [Violation] 'setInterval' handler took 111ms
(index):123 [Violation] 'setInterval' handler took 91ms
(index):123 [Violation] 'setInterval' handler took 96ms
(index):123 [Violation] 'setInterval' handler took 82ms
(index):123 [Violation] 'setInterval' handler took 96ms
(index):137 [Violation] 'setInterval' handler took 1376ms
(index):123 [Violation] 'setInterval' handler took 174ms
(index):123 [Violation] 'setInterval' handler took 151ms
(index):123 [Violation] 'setInterval' handler took 87ms
(index):123 [Violation] 'setInterval' handler took 145ms
(index):123 [Violation] 'setInterval' handler took 54ms
(index):137 [Violation] 'setInterval' handler took 1607ms
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
XHR finished loading: GET "<URL>".
[Violation] Forced reflow while executing JavaScript took 86ms

Issue trying to make an API Post in React Native

I am trying to do an API Post with some information that I am saving in variables, using different functions.
To get this data before making the POST method, I have to get a Bearer Token also with an API Post, but this request takes some little time.
I have a button on my screen that I want to use it to make the final API Post, save the info in Firebase and navigate to the next screen, but for that I need my Token bearer. I don’t know how to make my second API Post to get in time the bearer token in a variable, so I can made in a correct way my API Post final. Maybe is a easier way to set my bearer token to Axios, because I have to do several API Post in different screen and this token has an expire time.
The problem with my code is that after I touch the botton 3 times, it works, and I can navigate to my next screen (the name of the next screen is in the response of the API Post final).
First time I touch the button it appears the next error:
The action ‘NAVIGATE’ with payload {“name”:””} was not handled by any navigator.

You need to pass the name of the screen to navigate to.

But after this, mi bearer token is set correctly and appears in mi console.

The second time I touch my button, the functions that I made to make this call async, are correctly execute sending this message to the console:
Promise Resolved:
LOG Next step –> API POST
LOG Data saved in DB and API Request completed

After this the bearer token appears again in my console, following with the response of the final API Post, but it doesn’t navigate correctly.

The third time I touch the button it works correctly, sending the same info to the console that in the last step, but navigating to next screen.

I attached my code, changing some info for security.

import React, {useState, useContext, useEffect} from 'react';
import axios from 'axios';
import firestore from '@react-native-firebase/firestore';
import FormInput from '../../components/FormInput';
import { 
    View, 
    Text, 
    ScrollView, 
    FlatList, 
    TouchableOpacity, 
    Image,
    TextInput,
    Button
} from 'react-native';
import { COLORS, SIZES, FONTS, icons, image, functions, dummyData} from "../../constants"
import FormButton from '../../components/FormButton';
import { AuthContext } from '../../navigation/AuthProvider';

 // Variables to set new values
let user_token = '';
let nextStep = '';
//let username = '';

const myFirstScreen = ( {navigation} ) => {

    const { user} = useContext(AuthContext); 
    const [username, setUsername] = useState();
   // const [user_token, setUserToken] = useState();
   //  const [nextStep, setNextStep] = useState();
    const [isLoading, setIsLoading] = useState(false);
  

 // Save User name and id in Firebase database
    const submitUserdata = async () => {
        firestore()
            .collection('UserData')
            .doc(user.uid)
            .set ({
                userId: user.uid,
                userName: username,  
            })
            .then ( () => {
                console.log('User NAME and ID Added!')
            })
            .catch((error) => {
                console.log(error)
            });
    };


    function getCredentialsInfo() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve (getBearerToken())
            }, 10)
        })
    }

    async function setUserDataDB() {
        const result = await getCredentialsInfo()
        console.log('Promise Resolved: ')
        console.log('Next step --> API POST')
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve (onSubmitFormHandler() )
            }, 10)
        })
    };

    async function callForButton() {
        const result = await setUserDataDB()
        console.log('Data saved in DB and API Request completed')
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve ( navigation.navigate(nextStep) )
            }, 10)
        })
    }

    //getCredentiales, client_id and client_secret wont be here in the future

const getBearerToken = () => {

    const client_id =  "xxxxxx";
    const client_secret =  "xxxxxxx";
    

    axios.post('myurl.com', 
    {client_id,
    client_secret})   
    .then(response => {
       console.log(response.data);
    //setUserToken(response.data.access_token);
        user_token = response.data.access_token;
     })   
    .catch((error) => {
       console.log('error en Get Token ' + error);   
    });
    
    }


     // API Rest POST - User Name Validation -  
    const onSubmitFormHandler =  (event) => {

        axios.post("myurl.com/2", 
        {username},
        {headers: {'Authorization': `Bearer ${user_token}`}})    
        .then(response => {
         // If request es 200
         console.log(response.data);
        // setNextStep(response.data.next_action);
         nextStep = response.data.next_action;
         console.log(response.data.next_action)})
        .catch((error) => {
         console.log('Error en POST ' + error);
         //setNextStep('myFirstScreen')
         nextStep = 'actual screen';
      });
    };

    return (
        <View style={{
            alignItems: 'center',
            height: "100%",
            width: "100%",
            backgroundColor: COLORS.white
        }}>
            <View style={{
                // marginTop: "10%",
                // marginBottom: "10%",
                alignItems: 'center'
            }}>
                 <View style={{
                    backgroundColor: COLORS.lightGray1,
                    borderRadius: 40,
                    height: "85%",
                    width: "100%"
        }}>
            <View style={{
                width: "100%",
                paddingHorizontal: "8%",
                paddingVertical: "10%"
            }}>

            {/* Username */}
            <FormInput
                labelValue = {username}
                //onChangeText = {(userName) => username = userName}
                onChangeText = {(userName) => setUsername (userName)}
                placeholderText = "Username"
                autoCapitalize = "none"
                autoCorrect = {false}
            />

            </View>
            </View> 
            <FormButton buttonTitle='Save User Name' 
            
            //onPressIn ={() => {getToken()}}
            onPress={() => {
                // submitUserdata()
                // onSubmitFormHandler()
                // navigation.navigate(nextStep)
                callForButton()  
            }}       
            disabled={isLoading}/>
            </View>
            </View>
    );
}
export default myFirstScreen;

Thank you in advance! Any suggestions are welcome. I dont know if the useState() hook is making something work in a bad way.

Recreating flappybird in P5JS. (original i know). I dont know exactly how i am supposed to spawn the “pipes” at different heights

So i have a small assignment of recreating flappy bird, where the player has 10 lives and loses one every time they touch the “pipes”. Im essentially done but would like to make it so the openings of the pipes are located at different y values sort of like this. How would i exactly go about doing that.
Github:
https://github.com/Albatrossdk/Programmering-B/tree/main/113-P5-BOLD

Github pages:
https://albatrossdk.github.io/Programmering-B/113-P5-BOLD/

How to apply a gradient to the color instead of a solid color value

I came across this snippet in CSS tricks

So trying to change the green color to the gradient value. But that value is not applying.
I tried both fill property with gradient color but that too has no success.

Here is the code:

const FULL_DASH_ARRAY = 283;

const TIME_LIMIT = 20;
let timePassed = 0;
let timeLeft = TIME_LIMIT;
let timerInterval = null;

document.getElementById("app").innerHTML = `
<div class="base-timer">
  <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
    <g class="base-timer__circle">
      <circle class="base-timer__path-elapsed" cx="50" cy="50" r="45"></circle>
      <path
        id="base-timer-path-remaining"
        stroke-dasharray="283"
        class="base-timer__path-remaining green"
        d="
          M 50, 50
          m -45, 0
          a 45,45 0 1,0 90,0
          a 45,45 0 1,0 -90,0
        "
      ></path>
    </g>
  </svg>
  <span id="base-timer-label" class="base-timer__label">${formatTime(
    timeLeft
  )}</span>
</div>
`;

startTimer();

function onTimesUp() {
  clearInterval(timerInterval);
}

function startTimer() {
  timerInterval = setInterval(() => {
    timePassed = timePassed += 1;
    timeLeft = TIME_LIMIT - timePassed;
    document.getElementById("base-timer-label").innerHTML = formatTime(
      timeLeft
    );
    setCircleDasharray();

    if (timeLeft === 0) {
      onTimesUp();
    }
  }, 1000);
}

function formatTime(time) {
  const minutes = Math.floor(time / 60);
  let seconds = time % 60;

  if (seconds < 10) {
    seconds = `0${seconds}`;
  }

  return `${minutes}:${seconds}`;
}



function calculateTimeFraction() {
  const rawTimeFraction = timeLeft / TIME_LIMIT;
  return rawTimeFraction - (1 / TIME_LIMIT) * (1 - rawTimeFraction);
}

function setCircleDasharray() {
  const circleDasharray = `${(
    calculateTimeFraction() * FULL_DASH_ARRAY
  ).toFixed(0)} 283`;
  document
    .getElementById("base-timer-path-remaining")
    .setAttribute("stroke-dasharray", circleDasharray);
}
body {
  font-family: sans-serif;
  display: grid;
  height: 100vh;
  place-items: center;
}

.base-timer {
  position: relative;
  width: 300px;
  height: 300px;
}

.base-timer__svg {
  transform: scaleX(-1);
}

.base-timer__circle {
  fill: none;
  stroke: none;
}

.base-timer__path-elapsed {
  stroke-width: 7px;
  stroke: grey;
}

.base-timer__path-remaining {
  stroke-width: 7px;
  stroke-linecap: round;
  transform: rotate(90deg);
  transform-origin: center;
  transition: 1s linear all;
  fill-rule: nonzero;
  stroke: currentColor;
}

.base-timer__path-remaining.green {
  color: rgb(65, 184, 131);
}

.base-timer__label {
  position: absolute;
  width: 300px;
  height: 300px;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
}
<div id="app"></div>

Is it possible to use gradient only in the progress bar(green) of SVG or is gradient is not allowed in SVG.