Can I focus on learning two languages at a time

I need to learn python and Javascript course at the in a span of 4 months, is it possible, ensuring I grasp as much as possible in both

Am not sure I can but I wanna give it a shot. Anyone please give some advice on this, I have focused on html css, and digital marketing and have gone well, but this is different because they are more technical.

Creating a playlist that can be controlled via Bluetooth earphone in HTML

I want to control the audio files these I added to my html page according to the commands I send from my Bluetooth earphone, but I could not find how to do this. What I mean is, I want to move on to the next or previous audio like on YouTube, is there a way to do this?

I added a few audio files to my page and tried to control them with my earphone. I can play and pause them with my earphone, but I cannot play the next or previous song.
Thank you all

Does a code transformer / formatter exist that will add curly braces to Typescript code

I want all the code in our repository to always use blocks enclosed with brackets for the clauses of if statements, loops and even for inline functions. The following code is banned:

const func = () => doSomething();

It should be converted to:

const func = () => {
  return doSomething();
};

It’s personal preference, of course, but I think if only the latter is checked in, then diffs are easier to read, it’s easier to add and remove debug logging, and you are less likely to accidentally check in changes that have no impact on the logic.

Prettier won’t do this, it is considered beyond its scope. But there must be some tools that do it. I’ve done google searches but found nothing.

How to call functions from a JavaScript file in HTML

Ive been trying to link my three.js function into html so that when an element is clicked by the mouse the js function runs in the external js file. I thought i had done everything right and followed correct steps but still wont work

I’ve tried modifying the directories for librarys and external files and moving the script tag to see if it changes anything but its the kinda thing thats meant to work but it wont so i have run out of solutions.

Ive got the js file in the same folder and i am certain the function is named correctly

<!DOCTYPE html>
<html>

<head>

  <title> Solar System </title>
  <style>
    body {
      margin: 0;
    }

    canvas {
      width: 100%;
      height: 100%
    }
  </style>
</head>

<body>
  <script type="module" src="./index.js"> </script>

  <link href="./styles.css" rel="stylesheet" />
  <script src="js/threex.domevents.js"></script>
  <script src="./js/three.module.js"></script>
  <script src="./js/threex.linkify.js"></script>


  <div id="planet-menu">
    <ul>
      <li onclick="selectPlanet('Mercury')">Mercury</li>
      <li onclick="selectPlanet('Venus')">Venus</li>
      <li onclick="selectPlanet('Earth')">Earth</li>
      <li onclick="selectPlanet('Mars')">Mars</li>
      <li onclick="selectPlanet('Jupiter')">Jupiter</li>
      <li onclick="selectPlanet('Saturn')">Saturn</li>
      <li onclick="selectPlanet('Uranus')">Uranus</li>
      <li onclick="selectPlanet('Neptune')">Neptune</li>
    </ul>
  </div>



  <script type="module" src="./index.js "> </script>


</body>

</html>

function does not wait for a return in JS

I am creating an electron app and having a problem making the following function work step by step without jumping to the following procedure.

Note: I have already solved this issue by making a function for each step and calling it as a callback function. I want to know why my original code didn’t work at all.

Code:

ipc.on("build.buildInstallEnv"), async (e,fpath) => {
   if (e) console.error(`Unexpected error occurs: ${e}`)
   await check_filePath(fpath) // this print "file deleted:" message
   console.log("last message")
}

