The CDN links for React isn’t rendering

I followed a tutorial and build my own simple react project but the links aren’t working. I followed a lot of tutorials on how to do it, but the results are the same
The web page just comes out blank. I don’t know if I’m missing something or not. I tried it on codepen and it works fine, but not with CDN links.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Random Quote Machine</title>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/c2d871e1b7.js" crossorigin="anonymous"></script>
</head>
<body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel" src="./script.js"></script>
</body>
</html>

script.js:

const quotes= [
    {
      quote:
        "Life is too short and sweet to be spent by cribbing and complaining about things. Here are some random quotes about the most wonderful gift that we've got",
      author: " Life"
    },
  {
   quote: "Programming is not a science. Programming is a craft.",
  author: "Richard Stallman"  
  },
  {
    quote: "Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.",
    author: "Linus Torvalds"
  },
   {
    quote: "In real open source, you have the right to control your own destiny",
    author: "Linus Torvalds"
  },
  {
  quote: "We don't make mistakes; we just have happy accidents.",
    
    author: "Bob Ross"
  }
  
  ];

class Quote extends React.Component {
constructor(props) {
  super(props);
  this.state = {
   quote: '----',
   author: '----'
   };
  
  this.handleChange=this.handleChange.bind(this);
}
  
  handleChange(){
    let i= Math.floor(Math.random() * quotes.length)
    this.setState({
      quote: quotes[i].quote,
      author: quotes[i].author
    });
  }
  
 render() {
  return (
    <div>
    <div id="quote-box" class="d-flex justify-content-center flex-nowrap">
      <div id="text"> 
      <button id="new-quote" onClick={this.handleChange}>Click Me</button>
      <p>Quote: {this.state.quote}</p>
        <div id="author">
        <p>Author: {this.state.author}</p>
           
         </div>
       </div>
     </div>
     </div>
  );
 }
}

ReactDOM.render(<Quote />, document.getElementById('root'));

Here is the screenshot of the errors:
[1]: https://i.stack.imgur.com/fYdNe.png

Whatsapp-web.js loading issue in browserless env

I am getting below errors while running whatsapp-web js in centos7 server

