grab contents from page by elememtsclassname using chrome extension

i want to grab content from page by class. I wrote chrome extension, but I don’t get the contents of the element. I recieved [object HTMLCollection] in textarea. Please tell me how to fix my solution?

script.js

var text1 = document.getElementsByClassName("a-form-label")[0].innerText;
var text2 = document.getElementsByClassName("a-form-label")[1].innerText;
var text3 = document.getElementsByClassName("a-form-label")[2].innerText;

document.getElementById("auto-fill").addEventListener("click", () => {
    
    document.getElementById('name').value = text1;
    document.getElementById('email').value = text2;
    document.getElementById('telephone').value = text3;
});

My API data is not being rendered with React

I’m learning React by making a spotify clone and for now what I’m trying to do is to show spotify sections such as "last played songs", "top artists" and "top songs" through a component called Body.js.

I get the data from a spotify official API library created by jmperez in a useEffect hook in the App.js component. Once I get the data from the API, I store it in an object called initialState in a file called reducer.js.

This reducer.js file contains the initial state and the reducer function for a custom hook called useDataLayer.js which is basically a useContext hook that passes as value a useReducer to all the branches of my program. This way what I do is to update the initialState from App.js and access this object through the useDataLayer hook in the different branches of my program (among them the Body component).

The problem I am having now is that it is not rendering the three sections mentioned before in spotify, but only shows me one which is the “top songs”. The weird thing is that for a second it does render the other components as if it was getting the data and rendering but then it updates and they disappear. Please if someone can help me with this problem and explain me why this happens it would be great.

App.js code

import React, {useState, useEffect} from 'react';
import Login from './components/Login';
import Player from './components/Player';
import { getTokenFromResponse } from './spotify';
import './styles/App.scss';
import SpotifyWebApi from "spotify-web-api-js";
import { library } from '@fortawesome/fontawesome-svg-core';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { fab } from '@fortawesome/free-brands-svg-icons';
import { useDataLayer } from './components/Hooks/useDataLayer';

library.add(fas, fab);


//spotify library instance
const spotify = new SpotifyWebApi();

function App() {

  const [token, setToken] = useState(null);
  const [{ user }, dispatch] = useDataLayer();

  // where I get the necessary data from the api
  useEffect(() => {
    // function to get access token
    let accessToken = getTokenFromResponse();
    window.location.hash = '';

    if(accessToken){
      spotify.setAccessToken(accessToken);
      setToken(accessToken);

      //FROM HERE I GET THE DATA I NEED
      
      // here I get the data of my user
      spotify.getMe().then((data) =>{
        dispatch({
          type: "GET_USER",
          user: date
        })
      });
      
      spotify.getUserPlaylists().then((data) => {
        dispatch({
            type: "GET_PLAYLISTS",
            playlists: dates
        })
      });
      
      spotify.getMyTopTracks({limit: 4}).then((data) => {
        dispatch({
          type: "GET_TOP_TRACKS",
          top_tracks:data,
        })
      });

      spotify.getMyRecentlyPlayedTracks({limit: 4}).then((data) => {
        dispatch({
            type: "RECENTLY_PLAYED",
            recently_played: date,
        })
      });

      spotify.getMyTopArtists({limit: 4}).then((data) => {
        dispatch({
          type: "GET_TOP_ARTISTS",
          top_artists: date,
        })
      });
    }
  }, [token])

  //if token is valid enter Player.js where Body.js is inside and if not return to login component
  return (
    
      <div className="App">
        { token ? <Player spotify= {spotify} /> : <Login />}
      </div>
  );
}

export defaultApp;

Body.js code

import React from 'react'
import '../styles/Body.scss'
import { useDataLayer } from "./Hooks/useDataLayer.js";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