function check_filePath(fpath) {
   fs.promises.readdir(fpath, (err, files) => {
     if (err) return;
     if (files.length === 0) return;
     const fFormat = ['file.jpg', 'file.png', 'file.bmp']
     fFormat.map((f) => {
       if (files.filter(x => x.match(new RegExp(`/${f}/`)))) {
         fs.unlink(fpath + f, (f) => {
           console.log(`file deleted: ${f}`)
         })
       }
     })
   }
}

Expected result:

file deleted: file.jpg
file deleted: file.png
file deleted: file.bmp
last message

Actual result:

last message
file deleted: file.jpg
file deleted: file.png
file deleted: fiile.bmp

Injecting React components into webpages using content scripts in browser extensions

I am creating a React-based browser extension and I am trying to inject a React component into webpages using content scripts. However, it seems like using React or ReactDOM prevents the content script from loading. Is there any to get around this issue?

This is the code that I currently have. It seems like the content script only loads when React and ReactDOM is not used since nothing is logged to the console.

import NavBar from "./NavBar";
import React from 'react';
import ReactDOM from 'react-dom';

console.log('Content script is running');

const container = document.createElement('div');
document.body.appendChild(container);
ReactDOM.render(<NavBar />, container);

Google Maps context menu example doesn’t work

I have been searching for way to incorporate a context menu n my Google maps application. Unfortunately many of the examples my search has uncovered are old and many links are no longer valid. This is true of this link Google maps marker custom context menu

I did find an example example that I could get to work but making it usable could get a bit messy: Here is the working html example (with my APIKEY obscured).

<!DOCTYPE html>
<html>
<script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initialize"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var map;
function initialize() {
            var latlng = new google.maps.LatLng(51.47,-0.025956);
            var myOptions = {
              zoom: 12,
              center: latlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, "rightclick",function(event){showContextMenu(event.latLng);});
google.maps.event.addListener(map, "click",function(event){closeContextMenu();});

 }
function getCanvasXY(caurrentLatLng){
      var scale = Math.pow(2, map.getZoom());
     var nw = new google.maps.LatLng(
         map.getBounds().getNorthEast().lat(),
         map.getBounds().getSouthWest().lng()
     );
     var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
     var worldCoordinate = map.getProjection().fromLatLngToPoint(caurrentLatLng);
     var caurrentLatLngOffset = new google.maps.Point(
         Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
         Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
     );
     return caurrentLatLngOffset;
  }
  function setMenuXY(caurrentLatLng){
    var mapWidth = $('#map_canvas').width();
    var mapHeight = $('#map_canvas').height();
    var menuWidth = $('.contextmenu').width();
    var menuHeight = $('.contextmenu').height();
    var clickedPosition = getCanvasXY(caurrentLatLng);
    var x = clickedPosition.x ;
    var y = clickedPosition.y ;

     if((mapWidth - x ) < menuWidth)
         x = x - menuWidth;
    if((mapHeight - y ) < menuHeight)
        y = y - menuHeight;

    $('.contextmenu').css('left',x  );
    $('.contextmenu').css('top',y );
    };
  function showContextMenu(caurrentLatLng  ) {
        var projection;
        var contextmenuDir;
        projection = map.getProjection() ;
        $('.contextmenu').remove();
            contextmenuDir = document.createElement("div");
          contextmenuDir.className  = 'contextmenu';
          contextmenuDir.innerHTML = "<a id='menu1'><div class=context onclick=click1()>menu item 1</div></a><a id='menu2'><div class=context onclick=click2()>menu item 2</div></a>";
        $(map.getDiv()).append(contextmenuDir);

        setMenuXY(caurrentLatLng);

        contextmenuDir.style.visibility = "visible";
       }

    function closeContextMenu()
    {
       $('.contextmenu').remove();
    }
    function click1()
    {
     alert("click 1");
    }
    function click2()
    {
     alert("click 2");
    }

$(document).ready(function(){
initialize();

});
</script>

<style type="text/css">
html { height: 100%; }
body { height: 100%; margin: 0; padding: 0 }

#map_canvas{
    height: 100%;
}
.contextmenu{
    visibility:hidden;
    background:#ffffff;
    border:1px solid #8888FF;
    z-index: 10;
    position: relative;
    width: 140px;
}
.contextmenu div{
    padding-left: 5px
    }
</style>
Rightclick below to show context menu.
<div class="formDiv" id="map_canvas"></div>

</html>

Where it gets messy is at the line ‘contextmenuDir.innerHTML =’. Rather than expanding on how to dynamically provide menu items, I decided to search further. I located a project in github that appeared to be what I was looking for. However, the project was a fork of another project that turns out to be no longer valid. Thus, there is no detail about the html requirements. So, I created an html file and downloaded the contextmenu.js file and the rest of the example javascript code and tried it. The example references an apikey.js file which looks like this:

var apikey2  = "..........................."; // API key 3
console.log("api keys loaded");

My test4.htm file:

<!DOCTYPE html>
<html>
  <head>
  <meta name="viewport" content="initial-scale=1.0" user-scalable="yes" />
  <style type="text/css">
    html { height: 100%; }
    body { height: 100%; margin: 0; padding: 0 }
    #map { height: 100%; }

    .menu {
      background-color: rgb(255, 255, 255);
      border: 2px solid rgb(255, 255, 255);
      border-radius: 3px;
      box-shadow: rgba(0, 0, 0, 0.3) 0px 2px 6px;
      cursor: pointer;
      font-size: 1rem;
      text-align: center;
      color: #0d1f49;
      width: 20vw;
      margin: 2px;
      }
</style>

<title>Simple Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- playground-hide -->
    <script src="apikey.js"> </script>
    <!--script>
      const process = { env: {} };
      process.env.GOOGLE_MAPS_API_KEY =
        apikey2;
    </script-->
    <!-- playground-hide-end -->

    <!--link rel="stylesheet" type="text/css" href="./style.css" /-->
  </head>
  <body>
    <div id="map"></div>
    <div id="menu"></div>
    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: apikey2, v: "weekly"});</script>
    <script src = "./test4.js"></script>
    <!--script  src="./contextmenu.js"></script-->
  </body>
</html>

And the test4.js file which has the javascript code.