home/samplebot/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:241 reject(new Error([
^

Error: Failed to launch the browser process!
[0409/224659.794826:ERROR:zygote_host_impl_linux.cc(90)] Running as root without –no-sandbox is not supported. See https://crbug.com/638180.

TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md

at onClose (/home/samplebot/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:241:20)
at Interface.<anonymous> (/home/samplebot/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:231:68)
at Interface.emit (node:events:538:35)

Anybody have any solution for this , Please help me

Extract and save data from injected form with GM_saveValue

I have written a userscript for a particular webpage, and this script has some variables that I would like to be modifiable by the user, without them having to edit the script by hand such that the variables survive script updates.

Currently I am injecting a new <form> into the existing settings page of the website with the appropriate inputs and a <button> to trigger an injected function of which should run GM_saveValue with a value extracted from the form.

The problem is that this script/function isn’t able to access GM_saveValue as that only exists in the scope of the TM script itself, hence I cannot actually save the settings. The rest of the code is fine, except this problem.

I have also tried defining the function inside of the userscript instead of injecting it in a <script> tag, but this has much the same problem that the page itself is unaware of this function due to it being in TM’s scope.

Is there a way to either make GM_setValue accessible to the script that is injected into the page, or to make the button on the page able to access the function in the Userscript?

Option 1, inject a script tag:

    let custom_settings_section = document.createElement('section');
    let settings_script_tag = document.createElement('script');
    settings_script_tag.text = `
    function qol_saveCustomVariables() {
    GM_setValue("custom_currency", document.querySelector('qol_custom_currency').value); // GM_setValue is unavailable in this scope.
    document.querySelector('qol_save_success').style.display = "block";
    }
    `;
    main_content.appendChild(settings_script_tag);
    custom_settings_section.innerHTML = `
    </script>
    <h3>Ch4rl1e's QoL Settings</h3>
    <form onsubmit="return false">
    <p>Custom Currency Symbol: <input id="qol_custom_currency" type="string" name="qol_custom_currency" value=${custom_currency}></p>
    <button onclick=qol_saveCustomVariables()>Save</button>
    <p id="qol_save_success" class="alert alert-success" style="display: none;">Saved!</p>
    </form>
    `;

Option 2 define function in userscript:

    let main_content = document.querySelector("#rightcolumn");
    let custom_settings_section = document.createElement('section');
    function qol_saveCustomVariables() { // the button injected into the page cannot "see" this function
        GM_setValue("custom_currency", document.querySelector('qol_custom_currency').value);
        document.querySelector('qol_save_success').style.display = "block";
    }
    custom_settings_section.innerHTML = `
    <h3>Ch4rl1e's QoL Settings</h3>
    <form onsubmit="return false">
    <p>Custom Currency Symbol: <input id="qol_custom_currency" type="string" name="qol_custom_currency" value=${custom_currency}></p>
    <button onclick=qol_saveCustomVariables()>Save</button>
    <p id="qol_save_success" class="alert alert-success" style="display: none;">Saved!</p>
    </form>
    `

    main_content.appendChild(custom_settings_section);

Click with waitForEvents cause Timeout error when using Gauge and Taiko

I’m using Gauge and Taiko (v1.3.2).

Gauge version: 1.4.3
Commit Hash: f98dd40

Plugins:
html-report (4.1.4)
js (2.4.0)
screenshot (0.1.0)

I have a form that have a Save button. I want click the Save button and make sure that the form is fully submitted.

So I use the following code:

await click('Save' , {
            waitForEvents: ['firstMeaningfulPaint'],
            navigationTimeout:40000}); 

The Gauge timeout in js.properties is:

test_timeout = 40000

What actually happen:
The Save button being clicked and the form submit. Also it navigate to the next page and wait there. The page loads and you can see the elements of the page. after some moments its return this error:

enter image description here

Saving a text input to separate js files

I’m trying to make a quiz web app with javascript and I am stuck.
There are 2 HTML files, one as starter.html and one as index.html. I have an input in my starter file which takes in a username which I want to display later on the index site like:

alert(`Congrats ${playerName} you got all the questions right!`)

and a “submit” link which takes you to the next site and stores a variable like this:

<input type="text" id="username" placeholder="Enter your name"/>
<a id="startGame" href="index.html">Start Game</a>

const inputArea = document.querySelector("#username");
const startButton = document.querySelector("#startGame");

var saveUsername = function () {
  var playerName = inputArea.value;
};

How can i access the playerName variable from the index.html? Firstly, I intended to use a global js file but I miss some declared elements since i have two separate html file and it does not find the elements during the DOM manipulation (cannot read properties of null). I tried using two separate js file but I couldn’t find the solution to access data from a javascript file and store it in the second one.

Any ideas?

Vue3 | Pinia – Watching storeToRefs in composable function does not work

I’m trying to understand the purpose of composables. I have a simple composable like this and was trying to watch state from a Pinia store where the watch does not trigger:

import { ref, watch, computed } from "vue";
import { storeToRefs } from "pinia";
import useFlightsStore from "src/pinia/flights.js";
import usePassengersStore from "src/pinia/passengers.js";

export function useFlight() {
    const route = useRoute();

    const modalStore = useModalStore();
    const flightsStore = useFlightsStore();
    const { selection } = storeToRefs(flightsStore);

    const passengersStore = usePassengersStore();
    const { passengers, adults, children, infants } =
        storeToRefs(passengersStore);

    watch([adults, children, infants], (val) => console.log('value changes', val))


Where as the same thing in a Vue component works as expected.

So we cannot watch values inside composables?

Navigating the Prototype chain in javascript

function Student(name, age) {
  this.name = name;
  this.age = age;
}

Student.prototype.showDetails = function () {
  console.log(`${this.name}, ${this.age}`);
};

let Manish = new Student('Manish', 34);
console.log(Manish.__proto__.__proto__.__proto__);
console.log(Manish);

In the above code, the second last line “console.log(Manish.proto.proto.proto);” logs null as expected. However when i manually navigate through the prototype chain using the object from the last line “console.log(Manish)”, i have to go down 5-6 levels of the proto property till i get a null value. Is there some explanation?? Thanks in advance..

`REmap` package and radar chart inside `echarts4r` package showing blank plot

Question

## Set a data frame format cities and randomly set country code
data = data.frame(country=mapNames('world'), value=5*sample(178)+200)

vec = c('Beijing','Tokyo','Shanghai','New York','Sydney','London','Bangkok',
        'Taipei','Moscow','Washington','Lyon','Milan','Rome','Macao',
        'Singapore','Hong Kong','Kuala Lumpur','Madrid','Geneva','Paris',
        'Melbourne','Boston','Washington','Liverpool','Brighton','Bali',
        'San Francisco','Jakarta','Ho Chi Minh','Brasilia','Barcelona',
        'Rio de Janeiro','Buenos Aires','Bern','Basel','Zurich','Manila',
        'Toronto','Vancouver','Budapest','New Delhi','Thimphu','Mumbai',
        'Cairo','Greater Johannesburg','Durban','Alexandria','Zaria','Dubai',
        'Istanbul','Mexico City','Sapporo','Osaka','Ulaanbaatar','Vienna')

## Get world city geocode by ggmap
#geodata = suppressAll(as.data.frame(cbind(ggmap::geocode(vec),vec)))
## Get world city geocode from simplemaps.com
## https://simplemaps.com/data/world-cities
##
## https://github.com/scibrokes/owner/issues/2
## 
geodata <- readr::read_csv('data/worldcities.csv') |> 
  dplyr::filter(capital == 'primary') |> 
  dplyr::select(lng, lat, country, city) |> 
  dplyr::rename(lon = lng)

countries <- geodata$country |> 
  unique()

## randomly set country codes
data <- data.frame(
  country = countries, 
  value = 5 * sample(length(countries)) + 200)

## cities
#vec <- geodata$city

## lon & lat of cities
geodata <- geodata |> 
  data.frame() |> 
  dplyr::select(lon, lat, city) |> 
  dplyr::rename(vec = city)

## Design a line data frame
#markLinedata <- data.frame(
#  origin = rep('Beijing', (length(vec) - 1)), 
#  destination = geodata$vec[!geodata$vec %in% 'Beijing'])

## Design a line data.frame
markLinedata = data.frame(origin=rep('Beijing', 54),destination = vec[-1])

REmap package and radar chart inside echarts4r package showing blank plot.

Debugs

明白了Echarts.js和adminLTE.js都会使用$来作为一个调用的接口, 产生了冲突, 在JS层面产生了冲突, 所以不能同时使用
除了把它用htmlwidgets重写掉之外, 我想不出有什么解决的方法…

Citation: shinydashboard中如何展示REmap?DT::dataTableOutput一起用显示空白?#29

Check your canvas in the page. I suspect it’s just really huge and you need to scroll down a little to see it.

Citation: shiny htmlwidget renders blank

You can try using some jQuery directly in order to respond to the user clicking on the button. The onRender would be:
…

Citation: Shiny actionButton() output in onRender() function of htmlWidgets

原因总结 (transl: Reason)

  1. echarts路径错误 (transl: 1. echarts path error)
  2. 没有相关的json数据 (transl: 2. No relevant json data)
  3. 没有引入jQuery (transl: 3. doesn’t import jQuery)

原因总结 (transl: Reason)
…

Citation: 运行echarts的官方示例显示为空白的解决方法

Tried to raise an issue on GitHub 明白了Echarts.js和adminLTE.js都会使用$来作为一个调用的接口, 产生了冲突,在JS层面产生了冲突,所以不能同时使用#428 and noticed that somebody knew js via 写了个htmlwidget R包:faq, somebody shade me a light?

How to make pure js cycle of callbacks?

I have an API from which I need to query N pages of data. Because I do not want to overload the API, I want to do it sequentially and without blocking the main thread.

The code would be something like this:

var res = []; // all data from api
var totalPages = 10;
var pageSize = 100;
for (let page = 0; page < totalPages; page++) {
    // load using jQuery ajax request
    $.get('api.php', { page: page, page_size: pageSize }, function(result) {
        res.push(...result); // add data to resulting array
    });
}

But this approach has a few issues:

  1. Since it is async, it will just run all requests in parallel, overloading API as a result. I need them to still run async, but each should run only when the previous is done.
  2. Since all the calls are async, by the end of the cycle we still wouldn’t have the requested data – it will be loading in the background. We need somehow to wait for all callbacks to be done before returning res to some other code that needs it.
  3. There is no way to make every callback pass its result to the next callback and it is the only way to stop loading when some callback receives “stop loading”/”no more data” request from the server

Is there a way to fix these issues without using some side libraries or promises? Just plain old vanilla javascript.
Sorry if something looks unclear, I am not very experienced in js

How can i move this function out from app.js?

I intend to move out logic from my app.js. Right now, in app.js, I have a function that changes state of some variables in App.js. I want to learn what is the correct way to change the state inside app.js by letting app.js call a function (for example on click) that is in another component.

my app.js looks like the following:

const App = () => {
    const [opacity, opacitySet] = React.useState(1);
    const [showStep, setDisplayStep] = React.useState(true);
    const [isQrActive, setQrState] = React.useState(false);
    
/** code **/

  <ButtonContinue
    onClick={() => {
       stateChanger();
    }}
    style={{ backgroundColor: "black" }}
  >
    <p>cancel</p>
  </ButtonContinue>

/** lots of code **/

 function stateChanger() {  

   opacitySet(0);
     setTimeout(() => {

       opacitySet(1);
       setDisplayStep(!showStep);
       setQrState(!isQrActive);
     }, 400);

 }

/** and more code **/

}

I want to move the stateChanger function out from app.js, but still keep the same functionality. This in turn would allow me to call stateChanger from other classes easily.

Can’t find the source of error: Objects are not valid as a React child

I am still learning React and am doing a project using the SpotifyAPI to create playlists. I was having trouble getting the search results to display the correct properties, but now I think I have broken the whole app and I am really lost trying to get to the bottom of these errors.

When I try to search I get this error

Uncaught Error: Objects are not valid as a React child (found: object with keys {album_type, artists, available_markets, external_urls, href, id, images, name, release_date, release_date_precision, total_tracks, type, uri}). If you meant to render a collection of children, use an array instead.

When the user types into the search field the errors flow in (~99) I think it comes from generating the tracks array in the Spotify.js search() function but I have been staring at this for a while now and I’m lost

Here is my Spotify.js file

let userAccessToken;
let expirationTime;
const clientID = "a8ed13dbf0944e5f9eb0405c17cbc8e8";
const redirect_uri = "http://localhost:3000/";
const base_url = "https://api.spotify.com/v1";

const Spotify = {
  getAccessToken() {
    if (userAccessToken) {
      return userAccessToken;
    }
    const url = window.location.href;
    if (url.match(/access_token=([^&]*)/) !== null) {
      userAccessToken = url.match(/access_token=([^&]*)/)[1];
      expirationTime = Number(url.match(/expires_in=([^&]*)/)[1]);
      window.setTimeout(() => userAccessToken = '', expirationTime * 1000);
      window.history.pushState('Access Token', null, '/');
      return userAccessToken;
    } else {
      window.location = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirect_uri}`
    }
  },

  async search(term) {
    if (userAccessToken === undefined) {
      this.getAccessToken();
    }
    const endpoint = `${base_url}/search?type=track`;
    const query = `&q=${term}`;
    try {
      const response = await fetch(`${endpoint}${query}`, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${userAccessToken}`
        }
      });
      if (response.ok) {
        const jsonResponse = await response.json();
        let tracks = [];
        if (jsonResponse.tracks) {
          jsonResponse.tracks.items.forEach(track => tracks.push({
              id: track.id,
              name: track.name,
              artist: track.artist,
              album: track.album,
              uri: track.uri
          }));
        }
        return tracks;
      }
      throw new Error("Search request failed.");
    } catch (error) {
      console.log(error.message);
    }
  },

  findUserId() {
    if (userAccessToken === undefined) {
      this.getAccessToken();
    }
    let userId;
    return fetch(`${base_url}/me`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${userAccessToken}`
      }
    }).then(response => { return response.json() })
      .then(jsonResponse => {
        userId = jsonResponse.id;
        return userId;
      })
  },

  async savePlaylist(name, trackURIs) {
    if (!name || !trackURIs) {
      return;
    }
    if (userAccessToken === undefined) {
      this.getAccessToken();
    };
    const userId = await this.findUserId();
    let playlistId;
    try {
      const response = await fetch(`${base_url}/users/${userId}/playlists`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${userAccessToken}`
        },
        body: JSON.stringify({
          name: name,
          description: "Playlist made using Jammming",
          public: false
        })
      });
      if (response.ok) {
        const jsonResponse = await response.json();
        playlistId = jsonResponse.id;
        try {
          const result = await fetch(`${base_url}/users/${userId}/playlists/${playlistId}/tracks`, {
            method: "POST",
            headers: {
              Authorization: `Bearer ${userAccessToken}`
            },
            body: JSON.stringify({ uris: trackURIs })
          });
          if (result.ok) {
            return;
          }
          throw new Error('Adding to playlist request failed.');
        } catch (error) {
          console.log(error.message);
        }
      }
      throw new Error("Save playlist request failed.");
    } catch (error) {
      console.log(error.message);
    }
  }
};

