React.js: Fetching Data from API with Bearer Token

I am building a React.js SPA, that receives data from an API with Bearer Token Authentication (so a fetch request for authentication has to be done first and the given token can be used temporarily to access the data until the auth session ends)

I can authorize and print the object to the console, but the object is not saved into the variable objectOutput in order to be accessed by the components below.

My thought is, that the asynchronous fetching causes this, and the components are rendered before the fetch() reslut has arrived. But I wonder how this could be fixed, so I can store it in the variable and the components can access the data as their props.

Thanks in advance 🙂

import Header from "./components/Header";
import Cardsection from "./components/Cardsection";
import Flagsection from "./components/Flagsection";
import Footer from "./components/Footer";
import MapChart from "./components/MapChart";
import { useEffect } from "react";

let api_url = "https://api-url:3000";
let batch_id = "XXX";
let api_token = "";
let objectOutput = "";

function App() {
  useEffect(() => {

    const authorize = async () => {
      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");

      var raw = JSON.stringify({
        username: "username",
        password: "password",
      });

      var requestOptions = {
        method: "POST",
        headers: myHeaders,
        body: raw,
        redirect: "follow"
      };

      const res = await fetch(api_url + "/auth", requestOptions).catch(console.log("error"));
      const data = await res.json();
      api_token = data.token;
      console.log("Successful Authorization. Token: " + api_token);

      const getObject = async () => {
        var myHeaders = new Headers();
        myHeaders.append("Authorization", "Bearer " + api_token);

        var requestOptions = {
          method: "GET",
          headers: myHeaders,
          redirect: "follow"
        };

        const res = await fetch(api_url + "/get?function=readObject&args=" + batch_id, requestOptions).catch(console.log("error"));
        const data = await res.json();

        objectOutput = data;
        console.log(data);

      
      };
      getObject()

    };

    authorize();

  }, []);

  return (
    <div className="App">
      <Header
        title="Lorem Ipsum"
        description="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
      />
      <Flagsection hasFlag={objectOutput.alarmFlag} />
      <Cardsection sort={""} treatment={""} plantheight={""} harvesttime={""} />
      <MapChart/>
      <Footer />
    </div>
  );
}