var map; //google.maps.Map;
//$(document).ready(function() {
//  initMap();
//});

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  console.log("initMap start");

  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });

    /*
            google.maps.ContextMenu v1.0

            A context menu for Google Maps API v3
            http://code.martinpearman.co.uk/googlemapsapi/google.maps.ContextMenu/

            Copyright Martin Pearman
            Last updated 21st November 2011

            [email protected]

            This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

            This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

            You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
        */
    google.maps.ContextMenu = function(map, options, callback) {
        options = options || {};
        this.setMap(map);
        this.classNames_ = options.classNames || {};
        this.map_ = map;
        this.id = options.id;
        this.mapDiv_ = map.getDiv();
        this.menuItems_ = options.menuItems || [];
        this.pixelOffset = options.pixelOffset || new google.maps.Point(10, -5);
        this.callback = callback || null;
        this.eventName = options.eventName || 'menu_item_selected';

        /**
         * [createMenuItem description]
         * @param  {Object} itemOptions An object with a label (required), a className (optional) and an id (optional)
         * @param  {Boolean} before when True, the menuitem is prepended to the menu instead of appended.
         */
        this.createMenuItem = function(itemOptions, before) {
            var self = this;
            if (!self.menu_) {
                console.log('No menu');
                return;
            }
            itemOptions = itemOptions || {};
            var menuItem = document.createElement('div');
            menuItem.innerHTML = itemOptions.label;
            menuItem.className = itemOptions.className || self.classNames_.menuItem;
            menuItem.eventName = itemOptions.eventName || self.eventName;
            if (itemOptions.id) {
                menuItem.id = itemOptions.id;
            }
            menuItem.style.cssText = 'cursor:pointer; white-space:nowrap';

            menuItem.onclick = function() {
                google.maps.event.trigger(self, menuItem.eventName, self.position_, itemOptions.eventName);
            };
            if (before) {
                self.menu_.insertBefore(menuItem, self.menu_.firstChild);
            } else if (itemOptions.container_id) {
                document.getElementById(itemOptions.container_id).appendChild(menuItem);
            } else {
                self.menu_.appendChild(menuItem);
            }

        };


        /**
         * [createMenuGroup description]
         * @param  {Boolean} before when True, the menugroup is prepended to the menu instead of appended.
         */
        this.createMenuGroup = function(itemOptions, before) {
            var self = this;
            if (!self.menu_) {
                console.log('No menu');
                return;
            }
            itemOptions = itemOptions || {};
            var menuGroup = document.createElement('span');

            if (itemOptions.id) {
                menuGroup.id = itemOptions.id;
            }
            if (before) {
                self.menu_.insertBefore(menuGroup, self.menu_.firstChild);
            } else {
                self.menu_.appendChild(menuGroup);
            }
        };


        /**
         * [createMenuSeparator description]
         * @param  {Boolean} before when True, the menuitem is prepended to the menu instead of appended.
         */
        this.createMenuSeparator = function(itemOptions, before) {
            var self = this;
            if (!self.menu_) {
                console.log('No menu');
                return;
            }
            itemOptions = itemOptions || {};
            var menuSeparator = document.createElement('div');
            if (self.classNames_.menuSeparator) {
                menuSeparator.className = self.classNames_.menuSeparator;
            }
            if (itemOptions.id) {
                menuSeparator.id = itemOptions.id;
            }
            if (before) {
                self.menu_.insertBefore(menuSeparator, self.menu_.firstChild);
            } else if (itemOptions.container_id) {
                document.getElementById(itemOptions.container_id).appendChild(menuSeparator);
            } else {
                self.menu_.appendChild(menuSeparator);
            }
        };
    };

    google.maps.ContextMenu.prototype = new google.maps.OverlayView();

    google.maps.ContextMenu.prototype.draw = function() {

        if (this.isVisible_) {
            var mapSize = new google.maps.Size(this.mapDiv_.offsetWidth, this.mapDiv_.offsetHeight);
            var menuSize = new google.maps.Size(this.menu_.offsetWidth, this.menu_.offsetHeight);
            var mousePosition = this.getProjection().fromLatLngToDivPixel(this.position_);

            var left = mousePosition.x;
            var top = mousePosition.y;

            if (mousePosition.x > mapSize.width - menuSize.width - this.pixelOffset.x) {
                left = left - menuSize.width - this.pixelOffset.x;
            } else {
                left += this.pixelOffset.x;
            }

            if (mousePosition.y > mapSize.height - menuSize.height - this.pixelOffset.y) {
                top = top - menuSize.height - this.pixelOffset.y;
            } else {
                top += this.pixelOffset.y;
            }

            this.menu_.style.left = left + 'px';
            this.menu_.style.top = top + 'px';
        }
    };

    google.maps.ContextMenu.prototype.getVisible = function() {
        return this.isVisible_;
    };

    google.maps.ContextMenu.prototype.hide = function() {
        if (this.isVisible_) {
            this.menu_.style.display = 'none';
            this.isVisible_ = false;
        }
    };



    google.maps.ContextMenu.prototype.onAdd = function() {

        var $this = this; //    used for closures

        var menu = document.createElement('div');
        if (this.classNames_.menu) {
            menu.className = this.classNames_.menu;
        }
        if (this.id) {
            menu.id = this.id;
        }
        menu.style.cssText = 'display:none; position:absolute;z-index:250;';
        $this.menu_ = menu;
        for (var i = 0, j = this.menuItems_.length; i < j; i++) {
            if (this.menuItems_[i].label) {
                this.createMenuItem(this.menuItems_[i]);
            } else {
                this.createMenuSeparator();
            }
        }
        menu.onmouseover = function() {
            $this.map_.inmenu = true;
            //console.log('Mouseover Menu');
        };
        menu.onmouseout = function() {
            $this.map_.inmenu = false;
            //console.log('mouseout Menu');
        };
        //delete this.classNames_;
        delete this.menuItems_;

        this.isVisible_ = false;

        this.position_ = new google.maps.LatLng(0, 0);

        google.maps.event.addListener(this.map_, 'click', function(mouseEvent) {
            $this.hide();
        });
        this.getPanes().floatPane.parentNode.parentNode.appendChild(menu);

        if (this.callback) this.callback();
    };

    google.maps.ContextMenu.prototype.onRemove = function() {
        this.getPanes().floatPane.appendChild(this.menu);
        this.menu_.parentNode.removeChild(this.menu_);
        delete this.mapDiv_;
        delete this.menu_;
        delete this.position_;
    };

    google.maps.ContextMenu.prototype.show = function(latLng) {
        if (!this.isVisible_) {
            this.menu_.style.display = 'block';
            this.isVisible_ = true;
        }
        this.position_ = latLng;
        this.draw();

    };

    var menuStyle = {
            menu: 'context_menu',
            menuSeparator: 'context_menu_separator',
            menuItem: 'context_menu_item'
        };

        var contextMenuOptions  = {
            id: "map_rightclick",
            eventName: "menu_item_selected",
            classNames: menuStyle,
            menuItems:
            [
               {label:'option1', id:'menu_option1'},
               {label:'option2', id:'menu_option2'},
            ]
        };
    var contextMenu = new google.maps.ContextMenu(map, contextMenuOptions, function() {
          console.log('optional callback');
    });
    google.maps.event.addListener(map, 'contextmenu', function(mouseEvent) {
        console.log("contextmenu clicked");
      contextMenu.show(mouseEvent.latLng);
    });
    console.log("initMap done");
  }

