Write multiple values from json file into HTML table with Javascipt

Heyy!

I have a small problem and I am still a beginner. That’s why I haven’t found a solution yet. ^^

There is a json file with multiple values. I would like to write the values from the file into an HTML table with Javascript (not php!).


Here is an example:

Json File:

{
   "628e191673ae8f7750c62fce": {
     "name": "John",
     "surname": "Smith",
     "age": "24"
   },
   "628e1fd0d27981c6250d886c": {
     "name": "Fred",
     "surname": "Bloggs",
     "age": "32"
   },
   "628e20c805f38641bdc08d7d": {
     "name": "Joe",
     "surname": "Harris",
     "age": "27"
   }
}

The table should then look like this:

Name Surname Age
John Smith 24
Fred Bloggs 32
Joe Harris 27

What is the best way for me to do this with Javascript?
Thank you in advance. 🙂

How to mock NODE_ENV in unit test using Jest

I want to set NODE_ENV in one of the unit test but it’s always set to test so my tests fails.

loggingService.ts

...

const getTransport = () => {
  if (process.env.NODE_ENV !== "production") {
    let console = new transports.Console({
      format: format.combine(format.timestamp(), format.simple()),
    });
    return console;
  }

  const file = new transports.File({
    filename: "logFile.log",
    format: format.combine(format.timestamp(), format.json()),
  });
  return file;
};

logger.add(getTransport());
const log = (level: string, message: string) => {
  logger.log(level, message);
};

export default log;

loggingService.spec.ts

     ...
    describe("production", () => {
        beforeEach(() => {
          process.env = {
            ...originalEnv,
            NODE_ENV: "production",
          };
    
          console.log("test", process.env.NODE_ENV);
          log(loglevel.INFO, "This is a test");
        });
    
        afterEach(() => {
          process.env = originalEnv;
        });
    
        it("should call log method", () => {
          expect(winston.createLogger().log).toHaveBeenCalled();
        });
    
        it("should not log to the console in production", () => {
          expect(winston.transports.Console).not.toBeCalled();
        });
    
        it("should add file transport in production", () => {
          expect(winston.transports.File).toBeCalledTimes(1);
        });
      });
...

How can I set process.env.NODE_ENV to production in my tests preferably in the beforeEach such that the if block in my service is false and the file transport is returned. I have omitted some code for the sake of brevity.

What is more performant way to request an image using Axios and proccess it (Blob vs Buffer)?

I am looking for a workaround to authenticate image requests in a RESTful app, see JWT-based authentication for tags?. I’ve come to a solution which uses Axios to grab the images via api routes (where the auth layer is already set).

I’ve tested two ways to grab a binary resource via axios, one is using a blob the second an arraybuffer, they both seemed to work fine:

Blob / FileReader, ReadAsDataUrl:

const SecuredImageAsBlob = ({ path, ...props }: Props) => {
  const [imageDataUrl, setImageDataUrl] = useState<string | ArrayBuffer | null>()
  useEffect(() => {
    axiosWithAuthHeaders
      .get(`/securedimage/${path}`, {
        responseType: "blob",
      })
      .then(response => {
        var reader = new window.FileReader()
        reader.readAsDataURL(response.data)
        reader.onload = function () {
          setImageDataUrl(reader.result)
        }
      })

    return () => {}
  }, [path])
  return imageDataUrl ? <img src={String(imageDataUrl)} {...props} /> : null
}

vs Buffer / toString("base64"):

const SecuredImageAsBuffer = ({ path, ...props }: Props) => {
  const [base64string, setBase64string] = useState<string | null>()
  useEffect(() => {
    axiosWithAuthHeaders
      .get(`/securedimage/${path}`, {
        responseType: "arraybuffer",
      })
      .then(response => {
        const buffer = Buffer.from(response.data, "binary").toString("base64")

        setBase64string(buffer)
      })

    return () => {}
  }, [path])
  return base64string ? <img src={`data:image/png;base64,${base64string}`} {...props} /> : null
}

But which one is more performant? I would say the Blob with FileReader() and readAsDataUrl, because it is reading a stream, so it can start to paint the image before it is fully loaded (which is close to the native <img /> behaviour). Buffer, on the other hand, has to be fully loaded and then converted to base64 before it can be shown as image, and I also guess it would take more memory because the size would be bigger. But I might be completely wrong, so feel free to correct me!