function Body({ spotify }) {

    //get the properties of the necessary data that I want to display in this component with useDataLayer
    const [{ spotify_recommendations, recently_played, top_tracks, top_artists }, dispatch] = useDataLayer();
   
    return (
        <div className= "main-body">
            <div className= "body-option">
                <span className= "see-more">See All</span>
                <FontAwesomeIcon icon={['fas', 'arrow-right']} />
                <div>
                    {
                        //to show the image and info of the track
                        recently_played?.items.map((item, index) =>{
                            return (
                                <div className= "track" key= {index}>
                                    <img src= {item.track.album.images[1].url} alt= "recently played track"></img>
                                    <div className= "track-data">
                                        <h3>{item.track.name}</h3>
                                        <p>{item.track.artists.map(artist => artist.name).join(", ")}</p>
                                    </div>
                                    
                                </div>
                            )
                        })
                        
                    }
                </div>
            </div>
            <div className= "body-option">
                <span className= "see-more">See All</span>
                <FontAwesomeIcon icon={['fas', 'arrow-right']} />
                <div>
                    {
                        //to show the image and info of the track
                       top_tracks?.items.map((topArtist, index) => {
                            return (
                                <div className= "track" key= {index}>
                                    <img src= {topArtist.album.images[1].url} alt= "recently played track"></img>
                                    <div className= "track-data">
                                        <h3>{topArtist.name}</h3>
                                        <p>{topArtist.artists.map(artist => artist.name).join(", ")}</p>
                                    </div>
                                    
                                </div>
                            )
                        })
                    }
                </div>
            </div>
            <div className= "body-option">
                <span className= "see-more">See All</span>
                <FontAwesomeIcon icon={['fas', 'arrow-right']} />
                <div>
                    {
                        //to show the image and info of the artist
                         top_artists?.items.map((topTrack, index) => {
                            return (
                                <div className= "track" key= {index}>
                                    <img src= {topTrack.images[1].url} alt= "recently played track"></img>
                                    <div className= "track-data">
                                        <h3>{topTrack.name}</h3>
                                        <p>{topTrack.genres.join(", ")}</p>
                                    </div>
                                    
                                </div>
                            )
                        })
                    }
                </div>
            </div>
        </div>
    )
}

export default Body

Code of my custom hook useDataLayer.js

import React, {useContext, createContext, useReducer} from 'react'

let DataContext = createContext();

export function DataLayer({reducer, initialState, children}) {
    return (
        <DataContext.Provider value= {useReducer(reducer, initialState)}>
            {children}
        </DataContext.Provider>
    )
}

export let useDataLayer = () => useContext(DataContext);

Thank you very much for your time and attention.

I’m not getting this warning. I was trying to do a react inventory management website. How can I solve this?? this warning is given below