initMap();
//export {};

However, loading the test5.htm file in my browser creates a google maps but no context menu. I presume that it doesn’t work because the html file is missing a div and/or some style info. I think the div sgold have a classname referred to as ‘container_id’ but I don’t now what it is looking for. I need somebody who understands this all to help me figure out what to fix.

How to have dynamic variables in config.json in next JS

I’d like to build a config.json file where I can put some variable like a title or a color hex and much more.

My web app in next js have to take the confing befor mount his component and I’d like to have a setting page for modify the variables as we want in the app.
The app should re render the components when a variable change.

How could I do this ?

I tried nothing for the moment, I don’t know what is the best. Use a config.json file with a context and some api call. Use the local storage ?

Using React with routing and redux

I recently learned how to use the module “react-router-dom” for SPA routing. Before learning this, I learned how to use redux. I wonder if the two can be used together.
For example:

import React from 'react';
import { useLoaderData } from 'react-router-dom';

function HomePage(props) {
    const weather = useLoaderData();
    const weatherToday = weather.timelines.daily[1];
    console.log(weatherToday);
    return (
        <div>
            
        </div>
    );
}

export default HomePage;


export const loader = async () => {

    const response = await fetch("https://api.tomorrow.io/v4/weather/forecast?location=paris&apikey=random");
    const data = await response.json();
    return data;
};

Let’s say for this code.
In the loader I fetch some data from an API.
Could I instead of returning the data, dispatch it into my store somehow? Or is it redundant?
I want to learn how to use redux with routing basically.

Click a Button Issue [clickButton is not a function] [discord.js-selfbot-v13]

const { Client, clickButton } = require('discord.js-selfbot-v13');
const client = new Client({
    checkUpdate: false,
});

client.on('ready', async () => {
    const channelId = '1190781950944886870';
    const channel = client.channels.cache.get(channelId);
  
    if (channel) {
      console.log(`Channel found: ${channel.name}`);
      const message_id = await channel.sendSlash('999736048596816014', 'config channel', channelId);
      console.log('Slash Command Sent! | '+message_id)
      await message_id.clickButton()
    } else {
      console.error('Channel not found.');
    }
  });

client.login('my token');

Error:

await message_id.clickButton()
                       ^

TypeError: message_id.clickButton is not a function

I don’t know why it says that .clickButton is not an function, the Docs say otherwise…

Clicking in random time durations to a button with Chrome extension

I am creating a chrome extension to calculate the time range based on the user input and press the button on the webpage. For an example; user enters the duration as 5 minutes. The program sets the lower boundary as duration-1 (4), upper boundary as duration+1 (6). And it will randomly create a time duration (example 4 mins 23 secs.). So far it is randomly pressing the button but when I test the durations its not matching. Sometimes it is pressing completely random, not with the calculated random duration. So, I am confused. What am I doing wrong? I think my math is correct for calculating the duration but not sure..


function startClicking(duration) {
    const userDuration = duration || 5; // Default user input is 5 if no duration is provided
    
    const lowerBoundary = Math.max(1, userDuration - 1); // Ensure lower boundary minimum is 1
    const upperBoundary = userDuration + 1; // Upper boundary (6)
  
    clickTargetButton(); // Click the button immediately
  
    setTimeout(function clickWithRandomDuration() {
      const randomizedMinutes = Math.floor(Math.random() * (upperBoundary - lowerBoundary)) + lowerBoundary;
      const randomizedSeconds = Math.floor(Math.random() * 60);
      const randomizedDuration = randomizedMinutes * 60 * 1000 + randomizedSeconds * 1000;
  
      clickTargetButton(); // Click the button after the randomized duration
      console.log(`Randomized/Next click in: ${randomizedMinutes} minutes ${randomizedSeconds} seconds`);
  
      setInterval(clickWithRandomDuration, randomizedDuration);
    }, userDuration * 60 * 1000); // Initial delay for the first random click
  }

remove part of a string in JavaScript [duplicate]

I have a string returned from a source that could be …

'an unknown char count (more chars here of however many) then some more chars of unknown count'

I want to remove anything inside the ( ) including the brackets, anything before and after need to stay, which method will give me that result?