What do you thing? Blob / FileReader, Buffer / base64, or some other way I completely missed?

How download and after delete file JQUERY

Can I download file if I get full way to him? And then delete it?

That’s my folders

folders

My jquery in static/js/my_jquery. I need to get file from data/Expenses01.xlsx after ajax.done

$.ajax({
    type: "POST",
    url: "/create_excel/" + url,
    data: JSON.stringify(for_download),
    contentType: "application/json; charset=utf-8",
    async: false
}).done((response) => {
    console.log(response)
});

In response I get full way to file

My response

Flask code which return way, but I think that’s don’t very important

@bp.route('/create_excel/', methods=['POST', 'GET'])
def export_excel():
    filename = excel()
    print(request.json['Test'])
    return redirect(url_for('main.download_file', filename=filename))


@bp.route('/download_file/')
def download_file():
    filename = request.args['filename']
    return filename
    # return send_file(filename, mimetype='text/xlsx', as_attachment=True)

I click button then call ajax which call python function which create file, after I need to download this, return send_file/send_from_dictionary doesn’t work and I want to try download in ajax.done

There’s my project on git:
https://github.com/Danila0987654/Flask_download_files

Dropdown / close block

On this in my application there is a filter button, when clicked, the user can see a list (done using a modal window) of categories for filtering (Categories are: Method, Status code, Link, Date). Visually, the filter window looks like this:

enter image description here

However, I would like all categories (Method, Status code, Link, Date) to be collapsed and expanded. Schematically, this can be shown as follows:

enter image description here enter image description here

My code is divided into blocks (for each filter category there is a separate file).
Here I will give an example of how I built the filtering by Method.
And I will be grateful if you tell me how to change it in such a way that this category could open and close (for the rest of the categories I will do it myself)

export default function FilterMethod  () {
const [methods, setMethods] = useState([]);

const onMethodChange = (e) => {
    let selectedMethods = [...methods];

    if (e.checked)
        selectedMethods.push(e.value);
    else
        selectedMethods.splice(selectedMethods.indexOf(e.value), 1);

    setMethods(selectedMethods);
}

return (
        <div>
            <h6>Method</h6>
            <div style={{display: "flex"}}>
                <Checkbox inputId="method1" name="method" value="Connect" onChange={onMethodChange} checked={methods.indexOf('Connect') !== -1} />
                <label  htmlFor="method1">Connect</label>
            </div>

            <div style={{display: "flex"}}>
                <Checkbox inputId="method2" name="method" value="Delete" onChange={onMethodChange} checked={methods.indexOf('Delete') !== -1} />
                <label htmlFor="method2">Delete</label>
            </div>

         // Here I shortened the code, since it's just a list of methods

        </div>

)}

.css file

    input[type="checkbox"] {
    width: 50px;
    height: 18px;
    vertical-align: middle;
}

Uncaught (in promise) FirebaseError: Expected type ‘wc’, but it was: a custom Vc object

The indicated error appears on line //line29, and I am not able to find the error within the code, can someone help me?
the code is to show the information of the registered users when it is searched through the cpf;

   const app = initializeApp(firebaseConfig);
   const db = getFirestore(app);

async function GetADocument(){
var Ref =  setDoc(db, 'cpf', pesquisa.value);
const docSnap  = await getDocs(Ref);

  if(docSnap.exists(cpf = pesquisa)){
    nome.value = docSnap.data().nome;
    endereco.value = docSnap.data().endereco;
    bairro.value = docSnap.data().bairro;
    cidade.value = docSnap.data().cidade;
    uf.value = docSnap.data().uf;
    cep.value = docSnap.data().cep;
    rg.value = docSnap.data().rg;
    cpf.value = docSnap.data().cpf;
    nascimento.value = docSnap.data().nascimento;
    tel.value = docSnap.data().tel;
    cel.value = docSnap.data().cel;
    titulo.value = docSnap.data().titulo;
    zona.value = docSnap.data().zona;
    secao.value = docSnap.data().secao;
    pai.value = docSnap.data().pai;
    mae.value = docSnap.data().mae;
  }
   else{
    alert("usuário não encontrado");
   }
} //line29

btnbuscar.addEventListener("click", GetADocument);


Cant pass state to a conditional?