react-dom.development.js:86 Warning: Cannot update a component (BrowserRouter) while rendering a different component (SocialLogin). To locate the bad setState() call inside SocialLogin, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at SocialLogin (http://localhost:3000/static/js/bundle.js:3002:130)
at div
at div
at div
at div
at Login (http://localhost:3000/static/js/bundle.js:2182:65)
at Routes (http://localhost:3000/static/js/bundle.js:82509:5)
at div
at App
at Router (http://localhost:3000/static/js/bundle.js:82442:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:81251:5)

window.open opens a browser page instead of a popup on discord (using BetterDiscord)

I’m trying to make a button that’ll Popout a webpage and run it from discord. I’m using BetterDiscord and making a plugin for it using JS. It works when I run it on an HTML page on my browser, but when I run it on discord, it opens a new tab onmy browser, instead of a popup. Does discord disable popups ?

const collection = document.getElementsByClassName("title-31SJ6t container-ZMc96U themed-Hp1KC_");

for (let i = 0; i < collection.length; i++) {
    collection[i].innerHTML += "<button onclick="window.open(window.location.href, 'Chat', 'popup=yes,location=no')">Popout Chat</button>";
}

React-map-gl geocoder marker showing else where on the webpage than the map

I’m currently working on this application for school assignment that uses react-map-gl to achieve our map feature. I tried to create a text entry box for location information as the example here : https://github.com/visgl/react-map-gl/tree/7.0-release/examples/geocoder/src. However, the marker and the text entry box appeared below the map instead of over it and the marker is floating all over the screen when I zoom in and out. I don’t see other people to have the same problem or solutions to it here so please help me out

homepage.js

<div id = "map">
      <Map
      initialViewState={{
        latitude: 47.662777,
        longitude: -122.313877,
        zoom: 14
      }}
      style={{height: 600}}
      mapStyle="mapbox://styles/fuwak0o0/cl2vqyhwn000n14tgci6txwby"
      mapboxAccessToken={MAPBOX_TOKEN}
      >
        <GeocoderControl mapboxAccessToken={MAPBOX_TOKEN} position="top-left" />
      </Map>
    </div>

GeocoderControl code (I basically copied and pasted the example):

import * as React from 'react';
import { useState } from 'react';
import { useControl, Marker } from 'react-map-gl';
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder';
/* eslint-disable complexity,max-statements */
export default function GeocoderControl(props) {
    const [marker, setMarker] = useState(null);
    const geocoder = useControl(() => {
        const ctrl = new MapboxGeocoder(Object.assign(Object.assign({}, props), { marker: false, accessToken: props.mapboxAccessToken }));
        ctrl.on('loading', props.onLoading);
        ctrl.on('results', props.onResults);
        ctrl.on('result', evt => {
            var _a;
            props.onResult(evt);
            const { result } = evt;
            const location = result &&
                (result.center || (((_a = result.geometry) === null || _a === void 0 ? void 0 : _a.type) === 'Point' && result.geometry.coordinates));
            if (location && props.marker) {
                setMarker(React.createElement(Marker, Object.assign({}, props.marker, { longitude: location[0], latitude: location[1] })));
            }
            else {
                setMarker(null);
            }
        });
        ctrl.on('error', props.onError);
        return ctrl;
    }, {
        position: props.position
    });
    // @ts-ignore (TS2339) private member
    if (geocoder._map) {
        if (geocoder.getProximity() !== props.proximity && props.proximity !== undefined) {
            geocoder.setProximity(props.proximity);
        }
        if (geocoder.getRenderFunction() !== props.render && props.render !== undefined) {
            geocoder.setRenderFunction(props.render);
        }
        if (geocoder.getLanguage() !== props.language && props.language !== undefined) {
            geocoder.setLanguage(props.language);
        }
        if (geocoder.getZoom() !== props.zoom && props.zoom !== undefined) {
            geocoder.setZoom(props.zoom);
        }
        if (geocoder.getFlyTo() !== props.flyTo && props.flyTo !== undefined) {
            geocoder.setFlyTo(props.flyTo);
        }
        if (geocoder.getPlaceholder() !== props.placeholder && props.placeholder !== undefined) {
            geocoder.setPlaceholder(props.placeholder);
        }
        if (geocoder.getCountries() !== props.countries && props.countries !== undefined) {
            geocoder.setCountries(props.countries);
        }
        if (geocoder.getTypes() !== props.types && props.types !== undefined) {
            geocoder.setTypes(props.types);
        }
        if (geocoder.getMinLength() !== props.minLength && props.minLength !== undefined) {
            geocoder.setMinLength(props.minLength);
        }
        if (geocoder.getLimit() !== props.limit && props.limit !== undefined) {
            geocoder.setLimit(props.limit);
        }
        if (geocoder.getFilter() !== props.filter && props.filter !== undefined) {
            geocoder.setFilter(props.filter);
        }
        if (geocoder.getOrigin() !== props.origin && props.origin !== undefined) {
            geocoder.setOrigin(props.origin);
        }
    }
    return marker;
}
const noop = () => { };
GeocoderControl.defaultProps = {
    marker: true,
    onLoading: noop,
    onResults: noop,
    onResult: noop,
    onError: noop
};

React native fetch state not updating?

    const [restaurantsData,setrestaurantsData]=useState([])
  useEffect(()=>{
    const getData = async () => {
    await fetch('http://localhost:5000/api/v1/res/')
      .then((response) => response.json())
      .then((json) => {setrestaurantsData(json.data),console.log(restaurantsData)})
      .catch((error) => console.error(error))
      .finally();
  };
getData();
console.log(id)
console.log("photo",restaurantsData.photo)
  },[])

 useEffect(()=>
 {
  for (const {type: t} of menuDetailedData) 
 { 
   routes.push({key:i,title:t})
   i++;
 }
 console.log("routes",routes)
let acc=[]
 for(let i=0; i<menuDetailedData.length-1;i++)
 {
  if(routes[i].title===routes[i+1].title)
  {
    acc.push(routes[i])
  }
}
setroutes(routes.filter(item => !acc.includes(item)))
console.log("acc",acc)

 },[]) 
 

The restaurant data in this code is always null. However I have same code in previous screen working perfectly fine. I dont know why the state is not updating the . May be useeffect is causing problem

Pop down using jquery does not revert to original when selection is changed

New to Jquery here.

When I click on anything that is 2 – Somewhat dissatisfied and below I want id=”section1a” to pop down. This part works.

However if I change my selection back to anything 3 – Neither satisfied nor dissatisfied and above I want the popped id=”section1a” to disappear. This isn’t working. Your help here is appreciated.

my form code

<div class="row" name="satisfaction">
          <div class="col-md-2 col-4">
            <label>
              <input type="radio" class="form-control my-2" name="overall_rate" value="5 - Very satisfied">5 - Very satisfied
            </label>
          </div>
          <div class="col-md-2 col-4">
            <label>
              <input type="radio" class="form-control my-2" name="overall_rate" value="4 - Somewhat satisfied">4 - Somewhat satisfied
            </label>
          </div>
          <div class="col-md-2 col-4">
            <label>
              <input type="radio" class="form-control my-2" name="overall_rate" value="3 - Neither satisfied nor dissatisfied">3 - Neither satisfied nor dissatisfied
            </label>
          </div>
          <div class="col-md-2 col-4">
            <label>
              <input type="radio" class="form-control my-2" name="overall_rate" value="2 - Somewhat dissatisfied">2 - Somewhat dissatisfied
            </label>
          </div>
          <div class="col-md-2 col-4">
            <label>
              <input type="radio" class="form-control my-2" name="overall_rate" value="1 - Very dissatisfied">1 - Very dissatisfied
            </label>
          </div>
          <div class="col-md-2 col-4">
            <label>
              <input type="radio" class="form-control my-1" name="overall_rate" value="Don't Know / Doesn't Apply"> Don't Know / Doesn't Apply
            </label>
          </div>
        </div>

        <div id="section1a" class="d-none"> 
          <h6 class="text-yellow mt-4"> 1a. Please can you indicate which area we could do better? *
          </h6>
          <div class="row">
            <div class="col-md-12">
              <label>
                <input type="checkbox" name="improvement" class="form-control invisible-radio" value="option 1" onclick="onlyOne(this)">
                <span class="card-selector">option 1</span>
              </label>
              <label>
                <input type="checkbox" name="improvement" class="form-control invisible-radio" value="option 2" onclick="onlyOne(this)">
                <span class="card-selector">option 2</span>
              </label>
              <label>
                <input type="checkbox" name="improvement" class="form-control invisible-radio" value="option 3" onclick="onlyOne(this)">
                <span class="card-selector">option 3</span>
              </label>
              <label>
                <input type="checkbox" name="improvement" class="form-control invisible-radio" value="option 4" onclick="onlyOne(this)">
                <span class="card-selector">option 4</span>
              </label>
              </div>
          </div>
        </div>

Jquery

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

 $('[name=satisfaction]').change(e=>{
const value=$(e.target).val();
    if(value!='5 - Very satisfied'){
      if(value!='4 - Somewhat satisfied'){
       if(value!='3 - Neither satisfied nor dissatisfied'){
          $('#section1a').removeClass('d-none');
        }
        else {
          $('#section1a').addClass('d-none');
          $('#section1a [type=radio]').prop('checked',false).trigger('change');
               }
  }
                                 );

Updating data in react with graphQl

So I have a react component with input select, which is located in my header:

import { useState } from "react";
function ChangeCurrency(){
   const [selectValue, setSelectValue] = useState("USD");
   function changeSelectValue(event) {
     setSelectValue(event.target.value);
     }
    return (
      <select
        name="currencies"
        id="currencies"
        className={classes.changeCurrency}
        value={selectValue}
        onChange={changeSelectValue}
      >
        <option value="USD">$USD</option>
        <option value="GBP">£GBP</option>
        <option value="AUD">A$AUD</option>
        <option value="JPY">¥JPY</option>
        <option value="RUB">₽RUB</option>
      </select>
    );
}

and another component with products, which is in main content:

import Products from "./Products";
import {
  useQuery,
  gql,
} from "@apollo/client";
function ProductsAll(){
const GET_PRODUCTS = gql`
  query {
    category(input: { title: "all" }) {
      name
      products {
        id
        name
        gallery
       prices {
          currency {
            label
            symbol
          }
          amount
        }
      }
    }
  }
`;
      const{loading,error,data} = useQuery(GET_PRODUCTS)
      if(loading){
          return <div>loading...</div>
      }
      if(error){
          return<div>error..</div>
      }
      return (
        <Products data={data}/>
      );
    }
    export default ProductsAll;

I have a few categories so doing everything in one app.js isn`t an option(
how can I update data of second element with select changing?

Undefined when trying to send data to server nodeJS

I’m trying to send data to my server so that I can work with external API. I’m learning now slowly so please forgive for my noobness 🙂
In the code below I converted the elements of an array into a base64 strings (solution).
These strings are the ones I would like to send to the server with fetch, however the node server returned UNDEFINED. I suppose I’m wrong in some kind of process (read about async/await etc)… Could someone help me out? Thanks a lot.

NODEJS:

app.post("/upload",upload.any(),(req,res)=>{
console.log(req.files)
res.setHeader("Access-Control-Allow-Origin","*")
res.end("Done.")
});

CLIENT SIDE:
function getBase64(item,index,arr) {
let reader = new FileReader();
reader.readAsDataURL(item);
reader.onload = function(e) {
var rawLog = reader.result; // DataURL - rawLog
var solution = rawLog.split("base64,")[1]; //Rimozione parte prima di base64 
//  console.log(solution);
//  console.log(rawLog);
fetch("http://localhost:3000/upload",{
method:'post',
mode: 'no-cors',

body:solution

}).catch(console.error);
return reader.result;
};}
  

Trying to fetch from API but getting [object Promise] instead

I’m trying to make a website that fetches a random 10 lines from a poem and then outputs them in the HTML file but instead of getting the .json data I’m getting [object Promise]. Can someone help me out?

Here’s my code:

JS:

let url = 'https://poetrydb.org/random,linecount/1;10/title,author,lines.json'
const button = document.getElementById('button')
const body = document.getElementById('poem')

async function requestPoem(url) {
    await fetch(url)
    .then((response)=>{
        let data = response.json()
        return data
    })
}

button.onclick = ()=>{
    body.innerHTML = requestPoem(url)
}

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">
    <script defer src="scripts/main.js"></script>
    <title>poem request</title>
</head>
<body>
    <p id="poem"></p>
    <button id="button">request poem</button>
</body>
</html>

Getting Null From MongoDB

Why my Code Giving me Null

async function run() {
  try {
    await client.connect();

    const productsCollection = client.db("inventory").collection("items");

    // Get All Products
    app.get('/products', async (req, res) => {
      const query = {};
      const cursor = productsCollection.find(query);
      const products = await cursor.toArray();
      res.send(products);
    });

    // Get Single Product
    app.get('/products/:id', async (req, res) => {
      const id = req.params.id;
      console.log(id);
      const query = {_id: ObjectId(id)};
      const product = await productsCollection.findOne(query);
      res.send(product);
    })
  } 
  finally {
    
  }
}
run().catch(console.dir);

I do not understand why Null is showing?
And there is no error in giving products /id
And It doesn’t even showing anything
And this error is showing in the front end console

Create a XML DOM in OSB with JavaScript

JSON Requet
{"value":[{"bairro":"A Noite","codigoIBGE":3304144},{"bairro":"Albuquerque","codigoIBGE":3304144},{"bairro":"Aliança","codigoIBGE":3304144}]}

JavaScript action

var bairro = "<bairros>"; 
for( i = 0; i < process.body.value.length; i++ ){ 
  bairro += "<bairro>" + process.body.value[i].bairro + "</bairro>" 
}
process.bairros = bairro + "</bairros>"

How can i transform this XML string to an Object to replace my Response Body ?
On OSB 12c this code doesn’t work.

parser = new DOMParser();
xmlDoc = parser.parseFromString(bairro, "text/xml");

Log: ReferenceError: “DOMParser” is not defined. (#6)