React Numeric Input Sum Calculator

the following code is a dynamic sum calculator made in ReactDOM
extracted from codepen https://codepen.io/tfbrown/pen/zjXvZy

class NumericInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      num1: 0,
      num2: 0,
      result: 0
    };
    this._changeNum1 = this._changeNum1.bind(this);
    this._changeNum2 = this._changeNum2.bind(this);
  }
  
  _changeNum1(e) {
    if (e.target.validity.valid) {
      var newNum1 = +(e.target.value)
      this.setState({
          num1: newNum1,
          result: newNum1 + this.state.num2
        }); 
    }
  }
  
    _changeNum2(e) {
    if (e.target.validity.valid) {
      var newNum2 = +(e.target.value)
      this.setState({
          num2: newNum2,
          result: this.state.num1 + newNum2
        }); 
    }
  }

  render() {
    return (
      <div>
        <div>
          <p>first number:</p>
          <input type="number" value={this.state.num1} onChange={this._changeNum1} step="any" />
        </div>
        <div>
          <p>second number:</p>
          <input type="number" value={this.state.num2} onChange={this._changeNum2} step="any" />
        </div>
        <p>Result: {this.state.result}</p>
      </div>
    )
  }  
}  

// The following is boilderplate JavaScript
ReactDOM.render(<NumericInput />, document.getElementById("main"));

the problem is that I want to use this code but my project is made in Next.js and I would like to make this code functional in the .js file without the need for an html DOM making it functional in this index.js file.

import { useWeb3React } from "@web3-react/core"
import { useEffect } from "react"
import { injected } from "../components/wallet/Connectors"
import Web3 from 'web3'
import { Icon } from '@iconify/react';
import React, { useState } from "react";

export default function Home() {
 
    return (

  
    )

}

How to make the browser play a local mp3 when a span displays on the page?

When we accidentally scan a duplicate, Red text appears in the browser:

<span id="lblMessage" style="color:Red;font-weight:bold;">
    Duplicate serial number found.
</span> 

Can you please show javascript that we can add to a plugin like tampermonkey or chrome extension like “Edit – User JavaScript and CSS” that would play a local audio alert with error.mp3.

I have error.mp3 on local drive.

Thank you!

I have two different div coded using vue.js3 composition and v-if is not working correctly?

I’m trying to show or hide section of the app using Vue.js 3 composition using v-if. I was able to get this working using vue.js 2 API option, but recently started using vue.js 3 API Composition.

It looks like screenMode is being updated when displaying value using console.log, but the section is not hiding. Any idea?

<script setup>
  
  import { ref, onMounted } from 'vue'

  let screenMode = 'screenA'; 

  console.log('screenMode = ' + screenMode)

  function test(recordDate) {
    screenMode = 'screenB'
    console.log("screenMode =" + screenMode)
  }


  onMounted(() => {
    screenMode.value
  })

</script>



<template>
    <p class="screenTitle" >Calendar</p>

    <div class="container" v-if="screenMode === 'screenA'">    
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col"></th>
            <th scope="col">Date</th>
            <th scope="col">Total</th>
          </tr>
        </thead>
        <tbody>
          <tr id="row1" @click="test('5/26/2022')">
            <th scope="row"></th>
            <td>5/26/2022</td>
            <td>52</td>
          </tr>
          <tr>
            <th scope="row"></th>
            <td>5/27/2022</td>
            <td>4</td>
          </tr>
          <tr>
            <th scope="row"></th>
            <td>5/28/2022</td>
            <td>90</td>
          </tr>        
        </tbody>
      </table>
  </div>

  <div class="container" v-if="screenMode === 'screenB'">    
    <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">First</th>
          <th scope="col">Last</th>
          <th scope="col">Handle</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">1</th>
          <td>Mark</td>
          <td>Otto</td>
          <td>@mdo</td>
        </tr>
        <tr>
          <th scope="row">2</th>
          <td>Jacob</td>
          <td>Thornton</td>
          <td>@fat</td>
        </tr>
        <tr>
          <th scope="row">3</th>
          <td colspan="2">Larry the Bird</td>
          <td>@twitter</td>
        </tr>
      </tbody>
    </table>
  </div>


</template>

<style>

.screenTitle{
  color: blueviolet;
  margin-left: 10px;
  margin-top: 25px;
}

</style>

<!-- <style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style> -->