Working on an app where you can post your video game clips. Have two fetches for clip data that are the same thing just ordered in two different ways in the backend (default, and most comments). Trying to render the fetches conditionally. Seems to work when I change line 4 to switchFetches === true. But not when I press the button that changes switchFetches to false.

App

const [switchFetches, setSwitchFetches] = useState(true);

  useEffect(() => {
    if (switchFetches === false) {
      fetch("/most_comments")
        .then((r) => r.json())
        .then((data) => setClipData(data));
    } else {
        fetch("/clips")
        .then((r) => r.json())
        .then((data) => setClipData(data));  
    }
  }, []);

ClipList

function onChangeForFilter(e) {
    e.preventDefault();
    setSwitchFetches(false)
  }

Manage Shiny Sweetalert Size with Bootstrap

Below is code showing that the size of a sweetalert when bootstrap is used is very large. If you comment out the navbarpage() code chunk I note in the sample below the sweetalert is smaller.

I suppose I could overwrite with new .css which is fine. But, is there an alternative way to deal with that via arguments in the function itself? I don’t see an argument in the help, but there is the ... which passes to .js. I’m not savvy enough with js to know if that’s an option and if so what might that look like?

Thanks for any suggestions

library(shiny)
library(bslib)
library(shinyBS)


ui <- fluidPage(

    ### Code Chunk to comment out
    navbarPage(
        theme = bs_theme(bootswatch = "flatly", version = 4),
        title = 'Methods',
        tabPanel('One'),
    ),
    ### end BS code chunk
    
  tags$h2("Sweet Alert examples"),
  actionButton(
    inputId = "success",
    label = "Launch a success sweet alert",
    icon = icon("check")
  ),
  actionButton(
    inputId = "error",
    label = "Launch an error sweet alert",
    icon = icon("remove")
  ),
  actionButton(
    inputId = "sw_html",
    label = "Sweet alert with HTML",
    icon = icon("thumbs-up")
  )
)

server <- function(input, output, session) {

  observeEvent(input$success, {
    show_alert(
      title = "Success !!",
      text = "All in order",
      type = "success"
    )
  })

  observeEvent(input$error, {
    show_alert(
      title = "Error !!",
      text = "It's broken...",
      type = "error"
    )
  })

  observeEvent(input$sw_html, {
    show_alert(
      title = NULL,
      text = tags$span(
        tags$h3("With HTML tags",
                style = "color: steelblue;"),
        "In", tags$b("bold"), "and", tags$em("italic"),
        tags$br(),
        "and",
        tags$br(),
        "line",
        tags$br(),
        "breaks",
        tags$br(),
        "and an icon", icon("thumbs-up")
      ),
      html = TRUE
    )
  })

}
shinyApp(ui, server)

Why can I not use getElementById as a predicate to Array#map?

To map an array of stringified numbers to actual Numbers, I can simply pass the Number function:

let arr = ["0", "1", "-2.5"];

console.log(arr.map(Number));

Now I would like to use the same approach with document.getElementById to map a list of id strings to their corresponding DOM nodes:

let arr = ["a", "b"];

console.log(arr.map(document.getElementById));
<div id="a">a <span id="b">b</span></div>

which gives me

"TypeError: 'getElementById' called on an object that does not implement interface Document."

Can someone explain the error?

How to send server request to back-end relay and return API data to front-end

I am building a simple weather app. I am a front-end developer who has barely touched anything related to the back-end. In the process of building my weather app I wanted to use an API. I encountered an issue, my API key was public for anyone to see. I did some research on how to hide it and found out you need to create a back-end server relay to (I assume) take a request from the front end, use the API to generate the data on the back-end, then return that data to the front end.

Because I have very little experience with the back-end, I have attempted to do all this myself but am confused.

My goal is to have the client enter a location in the search bar of the application, for example, ‘Paris’, then send that to the back-end server (Node.js), convert ‘Paris’ to coordinates using the geocoding API, send the longitude and latitude to the weather API which will use that data to return an object of weather data for that region.

So far I have managed to:

  1. get the server to return the data I need but I do not know how to send this data to the front end.
  2. I can only use the server to generate the data if I replace the ${INSERT_LOCATION_HERE} to a location name manually because I don’t know how to send for example ‘Paris’ from the front-end to the server.

Here is a smaller version of the application with all the code:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=NTR&display=swap" rel="stylesheet">
    <title>Weather App</title>
