How to change a className of a particular element based off it’s child input value and input dataset comparison?

It’s my first time posting – hello everyone!

I’m making an app that’s going to help me memorize geographical data.

I have a map with markers on it, when I click on any of these markers a popup appears in which I have an input. I’m comparing the input value with input dataset to see if my answer was correct or not. The thing is, I would also like to change the color of the marker (ImageOverlay) to green as soon as my answer is correct and red if it’s wrong (as soon as any value appears).

The main problem I have is that those markers are mapped from an object which is fetched from firebase, meaning that every single input has to change the color of the corresponding marker and that marker only.

I hope I explained it clearly. Thank you so much in advance!

displayPins that maps data from a firebase doc:

 const displayPins = doc.map((d) => {
return (
  <ImageOverlay
    className="img-overlay"
    key={d.id}
    bounds={[
      [d.latitude - 2, d.longitude - 2],
      [d.latitude + 2, d.longitude + 2],
    ]}
    interactive={true}
    url={`./${d.shape}`}
  >
    <Popup>
      <input type="text" data-tag={d.name} onChange={valueCompare}></input>
      <button
        onClick={() => {
          console.log(test);
        }}
      ></button>
    </Popup>
  </ImageOverlay>
);});

Input’s onChange:

const valueCompare = (e) => {
const data = e.target.dataset.tag;
const value = e.target.value;
if (data != value) {
  console.log("WRONG");
} else {
  console.log("CORRECT");
}};

CSS

.img-overlay {
  filter: brightness(0) saturate(100%);
}
.img-overlay-wrong {
  filter: invert(10%) sepia(95%) saturate(7496%) hue-rotate(11deg)
    brightness(97%) contrast(120%);
}
.img-overlay-correct {
  filter: invert(69%) sepia(61%) saturate(4725%) hue-rotate(78deg)
    brightness(112%) contrast(128%);
}

How to stop collide2D from detecting p5.js

I am using the collide2D library in p5.js to detect if my player hits an obstacle. If it does, i wantthe player to have 1 less lives. The problem i’ve run in to is that when i hit an obstacle it keeps removing lives for the whole time i hover over it so i end up with -100 lives when i hover over the whole obstacle.

Code in class Rock(my obstacle):

    isColliding(obj) {
      let hit = collideRectCircle(obj.x - 55, obj.y - 60, 105, 109, this.x, this.y, 130);
      return hit;
    }