export default Spotify;

Here is App.js

import React from 'react';

import SearchBar from '../SearchBar/SearchBar';
import SearchResults from '../SearchResults/SearchResults';
import Playlist from '../Playlist/Playlist';
import Spotify from '../../util/Spotify';

import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchResults: [],
      playlistName: "",
      playlistTracks: []
    };
    this.addTrack = this.addTrack.bind(this);
    this.removeTrack = this.removeTrack.bind(this);
    this.updatePlaylistName = this.updatePlaylistName.bind(this);
    this.savePlaylist = this.savePlaylist.bind(this);
    this.search = this.search.bind(this);
  }

  addTrack(track) {
    if (this.state.playlistTracks.find(t => t.id === track.id)) {
      return;
    }
    this.setState({ playlistTracks: [...this.state.playlistTracks, track] });
  }

  removeTrack(track) {
    const newList = this.state.playlistTracks.filter(t => t.id !== track.id);
    this.setState({ playlistTracks: newList });
  }

  updatePlaylistName(name) {
    this.setState({ playlistName: name });
  }

  savePlaylist() {
    const trackURIs = this.state.playlistTracks.map(t => t.uri);
    Spotify.savePlaylist(this.state.playlistName, trackURIs)
      .then(this.setState({
        playlistName: 'New Playlist',
        playlistTracks: []
      }));
  }

  async search(term) {
    const results = await Spotify.search(term);
    this.setState({ searchResults: results });
  }

  render() {
    return (
      <div>
        <h1>Ja<span className="highlight">mmm</span>ing</h1>
        <div className="App">
          <SearchBar onSearch={this.search} />
          <div className="App-playlist">
            <SearchResults
              results={this.state.searchResults}
              onAdd={this.addTrack} />
            <Playlist
              name={this.state.playlistName}
              tracks={this.state.playlistTracks}
              onRemove={this.removeTrack}
              onNameChange={this.updatePlaylistName}
              onSave={this.savePlaylist} />
          </div>
        </div>
      </div>
    );
  }
}