</head>
<body>
    <section class="search-bar">
        <div class="container">
            <span class="input-container">
                <input class="input" type="text" placeholder="Enter a city">
                <button class="set">SET</button>
            </span>
        </div>
    </section>
    <section class="weather-information">
        <div class="success-container">
            <div class="inner-container">
                <div class="weather-details">
                    <header class="temperature">-°</header>
                    <p class="feels-like-temperature">Feels like: -°</p>
                    <p class="weather">Weather: -</p>
                    <p class="smaller-line-height humidity">Humidity: -%</p>
                    <p class="smaller-line-height wind-speed">Wind Speed: -m/s</p>
                </div>
            </div>
        </div>
    </section>
    <script src="script.js"></script>
</body>
</html>

CSS

/* Code to remove all element default styling */

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html {
    scroll-behavior: smooth;
    font-family: 'NTR', sans-serif;
    font-size: 20px;
}

button,
button:hover {
    background: transparent;
    box-shadow: 0px 0px 0px transparent;
    text-shadow: 0px 0px 0px transparent;
}

button {
    -webkit-tap-highlight-color: transparent;
    border: 0px solid transparent;
}

button:active,
button:focus
.submit-button,
input:focus, textarea:focus, select:focus {
    outline: none;
}
  
button:active,
.wrapper-for-each-form-section input,
.wrapper-for-each-form-section textarea,
.submit-button {
    border: none;
}

/* All Devices */

.search-bar {
    font-size: 0.75rem;
    width: 100%;
    height: 5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    top: 25px;
    letter-spacing: 1px;
}

.search-bar .container {
    height: 100%;
    width: 75%;
    border-bottom: 2px solid #d6d6d6;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.search-bar .container .input-container {
    height: 70%;
    width: 100%;
    display: flex;
    align-items: center;
}

.search-bar .container .input-container input {
    font-size: 1.5rem;
    border: none;
    width: 70%;
}

.search-bar .container .input-container button {
    width: 30%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
    color: #adadad;
    cursor: pointer;
}