I am getting “Uncaught SyntaxError: Cannot use import statement outside a module” although i have script type=”module” in my html file [duplicate]

I am getting “Uncaught SyntaxError: Cannot use import statement outside a module” error when i am trying to import another javascript files from my javascript & html file. I added script type=”module” in html but didnt make any other changes as these are only vanilla js files. What is wrong with my import?

Thanks in advance

My html file

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <link rel="stylesheet" href="./css/cizim.css" />
        <title>Line</title>
        
    </head>
    <body>
<table align="center" width="1200" border="0">
  <tbody>
    <tr>
      <td width="500"><div align="center"><canvas width ="400" height="400" id="canvas" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.
          
        </canvas>
    <script type="module" src="canvas.js"></script>  
          </td>
      <td><table>
          <tbody>
              <tr>
                <td><label for="fname">Başlangıç Mesneti:</label></td>
                <td>
                    <input type="radio" id="msm" name="first" value="msm" checked="checked">
                    <label for="css">Mafsallı Sabit Mesnet</label>
                    <input type="radio" id="mhm" name="first" value="mhm">
                    <label for="javascript">Mafsallı Hareketli Mesnet</label>
                    <input type="radio" id="ank" name="first" value="ank">
                    <label for="html">Ankastre Mesnet</label>
                </td>
              </tr>
                <tr>
                <td><label for="fname">Bitiş Mesneti:</label></td>
                <td>
                    <input type="radio" id="msm" name="second" value="msm" checked="checked">
                    <label for="css">Mafsallı Sabit Mesnet</label>
                    <input type="radio" id="mhm" name="second" value="mhm">
                    <label for="javascript">Mafsallı Hareketli Mesnet</label>
                    <input type="radio" id="ank" name="second" value="ank">
                    <label for="html">Ankastre Mesnet</label>
                </td>
                </td>
              </tr>
              <tr>
                <td><label for="fname">Başlangıç:</label></td>
                <td><input type="text" id="start" name="fname"></td>
              </tr>
              <tr>
                <td><label for="fname">Bitiş:</label></td>
                <td><input type="text" id="end" name="sname"></td>
              </tr>
                <tr>
                <td><label for="fname">Başlangıç Yükü:</label></td>
                <td><input type="text" id="byuk" name="sname"></td>
              </tr>
                  </tr>
                <tr>
                <td><label for="fname">Bitiş Yükü:</label></td>
                <td><input type="text" id="syuk" name="sname"></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td><button id="myBtn" onclick="updateCanvas()">Hesapla</button></td>
              </tr>
          
          
          
          </tbody>
          </table>
    </td>
    </tr>
  </tbody>
</table>


        <div align="center">

            
<script src="canvas.js"></script>
        </div>
        
        
    </body>
</html>

My main .js file (canvas.js)

import Draw from "./draw.js";
import Values from "./values.js";

Other 2 js files i want to import through canvas.js

export default class Values {
  constructor() {
    this.first = document.querySelector('input[name="first"]:checked').value;
    this.second = document.querySelector('input[name="second"]:checked').value;
    this.canvas = document.getElementById("canvas");
    this.start = parseInt(document.getElementById("start").value);
    this.end = parseInt(document.getElementById("end").value);
    this.byuk = parseInt(document.getElementById("byuk").value);
    this.syuk = parseInt(document.getElementById("syuk").value);
    this.canvasWidth = canvas.width;
    this.canvasHeight = canvas.height;
    this.ctx = canvas.getContext("2d"); 
    this.canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
  }
}
export default class Draw {
  constructor(startx, starty,endX, endY,canvasData,ctx) {
    this.startx = startx;
    this.starty = starty;
    this.endX = endX;
    this.endY = endY;
    this.canvasData = canvasData;
    this.ctx = ctx;
  }
  drawMyLine(startx, starty,endX, endY){
    ctx.beginPath();
    ctx.lineWidth = 1;
    ctx.strokeStyle = 'red';
    ctx.moveTo(startx, starty);
    ctx.lineTo(endX,endY);
    ctx.stroke();
  }
  drawPixel (x, y, r, g, b, a) {
    var index = (x + y * canvasWidth) * 4;
    //pixelDensity(1);
    canvasData.data[index + 0] = r;
    canvasData.data[index + 1] = g;
    canvasData.data[index + 2] = b;
    canvasData.data[index + 3] = a;
  }
}