export default App;

Here is TrackList.js

import React from 'react';

import Track from '../Track/Track';

import './TrackList.css';

class TrackList extends React.Component {
  render() {
    return (
      <div className="TrackList">
        {this.props.tracks.map(track => (
          <Track
            key={track.id}
            track={track}
            name={track.name}
            artist={track.artist}
            album={track.album}
            onAdd={this.props.onAdd}
            onRemove={this.props.onRemove}
            isRemoval={this.props.isRemoval} />
          )
        )}
      </div>
    );
  }
}

export default TrackList;

Here is the Track.js

import React from 'react';

import './Track.css';

class Track extends React.Component {
  constructor(props) {
    super(props);
    this.addTrack = this.addTrack.bind(this);
    this.removeTrack = this.removeTrack.bind(this);
  }

  addTrack() {
    this.props.onAdd(this.props.track);
  }

  removeTrack() {
    this.props.onRemove(this.props.track);
  }

  renderAction() {
    return (
      <button
        className="Track-action"
        onClick={ this.props.isRemoval ? this.removeTrack : this.addTrack }>
        { this.props.isRemoval ? '-' : '+' }
      </button>
    );
  }

  render() {
    return (
      <div className="Track">
        <div className="Track-information">
          <h3>{this.props.name}</h3>
          <p>{this.props.artist} | {this.props.album}</p>
        </div>
        {this.renderAction()}
      </div>
    );
  }
}