code in draw:

  for (let i = 0; i < rocks.length; i++) {
    if (rocks[i].isColliding(unicorn)) {
      lives -= 1
      // if (lives <= 0) {
      //   gameOver();
      // }
    }

Select option change ‘Formation’

I’m building a Football Team Builder with 5 players per team. The idea is to have a select element with the options Formation 1: 1-1-2, Formation 2: 1-2-1, and Formation 3: 2-1-1 (Goalkeepers are not included in the formation).

I build it in a grid with divs of 3×3. See the table as an example:

Attacker 1 Attacker 2 Attacker 3
Midfielder 1 Midfielder 2 Midfielder 3
Defender 1 Defender 2 Defender 3

Now if I select Formation 1: 1-1-2, I only want to display the players according to the selected Formation. That should look like this:

Attacker 1 Attacker 3
Midfielder 2
Defender 2

How can I accomplish this for every Select Option with javascript?

CODE

<label for="formation"> Formation </label>
<select id="formation" name="formation">
  <option value="1"> 1-1-2 </option> <!-- 2 Attackers-->
  <option value="2"> 1-2-1 </option> <!-- 2 Midfielders-->
  <option value="3"> 2-1-1 </option> <!-- 2 Defenders-->
</select>

<div class="attackers">
  <div class="card" id="attacker_1"> Attacker 1 </div>
  <div class="card" id="attacker_2"> Attacker 2 </div>
  <div class="card" id="attacker_3"> Attacker 3 </div>
</div>

<div class="midfielders">
  <div class="card" id="midfielder_1"> Midfielder 1 </div>
  <div class="card" id="midfielder_2"> Midfielder 2 </div>
  <div class="card" id="midfielder_3"> Midfielder 3 </div>
</div>

<div class="defenders">
  <div class="card" id="defender_1"> Defender 1 </div>
  <div class="card" id="defender_2"> Defender 2 </div>
  <div class="card" id="defender_3"> Defender 3 </div>
</div>

Here is my JSFiddle: https://jsfiddle.net/dnf7a9c0/4/

GAPI Export to Google Sheet Invalid Argument Error

I’m trying to export details from out app into a google sheet and am getting an “Invalid argument” error. I’m trying to take the data from the page and also grab users’ birthdays on export. We use firestore as a db.

exportStaff(shift) {
      console.log(shift)
      const exportHeaders = [
        "Day",
        "Event",
        "Position",
        "Start",
        "End",
        "First Name",
        "Last Name",
        "Phone",
        "Email",
        "Confirmed",
        "DOB",
        "Code",
      ];
      const exportItems = [];
      for (var key in this.orderedPlacedUsers2(shift.id)) {

        function myDOB(staff) {
          return fb.usersCollection.doc(staff).get()
          .then(doc => {
            console.log(doc.data().dob)
            return doc.data().dob
          })
        }

        exportItems.push([
          shift.day,
          shift.event,
          shift.position.title,
          shift.startTime,
          shift.endTime,
          this.orderedPlacedUsers2(shift.id)[key].firstName,
          this.orderedPlacedUsers2(shift.id)[key].lastName,
          this.orderedPlacedUsers2(shift.id)[key].phone,
          this.orderedPlacedUsers2(shift.id)[key].email,
          this.orderedPlacedUsers2(shift.id)[key].confirmed,
          myDOB(this.orderedPlacedUsers2(shift.id)[key].userId),
          `=REGEXEXTRACT(H2,"....$")`
        ])
      }
     
      this.$gapi.getGapiClient().then(gapi => {
        const exportService = new ExportService(exportHeaders, Object.values(exportItems), gapi);
        exportService.export();
      });
    },

All of the birthdays are logging correctly to the console, but no values show on the sheet.

Here is a screenshot of the error in the console.

enter image description here

How can I get the birthdays (DOB) to export properly?

How to search for a specific value in an array of objects

I want to make my code render the data when i search for a value, tried it by using for, but it keeps showing unexpected token. Is there any way to do it properly? It may be an easy question but i don’t really know how to make this work.

export default function SelecionaRota() {
    const rota = {
        locais: [
            {
                nome: 'Rio de Janeiro',
                rotas: [
                    {
                        nome: 'RJ-SP',
                        valor: 1200
                    },
                    {
                        nome: 'RJ-BSB',
                        valor: 1400
                    }
                ]
            },
            {
                nome: 'São Paulo',
                rotas: [
                    {
                        nome: 'SP-RJ',
                        valor: 1200
                    },
                    {
                        nome: 'SP-BSB',
                        valor: 1400
                    }
                ]
            }
        ]
    }
    const location = useLocation()
    const { estadoOrigem } = location.state
    return (
        <div>
            <h1>{estadoOrigem}</h1>
            {for (var i = 0;i < rota.locais.length;i++) {
                if (estadoOrigem === rota.locais[i].nome) {
                    rota.locais[i].rotas.map(module => (
                        <>
                            <h1>{module.nome}</h1>
                            <h2>{module.valor}</h2>
                        </>
                    ))
                }
            }}
        </div>
    )
}

Error:

./src/pages/Rota.js
SyntaxError: D:Arquivos1 Estágio Testeaeroporto-testesrcpagesRota.js: Unexpected token (39:13)

  37 |         <div>
  38 |             <h1>{estadoOrigem}</h1>
> 39 |             {for (var i = 0;i < rota.locais.length;i++) {
     |              ^
  40 |                 if (estadoOrigem === rota.locais[i].nome) {
  41 |                     rota.locais[i].rotas.map(module => (
  42 |                         <>

How to use http-proxy with StompJS?

I have a Stomp client to do websocket communication with. To avoid hardcoding the URL to the websocket broker server I’d like to use a proxy.

I use http-proxy (especially the NuxtJS module nuxt-proxy) in this case. Here is my configuration for it:

// nuxt.config.js
  proxy: {
    '/websocket': {
      target: 'ws://localhost:1001/dispatcher',
      ws: true
    }
  },

I am using the Stomp client the following way:

// stomp client logic
      this.client = new Client()
      this.client.brokerURL = 'websocket'
      if (!this.debug) {
        this.client.debug = () => {
        }
      }
      this.client.onConnect = (_: IFrame) => {
        connectedCallback()
        console.debug('websocket connection established')
        resolve()
      }
      this.client.onStompError = (frame: IFrame) => {
        console.error('Broker reported error: ' + frame.headers.message)
        console.error('Additional details: ' + frame.body)
      }
      this.client.activate()

When testing the whole I see the following error:

Uncaught (in promise) DOMException: Failed to construct 'WebSocket': The URL 'websocket' is invalid.
    at Client._createWebSocket (webpack-internal:///./node_modules/@stomp/stompjs/esm6/client.js:286:25)
    at Client.eval (webpack-internal:///./node_modules/@stomp/stompjs/esm6/client.js:216:36)
    at Generator.next (<anonymous>)
    at fulfilled (webpack-internal:///./node_modules/@stomp/stompjs/esm6/client.js:9:58)
_createWebSocket @ client.js?453e:281
eval @ client.js?453e:211
fulfilled @ client.js?453e:4
Promise.then (async)
step @ client.js?453e:6
eval @ client.js?453e:7
__awaiter @ client.js?453e:3
_connect @ client.js?453e:183
activate @ client.js?453e:180
eval @ websocket.ts?c9d7:32
_callee$ @ websocket.ts?c9d7:14
tryCatch @ runtime.js?96cf:63
invoke @ runtime.js?96cf:294
eval @ runtime.js?96cf:119
asyncGeneratorStep @ asyncToGenerator.js?1da1:3
_next @ asyncToGenerator.js?1da1:25
eval @ asyncToGenerator.js?1da1:32
eval @ asyncToGenerator.js?1da1:21
connect @ websocket.ts?c9d7:5
_callee$ @ GameServer.ts?226d:24
tryCatch @ runtime.js?96cf:63
invoke @ runtime.js?96cf:294
eval @ runtime.js?96cf:119
asyncGeneratorStep @ asyncToGenerator.js?1da1:3
_next @ asyncToGenerator.js?1da1:25
eval @ asyncToGenerator.js?1da1:32
eval @ asyncToGenerator.js?1da1:21
connect @ GameServer.ts?226d:16
create @ BootScene.ts?536d:48
create @ phaser.js?d4ef:100338
loadComplete @ phaser.js?d4ef:100250
emit @ phaser.js?d4ef:1908
loadComplete @ phaser.js?d4ef:196794
fileProcessComplete @ phaser.js?d4ef:196760
onProcessComplete @ phaser.js?d4ef:4961
data.onload @ phaser.js?d4ef:19311
load (async)
onProcess @ phaser.js?d4ef:19307
nextFile @ phaser.js?d4ef:196694
onLoad @ phaser.js?d4ef:4890
load (async)
XHRLoader @ phaser.js?d4ef:122925
load @ phaser.js?d4ef:4855
eval @ phaser.js?d4ef:196648
each @ phaser.js?d4ef:41031
checkLoadQueue @ phaser.js?d4ef:196634
start @ phaser.js?d4ef:196584
bootScene @ phaser.js?d4ef:100227
start @ phaser.js?d4ef:100926
bootQueue @ phaser.js?d4ef:99971
emit @ phaser.js?d4ef:1926
texturesReady @ phaser.js?d4ef:162728
emit @ phaser.js?d4ef:1926
updatePending @ phaser.js?d4ef:102052
emit @ phaser.js?d4ef:1907
image.onload @ phaser.js?d4ef:102182
load (async)
addBase64 @ phaser.js?d4ef:102174
boot @ phaser.js?d4ef:102031
emit @ phaser.js?d4ef:1926
boot @ phaser.js?d4ef:162713
DOMContentLoaded @ phaser.js?d4ef:91974
Game @ phaser.js?d4ef:162673
IonPhaser.initializeGame @ ion-phaser.entry.js?af4d:19
connectedCallback @ ion-phaser.entry.js?af4d:50
safeCall @ index-53dab568.js?8203:233
fireConnectedCallback @ index-53dab568.js?8203:436
initializeComponent @ index-53dab568.js?8203:405
await in initializeComponent (async)
connectedCallback @ index-53dab568.js?8203:475
eval @ index-53dab568.js?8203:539
jmp @ index-53dab568.js?8203:9
connectedCallback @ index-53dab568.js?8203:539
insertBefore @ vue.runtime.esm.js?2b0e:5753
insert @ vue.runtime.esm.js?2b0e:6083
createElm @ vue.runtime.esm.js?2b0e:6002
updateChildren @ vue.runtime.esm.js?2b0e:6260
patchVnode @ vue.runtime.esm.js?2b0e:6363
patch @ vue.runtime.esm.js?2b0e:6526
Vue._update @ vue.runtime.esm.js?2b0e:3963
updateComponent @ vue.runtime.esm.js?2b0e:4075
get @ vue.runtime.esm.js?2b0e:4495
run @ vue.runtime.esm.js?2b0e:4570
flushSchedulerQueue @ vue.runtime.esm.js?2b0e:4326
eval @ vue.runtime.esm.js?2b0e:1989
flushCallbacks @ vue.runtime.esm.js?2b0e:1915
Promise.then (async)
timerFunc @ vue.runtime.esm.js?2b0e:1942
nextTick @ vue.runtime.esm.js?2b0e:1999
queueWatcher @ vue.runtime.esm.js?2b0e:4418
update @ vue.runtime.esm.js?2b0e:4560
notify @ vue.runtime.esm.js?2b0e:730
reactiveSetter @ vue.runtime.esm.js?2b0e:1055
proxySetter @ vue.runtime.esm.js?2b0e:4644
onSuccessfulLogin @ index.vue?0f48:26
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
Vue.$emit @ vue.runtime.esm.js?2b0e:3903
_callee$ @ login.vue?ef3c:42
tryCatch @ runtime.js?96cf:63
invoke @ runtime.js?96cf:294
eval @ runtime.js?96cf:119
asyncGeneratorStep @ asyncToGenerator.js?1da1:3
_next @ asyncToGenerator.js?1da1:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?1da1:13
_next @ asyncToGenerator.js?1da1:25
eval @ asyncToGenerator.js?1da1:32
eval @ asyncToGenerator.js?1da1:21
login @ login.vue?ef3c:34
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
Vue.$emit @ vue.runtime.esm.js?2b0e:3903
submit @ vuetify.js?ce5b:16249
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
original._wrapper @ vue.runtime.esm.js?2b0e:6961
Show 5 more frames

I understand the error however I have no idea how I can use a proxy and the Stomp Client at the same time. I can’t use the ws:// protocol in the Stomp client because I would not trigger the proxy that way (at least that’s what I think)

Any ideas?

VS Code & TypeScript hover over a type

I have been using typescript in vs code and I pretty new to typescript. when I hover an Express type, I get a lot of stuff in a pop up. I really don’t understand where it is coming from. I tried to trace it back, but I am guessing is a built in method in the packages… does anyone know what these are?

import GetServerSideProps

enter image description here

How can I prevent res.send() from overwriting the entire document?

I am firing an ajax call that handles the insertion of users into the database.

I want to return a string or status code to the ajax success for further use.

If I use res.send() server side it overwrites the current document and display the response in the top left in a black document.

I tried using return but that didn’t work either, unless I’m doing something wrong.

Client Side

$.ajax({
    url: "/register",
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify({ data: data }),
    success: function (response) {
      console.log(response);  
      Swal.fire({
        title: "Success!",
        text: "All good",
        icon: "success",
      });
    },
    error: function (e) {
      Swal.fire({
        title: "Error!",
        text: "There was an error saving to the database",
        icon: "error",
      });
      console.log(e);
    },
  });

Server Side

router.post("/", async (req, res) => {
  req.body = sanitize(req.body);

  const user = new User({
    username: req.body.username,
    email: req.body.email,
    password: req.body.password,
  });

  try {
    await user.save();
    return true;
  } catch (e) {
    return false;
    // Implement response to the user if for some reason the save failed
  }
});

Block scope in relation to global variables

Assuming I need to use global variable for some script:(example)

<script>
let myVAR=0;
// some functions
......
......
</script>

Is the following code good for preventing use of global variable? (for my understanding,this is called Block scope,If I’m wrong please clarify me). Second,Is this bad practice or it’s not? If it is,Is there another method to replace global variable?(My target is to access multiple functions in the script with unknown amount of uses,with onclick events,onkeyup events,etc..)

<script>
{
let myVAR=0;
// some functions
......
......
}
</script>

Is it possible to send multiple data in one view on Node JS?

I am trying to pass several data to one view. I can send the products to it but I would like to send the categories as well. I want to send them separately and not with a join. I have been advised to put it after the “then” but I don’t know how to do it.

router.get('/', function (req, res) {
  models.produit.findAll(
    {
      include: 
      [
        {
          model: models.image, as: "images" 
        },
        {
          model: models.promotionproduit, as: "promotionproduits",
          include:[{model: models.promotion, as: "Promotion"}]
        }
      ]})
      .then(data => {
        res.render('home', {
          data: data
        });
      
    }).catch(err => console.log(err));
});

React Router ComponentDidMount Not Executing

I need to have the componentDidMount method to fire when the Router mounts a component so that a timeout can be started. This timeout eventually sets the state so it can’t be initialized in any render lifecycles or the constructor. I tried changing the Route’s component={Home} to render={<Home>}, but then the error render is not a function comes up. I’m really not sure why this is happening so any help would be greatly appreciated!

App.js render method:

render() {
  return (
    <BrowserRouter>
      <Navbar />
      <Container>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/about" component={About} />
        </Switch>
      </Container>       
    </BrowserRouter>
  );
}

Home.js:

const Home = (props) => {
  const images = [ /* Stuff */ ];

  return (
    <Stack gap={4}>
      <div>
        <Card>
          <Card.Header>
            <ImageRotator images={images} />
          </Card.Header>
          <Card.Body>
            <Card.Title>// A Title</Card.Title>
            <Card.Text>
              // Text
            </Card.Text>
          </Card.Body>
        </Card>
      </div>
    </Stack>
  );
}

ImageRotator.js:

class ImageRotator extends Component {
  constructor(props) {
    super(props);

    this.state = {
      firstImageIndex: 0,
      renderImages: false,
      imagesShowing: [],
    }
  }

  componentDidMount() {
    const imagesShowing = this.calculateImagesToShow(this.state.firstImageIndex);
    this.setState({ imagesShowing: imagesShowing });

    window.addEventListener('resize', () => { 
      const imagesToShow = this.calculateImagesToShow(this.state.firstImageIndex);
      const imageTimeout = setTimeout(() => this.incrementImageIndex(), 5000);
      this.setState({ imagesShowing: imagesToShow, imageTimeout: imageTimeout });
    });
  }

  calculateImagesToShow(firstImageIndex) {
    // Returns the images to render on screen
  }

  resetImageInterval() {
    clearTimeout(this.state.imageInterval);
    this.setState({ imageInterval: setTimeout(() => this.incrementImageIndex(), 5000) });
  }

  incrementImageIndex() {
    // Increments the state's first image index
  }

  decrementImageIndex() {
    // Decrements the state's first image index
  }

  render() {
    // Renders the calculated images on the screen including two buttons
    // which when clicked on call the increment and decrement image index functions
  }
}

Javascript – remove sub-objects in an object of arrays of objects by key value

I have a javascript object containing an array of other objects, like the following:

const myObj = {
  people: [{
      firstname: 'Dave',
      lastName: 'Jones',
      sortOrder: 22
    },
    {
      firstname: 'Jane',
      lastName: 'Smith',
      sortOrder: 11
    }
  ],
  otherPeople: [{
      firstname: 'Jen',
      lastName: 'SomeLastName',
      sortOrder: 33
    },
    {
      firstname: 'ExampleFirstName',
      lastName: 'ExampleLastName',
      sortOrder: 12
    }
  ]
};

What I’m trying to do is, given a certain number, let’s say 2, remove that amount of sub objects with the highest sortOrder.

So if I were to eliminate 2, the new object would look like the following:

const myObj = {
  people: [{
      firstname: 'Jane',
      lastName: 'Smith',
      sortOrder: 11
    }
  ],
  otherPeople: [{
      firstname: 'ExampleFirstName',
      lastName: 'ExampleLastName',
      sortOrder: 12
    }
  ]
};

Is there a best way to do this?

Thanks!

How to navigate through a list

I want to render all the ‘name’ elements inside ‘rotas’, but when i try it says map is undefined. Maybe it’s a newbie question but i just can’t figure out how to do this, any help is apreciated.

export default function SelecionaRota(props) {
    const data = {
        locais: [
            {
                name: 'Rio de Janeiro',
                rotas: [
                    {
                        name: 'RJ-SP',
                        valor: 1200
                    },
                    {
                        name: 'RJ-BSB',
                        valor: 1400
                    }
                ]
            }
        ]
    }
    const location = useLocation()
    const { estadoOrigem } = location.state
    return (
        <div>
            <h1>{estadoOrigem}</h1>
            { rota.locais.rotas.map(module => (
                <h1>{module.nome}</h1>
            ))}
        </div>
    )
}

How to display data from DB with JS in HTML site

I want to display data in a paragraph in a HTML file using JS. I have the following codes:

the button:

<button class = "buttonClickMe" onClick="showData();">Show Data</button>
<p>Here we will show some data</p>
<p id = "demo"></p>

the function to show data:

function showData(){
    sql = `SELECT * FROM MyTable`;
    
    db.all(sql, [], (err, rows)=>{
        rows.forEach((row)=>{
            console.log = row;
        })
    })
}

i tried displaying it using this code that i found

document.getElementById("demo").addEventListener("click", myFunction);

function myFunction() {   document.getElementById("demo").innerHTML = "this works"; }

But when i put the showData() function on the place of “this works” or change MyFunction, it says that “showData()” doesn’t return. When I write it without () it still doesn’t work. But it works when it is only “this works”

document.getElementById("demo").addEventListener("click", myFunction //doesnt work when using showData here//);

function myFunction() {
  document.getElementById("demo").innerHTML = "text"//doesnt work when using showData here//;
}

I tried using return statement in showData(), but I am not sure how I should return the data.

¿Existe una función para convertir un ‘Undefined’ a String en JavaScript? [closed]

El frontend manda los valores requeridos al backend para hacer un post en mi base de datos, en este caso es agregar un usuario, pero no se porque el backend recibe la variable del celular como ‘undefined’ cuando debe de ser String, entonces quiero saber si hay alguna manera de convertir este campo a String para poder guardarlo correctamente en mi base de datos.

Este es mi código en el backend (JavaScript):

rutas.post('/' (req, res) => {})
    const{nombre, apellido, correo, cel, usuario, contra} = req.body

    // Esta parte es para verificar como se estaban recibiendo los datos
    let celular = req.body.cel;
    console.log(req.body);
    console.log("celular: "+ celular);
    console.log("tipo: "+ typeof(celular));

    let sql = `INSERT INTO usuarios(nombre_us, apellido_us, correo_us, cel_us, usuario_us, contra_us) `+
              `VALUES('${nombre}', '${apellido}', '${correo}', '${cel}', '${usuario}', '${contra}')`
    conexion.query(sql, (error, filas, campos) => {
        if(error) throw error;
        else
        {
            res.json({status: 'Usuario agregado'})
        }
    });
});

Y esto es lo que me muestra en consola:

enter image description here