innostudio fileuploader doesen’t shows thumbnails in bs-stepper

I built innostudio fileuploader into bs-stepper in a sub step.
Uploads and previews work correctly. The problem is showing the thumbnails when files are already called using “Preload Files”.
The preload files are correctly linked, but only a “no-image-icon” is shown.
I suspect that a lazy-loader is not running and I don’t know how to start it when calling the corresponding step.
I can execute a Javascript function by clicking on this step… but what should this function contain so that the lazyload is executed afterwards?

I’ve tried the following on click-statement on the last step-button before showing fileuploader:

function preloadImages(){
    $('input[name="filesUploadV2"]').fileuploader();
}

Image gallery innostudio fileuploader

React – Protocol “https:” not supported. Expected “http:”

Yeah, I saw this post, however I do not have such file where I can edit to use https and my backend is ASP.NET MVC Core 3.1.

So when my React application sends API calls to ASP.NET MVC application, then it throws an error:

TypeError [ERR_INVALID_PROTOCOL]: Protocol "https:" not supported. Expected "http:"
    at new NodeError (node:internal/errors:371:5)
    at new ClientRequest (node:_http_client:158:11)
    at Object.request (node:https:353:10)
    at Array.stream (C:My Files\Scriptsreactnode_moduleshttp-proxylibhttp-proxypassesweb-incoming.js:126:74)
    at ProxyServer.<anonymous> (C:My Files\Scriptsreactnode_moduleshttp-proxylibhttp-proxyindex.js:81:21)
    at middleware (C:My Files\Scriptsreactnode_moduleshttp-proxy-middlewarelibindex.js:46:13)
    at handle (C:My Files\Scriptsreactnode_moduleswebpack-dev-serverlibServer.js:322:18)
    at C:My Files\Scriptsreactnode_moduleswebpack-dev-serverlibServer.js:330:47
    at Layer.handle_error (C:My Files\Scriptsreactnode_modulesexpresslibrouterlayer.js:71:5)
    at trim_prefix (C:My Files\Scriptsreactnode_modulesexpresslibrouterindex.js:315:13)

the url looks like this:

http://localhost:3030/api/foo/bar

Our development config file dev.js looks like this:

// development config
const package = require('../../package.json')
const { merge } = require('webpack-merge')
const webpack = require('webpack')
const commonConfig = require('./common')
const agent = require('agentkeepalive')

module.exports = (webpackConfigEnv, argv) => {
    return merge(commonConfig(argv), {
        mode: 'development',
        entry: [
            'react-hot-loader/patch', // activate HMR for React
            'webpack-dev-server/client?http://localhost:3030', // 
            'webpack/hot/only-dev-server', // bundle the client for hot reloading
            './index.tsx', // the entry point of our app
        ],
        devServer: {
            port: 3030,
            hot: true, // enable HMR on the server
            historyApiFallback: true, //
            proxy: {
                '/api/*': {
                    target: argv.env.mock ? '' : 'https://localhost:43000',
                    secure: false,
                    changeOrigin: true,
                    agent: new agent({
                        maxSockets: 100,
                        keepAlive: true,
                        maxFreeSockets: 10,
                        keepAliveMsecs: 100000,
                        timeout: 6000000,
                        freeSocketTimeout: 90000, // free socket keepalive for 90 seconds
                    }),
                    onProxyRes: (proxyRes) => {
                        var key = 'www-authenticate'
                        proxyRes.headers[key] =
                            proxyRes.headers[key] && proxyRes.headers[key].split(',')
                    },
                },
            },
        },
        devtool: 'cheap-module-source-map',
        plugins: [
            new webpack.HotModuleReplacementPlugin(), // enable HMR globally
            new webpack.DefinePlugin({
                'process.env.appVersion': JSON.stringify(package.version),
                'process.env.isMockMode': JSON.stringify(argv?.env?.mock),
                'process.env.isDevelopment': true,
            }),
        ],
    })
}

How can I solve this issue? I cannot use http://localhost:43000 because my backend uses SSL.
Ahy help would be greatly appreciated!

js equivalent of str.replace(.., replacerFunction()) in rust

I am currently try to learn rust by transpiling some scripts from js to wasm.

In js there is this function:

string.prototype.replace(substr, replacerFunction())

I am searching a rust function for this case. I know there is also a string.replace func, but I think I cant pass there a custom replacerFunction to it.

I have this snippet in js:

const sentence = 'This is a sentence';
modifiedSentence = sentence.replace(/p{L}+/gu, (word) => {

      // imaging some heavily transformation on `word` here, based on its type like (verb, object or subject).

      return word;
});

Maybe a regex only solution would somehow be possible, but not for me 🙂

Thanks for any hints !

How to simulate receiving message from Server to Client in order to unit test SignalR client/manager with react-testing-library and jest?

I have a working SignalR manager with a connection: HubConnection that is already built with .build().
Check the following quick example:

const connection: HubConnection = new HubConnectionBuilder().withUrl(...).build();
connection.start().then(() => {
  console.log('connected');
  ...
  connection.on('PushNewMessage', (message) => addNewMessageToReduxStore(message));
  connection.on('DeleteMessage', (messageId) => deleteMessageFromStoreWithId(messageId));
  ...
});

Server sends message ‘PushNewMessage’ with an object with string text and number id. This triggers the addNewMessageToReduxStore(message) which is tracked for changes and trigger more Redux changes.

I want to write a unit test that starts with “Server sending a message” and compares the final Redux store state after 5 seconds since the message was received from the server to match an expected store state – then the test will pass.

So how to simulate receiving a message from the server in that exact web socket managed by the HubConnection used in the unit test initialization?

pieces not dropping properly after dragging pieces – chessboard.js

I’ve been trying to adapt a chess engine tutorial for my needs, and I’ve been trying to figure out how the board renders. When I drag a piece, while it is dropped it doesn’t stay and instead stays with my mouse pointer. The move highlight works but I cant drag another piece or see my random bot play the next move. I’ve checked the FEN and the moves are registered there though.

HTML Header:

<head>
  <title>ChessBot</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" 
  integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2"
  crossorigin="anonymous"></script>

  <!-- Our Custom CSS -->
  <link rel="stylesheet" href="assets/main.css">
  <link rel="stylesheet" href="assets/font/font.css">
  <link rel="stylesheet" href="assets/style.css">
  <!-- Font Awesome JS -->
  <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js"
    integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ"
    crossorigin="anonymous"></script>
  <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js"
    integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY"
    crossorigin="anonymous"></script>
  <!-- Chessboard JS -->
  <link rel="stylesheet" href="https://unpkg.com/@chrisoakman/[email protected]/dist/chessboard-1.0.0.min.css"
    integrity="sha384-q94+BZtLrkL1/ohfjR8c6L+A6qzNH9R2hBLwyoAfu3i/WCvQjzL2RQJ3uNHDISdU" crossorigin="anonymous">
  <script defer src="https://unpkg.com/@chrisoakman/[email protected]/dist/chessboard-1.0.0.min.js"
    integrity="sha384-8Vi8VHwn3vjQ9eUHUxex3JSN/NFqUg3QbPyX8kWyb93+8AC/pPWTzj+nHtbC5bxD"
    crossorigin="anonymous"></script>

  <!-- Chess JS (slightly modified) -->
  <script defer src="js/chess.js"></script>

  <!-- Bootstrap JS -->
  <script defer src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"
    integrity="sha384-6khuMg9gaYr5AxOqhkVIODVIvm9ynTT5J4V1cfthmT+emCG6yVmEZsRHdxlotUnm" crossorigin="anonymous">
    </script>

  <!-- Custom JS -->
  <script defer src="js/script2.js"></script>

</head>

Javascript Board Manipulation

function removeGreySquares() {
  $('#myBoard .square-55d63').css('background', '');
}

function greySquare(square) {
  var $square = $('#myBoard .square-' + square);

  var background = whiteSquareGrey;
  if ($square.hasClass('black-3c85d')) {
    background = blackSquareGrey;
  }

  $square.css('background', background);
}

function onDragStart(source, piece) {
  // do not pick up pieces if the game is over
  if (game.game_over()) return false;

  // or if it's not that side's turn
  if (
    (game.turn() === 'w' && piece.search(/^b/) !== -1) ||
    (game.turn() === 'b' && piece.search(/^w/) !== -1)
  ) {
    return false;
  }
}