export default Track;

JavaScript three array elements match-check by loops?

Unsure how to setup loops correctly to check whether elements in a targeted array matches any two other arrays or matches them both:

The code:

let test = [1,2,3,4,5,6,7]
let test2 = [7,8,9,10,11]
let check_test = [2,7,10,12]

for (var testa in test) {
  for (var test2a in test2) {
     for (var check_testa in check_test) {
        #Triple for-loop trying to loop all arrays
        if (check_testa == testa && check_testa != test2) {
           console.log("Match TEST")
        } else if (check_testa != testa && check_testa == test2) {
           console.log("Match TEST2")
        } else if (check_testa == testa && check_testa == test2) {
           console.log("Both match!")
        } else {
           console.log("None match!")
       }
     }
   }
 }

Basically the code supposed check whether the elements in array check_test matches any elements in the other two arrays test and test2.

If the element(of check_test) match elements in only one of the two other arrays, then print “Match [test] or [test2]!”. If both match then print “Both Match!” and finally if both no match then print “None Match!”

And the output for this is supposed to be:

Match TEST!
Both Match!
Match TEST2!
None Match!

So how to set loops correctly to make it match-check the elements and output only once? Thanks for reading.

useState polyfill, is this correct?

Trying to write a custom implementation of useState. Let’s say only for a single value.

function useMyState(initVal){
  const obj = {
    value: initVal,
    get stateValGet() {
      return this.value
    },
    set stateValSet(val) {
      this.value = val
    }
  };
  const setVal = (val) => {
    obj.stateValSet = val
  }
  return [obj.stateValGet, setVal]
}

Doesn’t seem to work though, can anyone tell why?
Unable to crack this.

It returns this [, <function_setter>]
So if you try to run this setVal method, it does trigger the setter. But getter never gets called upon the updation.