Tried a few ideas but getting nowhere

Can’t read properties of null for Spotify.Player

I am currently working on a project which uses the Spotify Web API and their Playback SDK. I was following their How-To tutorials through the documentation but keep running into errors. I have tried finding answers online but I can not find my specific problem.

I am creating my app in React and this is what the WebPlayback component looks like.

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

const track = {
    name: "",
    album: {
        images: [
            { url: "" }
        ]
    },
    artists: [
        { name: "" }
    ]
}

function WebPlayback(props) {

    const [is_paused, setPaused] = useState(false);
    const [is_active, setActive] = useState(false);
    const [player, setPlayer] = useState(undefined);
    const [current_track, setTrack] = useState(track);

    useEffect(() => {

        const script = document.createElement("script");
        script.src = "https://sdk.scdn.co/spotify-player.js";
        script.async = true;

        document.body.appendChild(script);

        window.onSpotifyWebPlaybackSDKReady = () => {

            const player = new window.Spotify.Player({
                name: 'Web Playback SDK Quick Start Player',
                getOAuthToken: cb => { cb(props.token); }
            });
            setPlayer(player);

            player.addListener('ready', ({ device_id }) => {
                console.log('Ready with Device ID', device_id);
            });

            player.addListener('not_ready', ({ device_id }) => {
                console.log('Device ID has gone offline', device_id);
            });

            player.addListener('player_state_changed', ( state => {

                console.log(player)

                if (!state) {
                    return;
                }

                setTrack(state.track_window.current_track);
                setPaused(state.paused);

                player.getCurrentState().then( state => {
                    (!state)? setActive(false) : setActive(true)
                });

            }));

            player.connect();

        };
    }, []);

    if (!is_active) {
        return (
            <>
                <div className="container">
                    <div className="main-wrapper">
                        <b> Instance not active. Transfer your playback using your Spotify app </b>
                    </div>
                </div>
            </>)
    } else {
        console.log(player)
        return (
            <>
                <div className="container">
                    <div className="main-wrapper">

                        <img src={current_track.album.images[0].url} className="now-playing__cover" alt="" />

                        <div className="now-playing__side">
                            <div className="now-playing__name">{current_track.name}</div>
                            <div className="now-playing__artist">{current_track.artists[0].name}</div>
                            <button className="btn-spotify" onClick={() => { player.previousTrack() }} >
                                &lt;&lt;
                            </button>

                            <button className="btn-spotify" onClick={() => { player.togglePlay() }} >
                                { is_paused ? "PLAY" : "PAUSE" }
                            </button>

                            <button className="btn-spotify" onClick={() => { player.nextTrack() }} >
                                &gt;&gt;
                            </button>

                        </div>
                    </div>
                </div>
            </>
        );
    }
}

export default WebPlayback

The error that is happening is some of the functions are not working because React sees them as null.

My hypothesis is that React is not actually setting my state variable to be the Spotify.Player Object.
For instance if I change the name of the variable from player to temp I get a “cannot read properties of undefined” Error, when I try and call the first .addListener() function.

type window.onSpotifyWebPlaybackSDKReady = () => {

            const **temp** = new window.Spotify.Player({
                name: 'Web Playback SDK Quick Start Player',
                getOAuthToken: cb => { cb(props.token); }
            });
            setPlayer(**temp**);

            player.addListener('ready', ({ device_id }) => {
                console.log('Ready with Device ID', device_id);
            });

            player.addListener('not_ready', ({ device_id }) => {
                console.log('Device ID has gone offline', device_id);
            });

            player.addListener('player_state_changed', ( state => {

                console.log(player)

                if (!state) {
                    return;
                }

                setTrack(state.track_window.current_track);
                setPaused(state.paused);

                player.getCurrentState().then( state => {
                    (!state)? setActive(false) : setActive(true)
                });

            }));

            player.connect();

        };here

This to me looks like it is not setting my player variable but I don’t know why it would do that. I haven’t worked much in React and am fairly new to API’s so any help would be appreciated!

Thanks in advanced!

What does //# mean and do?

I’ve found some code with this in it, //# what does it mean or do? Any kind of documents or guidance on it would be much appreciated because I’ve looked around and can’t really find it.

I’ve tried googling it and searching the web.