function onDrop(source, target) {
  undo_stack = [];
  removeGreySquares();

  // see if the move is legal
  var move = game.move({
    from: source,
    to: target,
    promotion: 'q', // NOTE: always promote to a queen for example simplicity
  });

  // Illegal move
  if (move === null) return 'snapback';

  globalSum = evaluateBoard(game, move, globalSum, 'b');
  updateAdvantage();

  // Highlight latest move
  $board.find('.' + squareClass).removeClass('highlight-white');

  $board.find('.square-' + move.from).addClass('highlight-white');
  squareToHighlight = move.to;
  colorToHighlight = 'white';

  $board
    .find('.square-' + squareToHighlight)
    .addClass('highlight-' + colorToHighlight);

  alert(game.fen()) 
  if (!checkStatus('black'));
  {
    // Make the best move for black
    window.setTimeout(function () {
      makeRandomMove('b');
      window.setTimeout(function () {
        showHint();
      }, 250);
    }, 250);
  }
}

function onMouseoverSquare(square, piece) {
  // get list of possible moves for this square
  var moves = game.moves({
    square: square,
    verbose: true,
  });

  // exit if there are no moves available for this square
  if (moves.length === 0) return;

  // highlight the square they moused over
  greySquare(square);

  // highlight the possible squares for this piece
  for (var i = 0; i < moves.length; i++) {
    greySquare(moves[i].to);
  }
}

function onMouseoutSquare(square, piece) {
  removeGreySquares();
}

function onSnapEnd() {
  board.position(game.fen());
}

Config:

var config = {
  draggable: true,
  position: 'start',
  onDragStart: onDragStart,
  onDrop: onDrop,
  onMouseoutSquare: onMouseoutSquare,
  onMouseoverSquare: onMouseoverSquare,
  onSnapEnd: onSnapEnd,
};
board = Chessboard('myBoard', config);

Screenshot

Any help would be greatly appreciated.

Pretty Printing the structure of nested SASS Maps?

If we have nested maps in SASS (an Angular Theme for example) we can log the contents of it with @debug however it outputs everything in one line.

Anyone know if SASS has something that will pretty print the structure of nested maps?

So for example if we had:

$colors: (
  "primary": (
    "milk":       #fff,
    "cola":       #000,
    "mine-shaft": #232323,
  ),
  "secondary": (
    "pampas":      #f4f1ef,
    "pearl-brush": #e9e2dd,
    "alto":        #ddd,
  ),
);

We could do something like

@recursive-debug $colors

To log the structure of it.

Google Calendar API – getEvents everyday and only certain events with time frames

I am trying to write a script that I can click a custom menu button and it will pull all the events scheduled on my calendar within the hours of (9:00 AM – 11:00 AM , 12:00 PM – 1:00 PM , 3:00 PM to 5:00 PM). Right now it runs by grabbing everything on my calendar for the day (including lunch) and internal meetings but I only need the events that are scheduled within the specific hours.

Also is it possible to only pull certain things from the description of a google event? For ex, the getDescription will get everything included and most of it is not needed, though there is a linkedin profile URL in the description that i do need. How can I set it so it gets the description and only retains the items I want? Here is the script I am running in App Script with the Calendar API.


  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var cal = CalendarApp.getCalendarById("[email protected]");
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth(); //January is 0!
  var yyyy = today.getFullYear();
  var hh = 

  var events = cal.getEvents(new Date(yyyy, mm, dd, 0, 0, 0), new Date(yyyy, mm, dd, 23, 0, 0));

  for(var i = 0;i<events.length;i++){

   var title= events[i].getTitle();
   var sd = events[i].getStartTime();
   var loc = events[i].getLocation();
   var des = events[i].getDescription();
   var email = events[i].getGuestList().map(function(x) {return x.getEmail();}).join(',')
  
   ss.getRange(i+2, 2).setValue(title);
   ss.getRange(i+2, 8).setValue(loc);
   ss.getRange(i+2, 9).setValue(des); 
   ss.getRange(i+2, 9).trimWhitespace();
   ss.getRange(i+2, 1).setValue(sd);
   ss.getRange(i+2, 1).setNumberFormat("mm/dd/yyyy");
   ss.getRange(i+2, 7).setValue(email);
  }
 }