.weather-information {
    height: 20rem;
    width: 100%;
    position: relative;
    top: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.weather-information .success-container {
    height: 100%;
    width: 75%;
    border-radius: 1rem;
    background: #f6f5fa;
    box-shadow: 0 10px 10px 0 rgb(0 0 0 / 16%);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 100%;
    position: absolute;
    z-index: 10;
}

.weather-information .success-container .inner-container {
    height: 85%;
    width: 80%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.weather-information .success-container .inner-container .image-container {
    display: flex;
    width: 100%;
    height: 35%;
    align-items: center;
    justify-content: center;
}

.weather-information .success-container .inner-container .image-container img {
    height: 100%;
}

.weather-information .success-container .inner-container .weather-details {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;
    width: 100%;
    height: 65%;
}

.weather-information .success-container .inner-container .weather-details header {
    font-size: 3.5rem;
    line-height: 3.5rem;
}

.weather-information .success-container .inner-container .weather-details p:nth-child(2),
.weather-information .success-container .inner-container .weather-details p:nth-child(3) {
    font-size: 1.5rem;
    line-height: 1.5rem;
    font-weight: 400;
}

.weather-information .success-container .inner-container .weather-details .smaller-line-height {
    font-size: 1rem;
    line-height: 1rem;
    font-weight: 500;
}

JavaScript (client)

const inputField = document.querySelector('.input');
const setButton = document.querySelector('.set');

// All elements for weather details when API call is successful:
const weatherDetailsContainer = document.querySelector('.success-container');
const temperature = document.querySelector('.temperature');
const feelsLiketemperature = document.querySelector('.feels-like-temperature');
const weather = document.querySelector('.weather');
const humidity = document.querySelector('.humidity');
const windSpeed = document.querySelector('.wind-speed');

setButton.addEventListener('click', () => {
    // insert code to send data to server
})

JavaScript (Server)

// These import necessary modules and set some initial variables
require("dotenv").config();
const express = require("express");
const fetch = require("node-fetch");
const rateLimit = require("express-rate-limit");
var cors = require("cors");
const app = express();
const port = 3000;
const axios = require("axios");

const limiter = rateLimit({
  windowMs: 1000, // 1 second
  max: 1, // limit each IP to 1 requests per windowMs
});

//  apply to all requests
app.use(limiter);

// Allow CORS from any origin
app.use(cors());

// Routes

app.get("/", (req, res) => res.send("Hello World!"));

app.get("/api/search", async (req, res) => {
  try {
    const coordAPI = await fetch(`https://api.openweathermap.org/geo/1.0/direct?q=${INSERT_LOCATION_HERE}limit=1&appid=${process.env.API_KEY}`);

    const coordAPIResponse = await coordAPI.json();

    const coordAPIResults = {
      lat: coordAPIResponse[0].lat,
      lon: coordAPIResponse[0].lon
    }

    const weatherDataAPI = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${coordAPIResults.lat}&lon=${coordAPIResults.lon}&appid=${process.env.API_KEY}&units=metric`)

    weatherDataAPIResponse = await weatherDataAPI.json();

    res.send({
      success: true,
      results: weatherDataAPIResponse,
    });
  } catch (err) {
    return res.status(500).json({
      success: false,
      message: err.message,
    });
  }
});

// This spins up our sever and generates logs for us to use.
// Any console.log statements you use in node for debugging will show up in your
// terminal, not in the browser console!
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

jquery sort table without plugin

Hello i’m using jquery to sort a table on click on the “th” tag, my code working well but only with numbers and words, but not with the date, is there anything wrong in the code :

<table>
  <thead>
    <tr>
      <th>head1</th>
      <th>head2</th>
      <th>head3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>b</td>
      <td>13/03/1998</td>
    </tr>
    <tr>
      <td>3</td>
      <td>a</td>
      <td>02/01/2005</td>
    </tr>
    <tr>
      <td>2</td>
      <td>c</td>
      <td>10/12/2022</td>
    </tr>
  </tbody>
</table>

and the js :

$(document).on('click', 'th', function() {
  var table = $(this).parents('table').eq(0);
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
  this.asc = !this.asc;
  if (!this.asc) {
    rows = rows.reverse();
  }
  table.children('tbody').empty().html(rows);
});

function comparer(index) {
  return function(a, b) {
    var valA = getCellValue(a, index),
      valB = getCellValue(b, index);
    return $.isNumeric(valA) && $.isNumeric(valB) ?
      valA - valB : valA.localeCompare(valB);
  };
}

function getCellValue(row, index) {
  return $(row).children('td').eq(index).text();
}

thank you in advance

Why when I send data from firebase to google sheets it is only shown in the first row of the sheet?

I’m trying send some data from firebase to google sheets. I used the method push() to insert the data into a variable and call it in “resource {values: duplicitiesWithJudicialCharges}”.

I know that have more than one value, but in my google sheet it’s apearing just one line.

From what I’ve observed, the last value erases the previous one and sticks to the first line. I would like all the values in the rows to appear in sequence.

import * as functions from 'firebase-functions'
import { google } from 'googleapis'
import { initializeApp } from 'firebase-admin/app'
const serviceAccount = require('../sheets_updater_service_account.json')
const sheets = google.sheets('v4')
import { getFirestore } from "firebase-admin/firestore"
initializeApp()
const firestore = getFirestore()


module.exports.readAndUpdateAdministrativeSheet = functions.https.onRequest(async (request, response) => {

    // =========================== AUTENTICAÇÃO FIREBASE ===================================
    const jwtClient = new google.auth.JWT({
        email: serviceAccount.client_email,
        key: serviceAccount.private_key,
        scopes: ['https://www.googleapis.com/auth/spreadsheets']
    })

    await jwtClient.authorize()


    // ================= CONEXÃO COM A PLANILHA CRIAÇÃO DE FILTROS =========================
    const { data } = await sheets.spreadsheets.values.get({
        auth: jwtClient,
        spreadsheetId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        range: `Listagem de pagamento!A2:X6`,
    })

    // ========= CRIAÇÃO DE BANCO DE DADOS DA COLEÇÃO LISTAGEM DE PAGAMENTO ================
    const generateDuplicities = data.values!.map(async row => {
        const [idade, nome, cpf, cpf_x, numeroRequerimento, arbitramentoHonorários,
            valorArbitrado, valorDeferido, valorComplementar, status, resultado, codigoBanco,
            banco, agencia, conta, dataDoRequerimento, dataRequerimento, dataStatus,
            comarca, vara, ato, assistidos, email, telefone] = row
        firestore.collection("Listagem de pagamento").doc(numeroRequerimento).set({
            idade, nome, cpf, cpf_x, numeroRequerimento, arbitramentoHonorários,
            valorArbitrado, valorDeferido, valorComplementar, status, resultado, codigoBanco,
            banco, agencia, conta, dataDoRequerimento, dataRequerimento, dataStatus, comarca, vara, ato,
            assistidos, email, telefone
        })

        const resultduplicitiesWithJudicialCharges = firestore.collection("Processos judiciais").where("documentosDosautores", "==", cpf)
        const duplicitiesWithJudicialCharges = new Array()

        resultduplicitiesWithJudicialCharges.get().then((querySnapshot) => {
            querySnapshot.forEach((parentDoc) => {
                //functions.logger.log(parentDoc.id, " => ", parentDoc.data())
                parentDoc.ref.collection("fee-arbitrations - Base de Execução").where('arbitramentoDeHonoráriosBE', '==', arbitramentoHonorários).get().then((querySnapshot) => {
                    querySnapshot.forEach(async (childDoc) => {
                        //duplicitiesWithJudicialCharges.push(`${'arbitramentoHonorários'}: ${arbitramentoHonorários}`, `${'nome'}: ${nome}`, `${'processoBE'}: ${childDoc.data().processoBE}`)
                        await duplicitiesWithJudicialCharges.push(`${arbitramentoHonorários}`, `${nome}`, `${childDoc.data().processoBE}`)
                        functions.logger.log(duplicitiesWithJudicialCharges)
                        // let res = [duplicitiesWithJudicialCharges]
                        // functions.logger.log(res)
                        const updateOptions = {
                            auth: jwtClient,
                            spreadsheetId: '1j9-R6gRj46Lxs0Zlj9LDTv37Hv-hW339Nph6dRI2W9c',
                            //range: 'grpr!A12',
                            range: '3. Duplicidades judiciais!A2:H1000',
                            valueInputOption: 'USER_ENTERED',
                            resource: { values: [duplicitiesWithJudicialCharges] },
                        }
                        await google.sheets({ version: 'v4', auth: jwtClient }).spreadsheets.values.clear({
                            range: '3. Duplicidades judiciais!A2:H1000', // SEMPRE QUE FOR QUERER DELETAR, VERIFIQUE A AS LINHAS E COLUNAS QUE POSSUEM VALOR
                            spreadsheetId: '1j9-R6gRj46Lxs0Zlj9LDTv37Hv-hW339Nph6dRI2W9c',

                            // Request body metadata
                            requestBody: {
                                // request body parameters
                                // {}
                            },
                        });
                        await google.sheets({ version: 'v4', auth: jwtClient }).spreadsheets.values.update(updateOptions)
                    })
                })
            })

        })
    })
    await Promise.all(generateDuplicities)
})

Does anyone knows where is the problem?

Infinite loop rerender react

I have faced the problem of infinite rerender after checkColor is true
I setIsCorrect to true and let the child component call handleCorrectAnswer to setIsCorrect to false after resetting the Clock Why I got an infinite loop?

This is main component
on update function I receive data from firebase and when the data in firebase match the current color that I generated I want to reset clock

import { Typography } from '@mui/material';
import React, { useEffect, useState } from 'react';
import CountdownTimer from './CountdownTimer';
import ColorBox from './ColorBox';
import app from '../utils/firebase';
import { getDatabase, ref, onValue } from 'firebase/database';

function genColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);

    return { r, g, b };
}

function checkColor(color1, color2) {
    const { r: r1, g: g1, b: b1 } = color1;
    const { r: r2, g: g2, b: b2 } = color2;
    const diffR = Math.abs(r1 - r2);
    const diffG = Math.abs(g1 - g2);
    const diffB = Math.abs(b1 - b2);
    return diffR < 25 && diffG < 25 && diffB < 25;
}

export default function Game() {
    const [isCorrect, setIsCorrect] = useState(false);
    const [colorFromUser, setColorFromUser] = useState({ r: 0, g: 0, b: 0 });
    const [gameColor, setGameColor] = useState({ r: 300, g: 300, b: 300 });
    const [timestamp, setTimestamp] = useState(0);

    if (checkColor(colorFromUser, gameColor)) {
        setIsCorrect(true);
    }

    function handleCorrectAnswer() {
        setIsCorrect(false);
        console.log('correct');
        const newColor = genColor();
        setGameColor((prevState) => {
            return { ...prevState, ...newColor };
        });
    }

    function update() {
        var userId = 'XJI27hbv5eVmvEXTaCJTQnhZ33C2';
        const dbRef = ref(getDatabase(app));

        onValue(dbRef, function(snapshot) {
            const data = snapshot.val().UsersData[userId].readings;

            const dataColor = data.data.split(' ');
            console.log(dataColor);
            setColorFromUser((prevState) => ({
                ...prevState,
                r: Number(dataColor[0]),
                g: Number(dataColor[1]),
                b: Number(dataColor[2]),
            }));
            setTimestamp(data.timestamp);
        });
    }

    useEffect(() => {
        update();
        handleCorrectAnswer();
    }, []);

    return (
        <div className="main-container">
            <div className="main">
                <div className="current-color">
                    <ColorBox
                        color={`rgb(${gameColor.r}, ${gameColor.g}, ${gameColor.b})`}
                    />
                    <CountdownTimer
                        isCorrect={isCorrect}
                        handleCorrectAnswer={handleCorrectAnswer}
                        setIsCorrect={setIsCorrect}
                    />
                </div>
            </div>
        </div>
    );
}

This is clock component that I want to reset in onComplete method

export default function CountdownTimer(props) {
    const [key, setKey] = useState(0);
    return (
        <div className="timer">
            <CountdownCircleTimer
                key={key}
                onComplete={() => {
                    console.log('done');
                    return { shouldRepeat: true, delay: 2 };
                }}
                onUpdate={(remainingTime) => {
                    if (props.isCorrect) {
                        setKey((prevKey) => prevKey + 1);
                        console.log('update');
                        props.handleCorrectAnswer();
                    }
                    console.log(remainingTime);
                }}
                size={130}
                isPlaying
                duration={60}
                colors="#C18FEE"
            >
                {({ remainingTime, color }) => (
                    <Typography sx={{ color, fontSize: 40 }}>
                        {remainingTime}
                    </Typography>
                )}
            </CountdownCircleTimer>

        </div>
    );
}

Trying send upload image to image server on button click , then return url and store to the backend. How to do it sequentially

this is the image upload code the URL only returns after the form has been submitted to the backend. Trying send upload image to an image server on button click, then return URL and store to the backend. How to do it sequentially

    const handleImgUpload = async imgb => {
 
    try {
  const images = imgb;
  let promiseArray = [];
  let imgbb = images.toString('base64');
  const details = {image: `${imgbb}`};
  let formBody = [];
  for (const property in details) {
    const encodedKey = encodeURIComponent(property);
    const encodedValue = encodeURIComponent(details[property]);
    formBody.push(encodedKey + '=' + encodedValue);
  }
  formBody = formBody.join('&');
  promiseArray.push(
    fetch(
      'https://api.imgbb.com/1/upload?key=xxxxxxxxxxxx',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        body: formBody,
      },
    ).then(r => r.json()),
  );

  Promise.all(promiseArray)
    .then(values => {
      if (values[0].success) {
        let thumb = '';
        values.map(imgs => {
          thumb = values[0].data.thumb.url;
          setImgUrl(imgs.data.url.replace(/["']/g, ''));
        });
        // setImageLoader(false);
        //YOU SEND imgURL
        // handleSubmitButton();
      } else {
        // setImageLoader(false);
        alert(
          'An error occurred while uploading image, please check your connection and try again',
        );
      }
    })
    .catch(err => {
      // setImageLoader(false);
      console.log('ERORRRRR', err);
      alert(err);
    });
} catch (e) {
  // setImageLoader(false);
  console.log('ERRRR', e);
}

};

this is the submit button code
I want to fetch the return URL first and then store it to a state then upload it to backend**

 const handleSubmitButton = async () => {


handleImgUpload(img); **handle upload function**

// Show Loader
setLoading(true);

UserApi.ElectionReport({

  imgUrl,
 
})
  .then(function (response) {
    // response handling
    setValue(response);
    console.log('res', response.data);

    if (response.data == 'successful') {
      // console.log('res', response.data)
      navigation.navigate('Home');

      alert('Sent Successfully');
      return;
    }
    setLoading(false);
    console.log('res', response.data);
  })
  .catch(function (error) {
    // error handling
    if (error.response) {
      alert(error.message);
      setLoading(false);
    }
  });

};