export default App;```

Trouble promisifying setInterval to do an action continuously for a given period and then allow a new asynchronous function to begin

Having trouble promisifying setInterval. The .then() is occurring immediately despite the embedEditor function returning a promise only if time === 0. How do I make a function in setInterval return a promise once a time period has completed?

const interval = setInterval(embedEditor, 1000);
async function embedEditor() {
    time -= 1;
    //inner function....//
    if (time === 0) {
        clearInterval(interval);
        return new Promise((res) => { res("time period over"); });
    }
}
await interaction.reply({ embeds: [exampleEmbed], components: [row, row2] });
await interval
    .then(/*action*/);

Vue3 LocalStorage set after component render

I have a nav bar that loads user data, all of this happens after a user successfully logs into the application. The problem is, localStorage must be setting slightly after I load the nav bar. If I wrap it in a setTimeout() everything works but I would rather my variables be reactive in nature since they can change based on user activity.

Toolbar.vue

<template>
  <!--begin::Toolbar wrapper-->
  <div class="d-flex align-items-stretch flex-shrink-0">
    <h2>check for value</h2>
    <div v-if="activeAccountId">{{activeAccountId}}</div>
  </div>
  <!--end::Toolbar wrapper-->
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";

export default defineComponent({
  name: "topbar",
  data() {
    let activeAccountId = ref(JSON.parse(localStorage.getItem('activeAccountId') || '{}')).value;

    return {
      activeAccountId
    }
  }
});
</script>

I’ve tried using watchers, and using setup() verses data(), but nothing seems to work properly. As I mentioned, setTimeout() does work but I’d rather avoid manually triggering a timeout and let vue handle things how it wants to.

Here’s a simple example, I can’t setup a dummy code side since it won’t have the localStorage item set.

iam getting buffer and hex codes

var fs = require('fs');

fs.readFile('TestFile.txt', function (err, data) {
                    if (err) throw err;

    console.log(data);
});

//TestFile.txt This is test file to test fs module of Node.js

  1. Iam getting buffer and hex codes in place of console data
  2. <Buffer 54 68 69 73 20 69 73 20 74 65 73 74 20 66 69 6c 65 20 74 6f 20 74 65 73 74 20 66 73 20 6d 6f 64 75 6c 65 20 6f 66 20 4e 6f 64 65 2e 6a 73>

D3 JS – how to append a string inside elements.enter()?

I have this json file:

[
    {
        "id": "1",
        "name": "Hello world",
        "shape": "rect",
        "fill": "pink"
    }
]

And I also have this javascript file:

const svg = d3.select('svg')
var stringToHTML = function (str) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(str, 'text/html');
    return doc.body;
};
d3.json("tree.json").then(data => {
    const elements = svg.selectAll('*')
        .data(data);
    elements.enter()
        .append("rect")
            .attr("x", 20)
            .attr("y", 20)
            .attr("width", 100)
            .attr("height", 100)
            .attr("fill", d => d.fill)
    elements.enter()
        .append('text')
            .attr("x", 50)
            .attr("y", 60)
            .html("text", d => {d.name})
    
})

and this html file:

<!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">
    <title>Document</title>
</head>

<body>
    <svg width="600" height="600">
    </svg>

    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script src="index.js"></script>
</body>

</html>

Now the output is:

1st output

but when I switch "rect" with d => d.shape it doesn’t behave as before.

d3.json("tree.json").then(data => {
    const elements = svg.selectAll('*')
        .data(data);
    elements.enter()
        .append(d => d.)
            .attr("x", 20)
            .attr("y", 20)
            .attr("width", 100)
            .attr("height", 100)
            .attr("fill", d => d.fill)

But how is it different than the previous one? I also tried outputting d.shape, and it prints string. Then how can I make something that will create a shape according to the shape data?

Read file from XHR post request

I have an XHR post request as follows:

    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    const inpFile = document.getElementById("inpFile");

    var numFiles = inpFile.files.length;
    for (let i = 0; i < numFiles; i++) {
        formData.append("file", inpFile.files[i]);
    }

    xhr.open("POST", "https://submit.com.xz");
    xhr.send(formData);

Once I post the form data to the server, or in this instance, a cloud function, I’d like to decode the file, store it as inpFile and send another very similar XMLHttpRequest.

Would appreciate some advice on how to do this as I’m having difficulty extracting the file from the original XMLHttpRequest.

How to persist a Firebase web SDK login in custom storage library?

I have an Electron app, And in Electron’s rendering process it has
it’s storage like (localStorage, sessionStorage), I also have a simple extension to install when the my Electron application starts.

The problem I have to log in again in this extension in order to meet my needs, because I assume that Electron has a different (localStorage, sessionStorage) for the installed extensions.

Is there a way to make Firebase persist the login state in custom storage like electron-store? So I don’t need to log in again in the extension rendering process as well.

Typescript: Generic function should not return union of all types

I managed to type the object currentProps so TS knows which properties it haves AND each property has its individual type (not an union of all possible types).

So far so good.

Then I have this generic function overrideForIndex which gets one of the possible properties, and should return its value. But it can’t be assigned, because its return-type is a union, and not the specific type.

Now I could just cast it as any and call it a day, but I am curious if there is a way to handle this properly without casting to any.

Here is the “simplified” example:
(open in TS playground)

export type MyProps = {
  id?: number;
  title?: string;
}

const props: Record<keyof MyProps, any> = {
  id: 123,
  title: 'foo'
}

export const propNames = Object.keys(props) as Array<keyof MyProps>;

const data: Record<number, MyProps> = { 0: { id: 123, title: 'foo' }};

const buildLatestProps = (): { [P in keyof Required<MyProps>]: MyProps[P] } => {
  const getLatest = <T extends keyof MyProps>(propName: T) => data[0][propName];
  return Object.fromEntries(propNames.map(n => [n, getLatest(n)])) as any;
};

const currentProps = buildLatestProps();

const overrideForIndex = <T extends keyof MyProps>(propName: T, index: number): MyProps[T] =>
  data[index][propName];

propNames.forEach(n => (currentProps[n] = overrideForIndex(n, 0) /* as any */)); // ERR: Type 'string | number | undefined' is not assignable to type 'undefined'.

Display images from google drive link

hello I am making a project in React js in which I want to get the help that how can I achieve this task
In a dashboard, there is an option in which users paste their public google drive folder link and in this folder, there will be images
once the user paste their google drive link and click on the upload button all images from the folder will start display on dashboard

Increase and decrease the number using addEventListener keydown in React

I wrote a program that adds or subtracts a unit to count by pressing the up and down keys on the keyboard.
The problem is that the program does not work properly. When you press the key, look at the console, which runs several times, while each time you press the key, it only has to run once.
This is a problem that crashes after pressing the up or down buttons a few times, please help

import React, { useState } from "react";

export default function Example() {
  const [count, setCount] = useState(0);

  document.addEventListener("keydown", function (e) {
    switch (e.keyCode) {
      case 38:
        setCount(count + 1);
        console.log(count);
        break;
      case 40:
        setCount(count - 1);
        console.log(count);
        break;
    }
  });
  return (
    <div>
      <p>You clicked {count} times</p>
    </div>
  );
}

JavaScript setattribute after searchParams in URL

I do some options in this code.

first, get Attribute by getAttribute() this called ‘src’.

second, use 'searchParams.set()' to change resize in this URL.

third, setAttribute() to accepte last change of size.

this is my code:

<!DOCTYPE html>
<html>
    <head>
        <style>
          #twoposition {
              position: absolute;
              width: 100%;
              height: 100%;
              left: 0px;
              top: 50px;
          }
        </style>
        
        <title></title>
    </head>
    <body>
        <select onchange="check()" id="selectbox" name="">
            <option hidden value="empty"></option>
            <option value="firstSize">1</option>
            <option value="secondSize">2</option>
        </select>
        <div id="two">
            <div id="de6854">
                <div style="width: 100%;height: 100%">
                    <iframe id="4526d" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100">
                    </iframe>
                    <iframe id="3ad34" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100">
                    </iframe>
                </div>
            </div>
        </div>

    </body>
        <script>
            function check() {
                var val = document.getElementById("selectbox").value
                var pic =  document.querySelectorAll("#two iframe")
                var aa = pic.getAttribute('src')
                
                var url = new URL(aa);
                var url0 = url.searchParams.set('resize', '500,300');
                var url2 = url.searchParams.set('resize', '400,200');
                
                if(val === "firstSize") {
                    pic.setAttribute('src',url0)
                } 
                else if(val === "secondSize") {
                    pic.setAttribute('src',url2)
                }
            }
        </script>
</html>

I try this code but not working.

I want if I select the check 1 has value firstSize change the attribute to url0.

and if I select the check 2 has value secondSize change the attribute to url2.

HTML get checkbox element

I’m making a checkbox where every user presses the checkbox, then the contents of the checkbox will appear in the list section :
as shown here

the problem is the checkbox that works is only the first checkbox in the list and every time the user presses the checkbox, the content that shown in the list is only the last data in the database.
here is my code :

@foreach($users as $user)
                                    <ol class="list-group" >
                                            <div class="card">
                                            <li class="list-group-item group-containers">
                                                <div class="row">
                                                <input onclick="checkBox(this)" class="form-check-input" type="checkbox" id="approver">
                                                    <div class="col-1 c-avatar mr-3">
                                                        <img class="c-avatar-img" src="{{ url('/assets/img/avatars/3.png') }}">
                                                    </div>
                                                    <div class="col-8">
                                                    <div class="">{{ $user->name }}</div>
                                                    <label for="" class="text-secondary">{{ $user->email }}</label>
                                                    </div>
                                                </div>
                                                </input>
                                            </li>
                                        </div>
                                    </ol>
                                    @endforeach

Here is the code that shows the selected checkbox content :

<ol id="list" class="list-group" style="display:none">
                            <div class="card">
                                <li class="list-group-item">
                                    <div class="row">
                                        <div class="col-1 c-avatar mr-3">
                                            <img class="c-avatar-img" src="{{ url('/assets/img/avatars/3.png') }}">
                                        </div>
                                        <div class="col-8">
                                        <div class="">{{ $user->name }}</div>
                                    </div>
                                </li>
                                </div>
                            </ol>

and here is the javascript code :

<script>
    
function checkBox(){
    // console.log(e)
    var cb = document.getElementById("approver");
    var text = document.getElementById("list");
    if(cb.checked==true){
        text.style.display="block";
    } else {
        text.style.display="none";
    }
}

</script>

any solutions?