function addCandidates()  {

  let ui = SpreadsheetApp.getUi();
  ui.createMenu('Run Code').addItem('Add New Candidates','getEvents').addToUi();



}```

How to detect page load for accessing anchor hash input to the browser?

I have links as follows:

www.foo.com/#my_hash

The problem is, is that when the user input this, the hash is not scrolled to / accessed. My temporary work around was to use a custom method, which waits 4 seconds to manually scroll.

client.scrollToHash = function(delay = 0, offset = 0) {
  window.setTimeout(() => {
    const hash = document.location.hash.slice(1);
    if(!hash) {
      return;
    }
    const element = document.getElementById(hash);
    if(!element) {
      return;
    }
    window.scrollTo({
      top: element.getBoundingClientRect().top - offset,
      behavior: 'smooth'
    });
  }, delay);
};

Is it possible to detect something like an on load event from the native DOM, instead of using a timeout?

I am using functional components.

Do react functional components have an easy way to let you know that the component has rendered?

I am confused how anchor hashes work in general as if they come in from the user / browser, there will always be a delay, as the page takes time to load.

I would prefer not to use another library, but accomplish this using the DOM, or React functionality if possible.

How does the reducer function know that count is a state’s item?

I do not understand how reducer knows that count is from state without using state’s name in the code. I thought it was like “return {state.count: state.count + 1}“. How does it work?

import { useReducer } from 'react';
    
    const initialState = {count: 0};
    
    const reducer = (state, action) =>{
      switch(action.type){
        case 'minus':
          return {count: state.count + 1}
        break;
        case 'plus':
          return {count: state.count - 1}
        break;
        case 'reset':
          return initialState;
        break;
      }
      return state;
    }
    
    const App = () =>{
      const [state, dispatch] = useReducer(reducer, initialState);
    
      return(
        <div>
          <button onClick={() => dispatch({type: 'menos'})}>-</button>
          <div>{state.count}</div>
          <button onClick={() => dispatch({type: 'mais'})}>+</button>
          <button onClick={() => dispatch({type: 'reset'})}>reset</button>
        </div>
      );
    }
    
    export default App;

Unable to access property in javascript file in react component

I am building a chrome extension, which uses react/webpack, and it needs to inject code into an existing page. So I need to load one of my javascript files when the component is rendered.

However, I cannot access properties in that javascript file. I get error ‘Cannot read properties of undefined (reading ‘initialvalue’)‘. I have given the manifest.json file all the proper permissions and I know the script file is loading correctly. What am I doing wrong?

plugin.bundle.js (javascript file I’m trying to load)

var plugin = plugin || {};

SetupPlugin();
function SetupPlugin() {
    plugin.initialvalue = plugin.initialvalue || 123;
}

index.jsx

import { render } from 'react-dom';
import Embedtab from './Embedtab';

render(<Embedtab />, window.document.body.querySelector('.someclass'));

Embedtab.tsx

declare global {
  interface Window {
    plugin: any;
  }
}

export class Embedtab extends React.Component<any> {
  componentDidMount() {
    const script = document.createElement("script");
    script.src = chrome.runtime.getURL("./../plugin.bundle.js");
    script.async = false;
    script.onload = () => this.scriptLoaded();

    document.body.appendChild(script);
  }

  scriptLoaded() {
    alert("embedded loaded, value is " + window.plugin.initialvalue); //errors here
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          Hello World
        </header>
      </div>
    );
  }
};

export default Embedtab;

Variable in React is undefined on first render but defined after re-rendering. (Uncaught TypeError: vairable is undefined)

When I try to show the title of a movie (line 8 of App.js) I get the error “Uncaught TypeError: movies[0] is undefined”. If I do a log of the variable “movies” after line 5 the console makes two logs: Frist, logs movies as an empty array and then logs movies as an array with all the content, like I want.

The weird thing is that if I delete the line 8 {movies[0].title} and save the error dissapears as normal, but then if I add it again and save the movie title renders on screen like I’m trying to do.

App.js:

import './App.css';
import useApi from './useApi';

function App() {
  const movies = useApi();
  return (
    <div className="App">
      {movies[0].title}
    </div>
  );    
}

export default App;

My useApi returns an array with a list of movies:

import axios from 'axios';
import { useState, useEffect } from 'react';

const useApi = () => {
    const [movies, setMovies] = useState([]);

    const getData = async () => {
        try {
            const res = await axios(url);
            setMovies(res.data.results);
        } catch (error) {
            return [];
        }
    }

    useEffect(() => {
        getData();
    }, [])

    return movies;
}

export default useApi;

Knowing that if I print movies it logs an empty array but then it prints it normal like I said, i guess I’m having a problem with asynchrony but I can’t figure out what. And the fact that it works when removing and readding line 8 makes me more confused.