React.js setState on page load not working, how to fix

I am using the react-apexcharts to create a piechart.
I am with success in rendering the series=[] because it is native from the component apexcharts.

But I am trying to render also the labels, which is a simple array.

If I run the console.log:

console.log(this.props.total.map(a=>a.name))

render

["label 1","label 2","label 3"]

How can update the label: [], with the values from this.props.total.map(a=>a.name)?

The full code is below

import React from 'react'
import { Card, CardHeader} from 'reactstrap'
import Chart from 'react-apexcharts'

class PieChart extends React.Component {
  constructor(props) {
    super(props);

    this.state = {    
      series: [],
      options: {
        chart: {
          width: 380,
          type: 'pie',
        },
        labels: [],
        theme: {
          mode: 'light', 
          palette: 'palette2', 
        },
        legend: {
          show: true,
          position: 'bottom',
          horizontalAlign: 'center', 
          floating: false,

      }
      
      },
    };
  }


  componentDidMount() {
    this.setState({
      label: this.props.total.map(a=>a.name),
    })
  }


  render() {
    return (
        <>

        <Card  color="gray" className="mb-3">
            <CardHeader className="bg-gray-lighter">PieChart</CardHeader>
            <Card body>
                <div id="chart3">
                  <Chart 
                  options={this.state.options} 
                  series={this.props.total.map(a=>a.total_today_brl)} 
                  type="pie" 
                  height={450} 
                  />
                </div>
                </Card>
        </Card>
        </>
    );
  }
}
export default PieChart;

I tried without success:

<Chart 
   options={this.state.options} 
   series={this.props.total.map(a=>a.total_today_brl)} 
   labels={this.props.total.map(a=>a.name)}
   type="pie" 
   height={450} 
/>

And tried also:

      options: {
        chart: {
          width: 380,
          type: 'pie',
        },
        labels: this.props.total.map(a=>a.name),
        theme: {
          mode: 'light', 
          palette: 'palette2', 
        },

Wrap all individual words in a span tag based on their first letter

I am trying to wrap each individual word on a webpage in a tag so I can style them individually based on their starting letter.

I have found this method of wrapping each word in a span tag individually, but I can’t figure out how to vary the class based on the first letter of the word.

let e = document.getElementById('words');

e.innerHTML = e.innerHTML.replace(/(^|</?[^>]+>|s+)([^s<]+)/g, '$1<span class="word">$2</span>');

Dynamically add divs to html from node/express

I’m trying to use express.js to search for images through an API, and then dynamically add those images to my image container div.

My initial thought was to just add them as I would when not using node and loop through the images and append them to the container:

Pseudocode
for(i, i<20, i++){
  document.getElementById('TheContainerDivForAllImages').append(singeImageDivWithImage[i])
}

but I noticed that wasn’t possible, as I can’t use document.anything, so how do I go about doing this instead?

I want to keep my frontend library-free but I will of course use what is needed in the backend to get this to work if it’s very hard to do manually.

Thank you very much!

https://codepen.io/programmingcuriosity/pen/QWQNOVQ or maybe snippet is better

import Flickr from "flickr-sdk";
import express, { Router } from "express";

let app = express();
app.use(express.static("public"));

var flickr = new Flickr(process.env.FLICKR_API_KEY);
flickr.photos
  .search({
    text: "example" //also need to get the searchInput to here so I get the right images
  })
  .then(function(res) {
    console.log("yay!", res.body.photos);
  })
  .catch(function(err) {
    console.error("bonk", err);
  });

//So far everything is working, but I essentially want to
//loop through a few images from "res.body.photos"
//and add them as
//<div class="singleImage"> <img src="urlFromPhotos"> </div>
//and append them to the allImages div.
//But I can't figure out how to do it when I can't loop over
// document.getElementById('allImages').append(singeImageDiv[i])
* {
  box-sizing: border-box;
}

#searchDiv {
  width: 25%;
}

#container {
  width: 100%;
  color: aquamarine;
  display: flex;
  flex-direction: column;
  align-items: center;
}

#seachInput {
  width: 50%;
}

#allImages {
  width: 100%;
  heigth: 500px;
  background-color: blue;
  margin: 1vw;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.singleImage {
  border-color: black;
  border: 2px;
  width: 20%;
}
<!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" />
  <link rel="stylesheet" href="index.css" />
  <title>apitest</title>
</head>

<body>
  <div id="container">
    <div id="searchDiv">
      <input type="text" placeholder="What do you want to see images of?" id="seachInput" />
      <button id="searchButton" type="button" onclick="getInputValue();">
        Search
      </button>
    </div>
    <div id="allImages">
      PLACEHOLDER
    </div>
  </div>
</body>

</html>

I have a getList method that receives parameters, but that method is used in 2 different pages. And I get an error in one of them. VUE JS .NET

What happens is the following:
enter image description here

I have this method created. In a screen that is to update prices, I pass the articuloTipoId as a parameter, this screen receives that parameter and filters me according to the articuloTipoId
enter image description here

Until then everything works perfect. My problem starts when another screen has the same getList method. And I don’t need to send that parameter… I put null, empty, try several ways so that it doesn’t break.

enter image description here

And the following error appears on the screen:

enter image description here

My question is this:
How can I do so that I don’t break the screen and pass a null or see how to solve this getList?enter image description here

Nanoleaf API Acces Control Allow Origin

I try to acces my Nanoleaf Panel via Axios

        axios({
        url:'http://192.168.178.53:16021/api/v1/XXX/state',
        data: null,
        method:"POST",
        mode: 'cors',
        headers:{
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Request-Headers": 'Content-Type, Authorization'

        }
    })
        .then(res => {
            console.log(res);
        })
        .catch(err =>{
            console.log(err);
        })

But i get the Following Error:

Access to XMLHttpRequest at ‘http://192.168.178.53:16021/api/v1/XXX/’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Function returning Promise { } instead of a value? [duplicate]

I’m trying to hash a password and send it to the database using Bcrypt on NodeJS, but when I use my function I got a Promise { <pending> } and in my database the Password is stored as [object Promise] instead of being a Hashed password. I need to hash the password and send that hash to the database.

Here is the function I use to hash the Password:

const EncryptPassword = async (Password) => {
    const salt = await bcrypt.genSalt();
    const hash = await bcrypt.hash(Password, salt);
    return hash;
}

And here is the controller I’m using to register a user into the Database:

authcontroller.Register = async (req, res) => {
    const {Name, LastName, Email, Password, Role} = req.body;
    const hash = EncryptPassword(Password);
    console.log(hash);
    return await pool.query(`Call InsertUser('${Name}','${LastName}','${Email}','${hash}','${Role}')`, async function(error){
        if(error){
            res.status(400).send({Error: error})
        }
        else{
            const user = await findaux.finduseremail(Email);
            const token = createToken(user[0].UserID);
            res.cookie('token', token, {
                httpOnly: true,
                MaxAge: MaxAge * 1000
            });
            res.status(201).send({
                UserID: user[0].UserID,
                Role: user[0].Role,
                Token: token
            })
        }
    })
}

The console log after the const hash is the one who prints Promise { <pending> }.

Does anyone know how I can handle this problem?

node-ssdp API for Sonos is missing

I’m trying to figure out how to interact with the Sonos One using JavaScript; Sonos has developer guides and downloads for JavaScript but none of them work, because the node-ssdp project has been archived and is no longer available. Does anyone have a reference or a contact at Sonos through which we can access the devices directly? The cloud API works but is a lot heavier than talking to the devices directly over a LAN.

Onclick event works as intended, but using addEventListener for keyup does not on JavaScript/HTML

I’m creating a simple rock, paper, scissors javascript project. The problem I’m running into is that when I click an input button to submit a choice (taken from radio buttons for rock, paper or scissors) it works as intended, resetting the checked radio buttons and styles as to allow another selection to be made from scratch.

// Code to run when the user clicks the submit button
const submit = () => {
    // Check if the choice has been made
    if (!userChoice) {
        document.getElementById('played').textContent = (`
        Please make a choice`);
        document.getElementById('played').style.color = 'red';
        document.querySelector(".submit-choice").focus();
        // Check if there are still rounds left to be played
    } else if (roundNumber < roundsToPlay) {
        document.getElementById('played').style.color = '';
        // delete content on div
        document.getElementById('played').textContent = null;
        // get user choice
        userChoice = getUserChoice(userChoice);
        // get ai choice
        aiChoice = getComputerChoice();

        document.getElementById('played').innerHTML = (`${determineRoundWinner(userChoice,aiChoice)}`)
        updateState();
        // reset all buttons:
        if (document.querySelector('input[type=radio]:checked')) {
            document.querySelector('input[type=radio]:checked').checked = false;
        }
        resetStyles()
        userChoice = '';
    } else {
        if (gameFinished && userScore > aiScore) {
            document.getElementById('played').style.color = 'green';
            document.getElementById('played').innerHTML = (`The game ended ${userScore} for you and ${aiScore} for the AI.<br>CONGRATULATIONS! YOU WON!`);
        } else if (gameFinished && aiScore > userScore) {
            document.getElementById('played').style.color = 'red';
            document.getElementById('played').innerHTML = (`The game ended ${userScore} for you and ${aiScore} for the AI.<br>F, you've lost :(`);
        } else if (gameFinished) {
            document.getElementById('played').style.color = '';
            document.getElementById('played').innerHTML = (`The game ended ${userScore} for you and ${aiScore} for the AI.<br>ITS A TIE :O`)
        }
    }
    if (roundsToPlay > roundNumber) {
        document.getElementsByTagName(
            "legend"
        )[0].innerText = `What do you choose for round ${roundNumber + 1}?`;
    } else {
        gameFinished = true;
    }
}

The result of this function when ran from a onClick submit button works perfectly, the choice is made, the game state is updated accordingly and the styles get reset and the variable userChoice rolled back.

But when this exact same code gets runned from addEventListener it does not work:

document.addEventListener('keydown', event => {
    if (event.code !== 'Space') return;
    if (pressed) return;
    pressed = true;
    setStyle('.submit-choice', 'transform', 'scaleY(80%) translateY(1rem)')
})
document.addEventListener('keyup', event => {
    if (event.code !== 'Space') return;
    pressed = false;
    setStyle('.submit-choice', 'transform', '')
    submit();
})

I tried logging what happens inside of the eventListener, but after submit the variable userChoice is an empty string (as intended), but gets rolled back to the latest choice once the event ends (not intended). Same goes for the styles, they do get restarted for a very brief moment and afterwards the last choice gets highlighted again (not intended). This is the only not intended behavior, since the game does advance accordingly otherwise.

Why does this work with onClick perfectly and not with eventListener ? How can I fix this?

Thanks a lot in advance, I’m struggling to learn this language and any help is much appreciated.

Error on trying to override POST method with PUT

I am experiencing a “Method Not Allowed” issue when trying to override my POST request with PUT (for updating information in my blog).

HTML:

  <div class="create-message content">
<form action="/messages/edit/<%= message.id %>?_method=PUT" method="POST">
  <label for="title">Message title:</label>
  <input required value="<%= message.title %>" type="text" id="title" name="title" required>
  <label for="snippet">Message snippet:</label>
  <input required value="<%= message.snippet %>" type="text" id="snippet" name="snippet" required>
  <label for="body">Message body:</label>
  <input required value="<%= message.body %>" type="text" id="body" name="body" required>
  <input type = "submit" class="waves-effect waves-light btn navybg" value="Edit Post"/>
  <button>Update</button>
</form>

My routs are the following:

  //edit message
  router.get('/messages/edit/:id', async (ctx, next) => {
    const id = ctx.params.id;
    const result = await MessageModel.findById(id)
    await  ctx.render('edit', {
      title: 'Messages',  
      message: result
     })
    });

The code above runs well, but after I click on submit button, “Method Not Allowed” issue occurs instead of running this:

  //update edited message
  router.put('/messages/edit/:id', async (ctx, next) => {
      MessageModel.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new:true}, (err:any, result:any) => {
      })
    return ctx.redirect('/');
});

Please share your thoughts on this issue.
Thank you

How to pass Github secrets as value in json file?

I’m using Cypress.io for my automated tests & triggering it in CI/D with Github Actions. The config cypress.json file has nested env values like so:

{
  "baseUrl": "<url-to-login>",
  "env": {
    "roles": {
      "admin": {
        "PASSWORD": "<password>",
        "USERNAME": "<username>"
      },
      "employee": {
        "PASSWORD": "<password>",
        "USERNAME": "<username>"
      },
      "client": {
        "PASSWORD": "<password>",
        "USERNAME": "<username>"
      }
    }
  }
}

Unfortunately, Cypress can’t access deeply env variables so I’m creating the config cypress.json like so:

name: Cypress Tests

on: [push]

jobs:
  cypress-run:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        # creates cypress.json file to run Cypress
      - name: Create Cypress config files
        run: |
          echo '{ "baseUrl": "${{ secrets.BASE_URL }}", "env": { "roles": { "admin": { "PASSWORD": "${{ secrets.PASSWORD }}", "USERNAME": "${{ secrets.USERNAME }}" } } } }' > cypress.json
      - name: Cypress run
        uses: cypress-io/github-action@v2
        with:
          build: yarn run
          start: yarn cypress:run
          wait-on-timeout: 120
          browser: chrome

It doesn’t work, but I hardcoded the values it did work like so:

run: |
          echo '{ "baseUrl": "<hardcoded-redacted-value>", "env": { "roles": { "admin": { "PASSWORD": "<hardcoded-redacted-value>", "USERNAME": "<hardcoded-redacted-value>" } } } }' > cypress.json

So my question is, how to pass the secret in the json file?

ReactJs useEffect execute twice when the page load

UseEffect executes twice when it should execute only once I think.
I use useEffect here to fetch some info when the page load, and I need to fetch data only once. I used to do this with the code below, but now I’m facing this problem

import "./App.css";
import axios from "axios";
import { useEffect, useReducer } from "react";

const appInitialState = {
  pageLoading: true,
  adminSignedIn: false,
};
const appStateReducer = (state, action) => {
  if (action.type === "adminSigned") {
    return { ...state, pageLoading: false, adminSignedIn: true };
  } else {
    return { ...state, pageLoading: false, adminSignedIn: false };
  }
};

function App() {
  const [appState, appStateDispatch] = useReducer(
    appStateReducer,
    appInitialState
  );
  useEffect(() => {
    axios.post("http://localhost:8080/admin/v1/isAuthenticated").then((res) => {
      console.log(res.data);
      appStateDispatch({
        type:
          res.data.isAuthenticated === true ? "adminSigned" : "adminNotSigned",
      });
    });
  }, []);

  return (
    <div className="App">
      <h1>App</h1>
    </div>
  );
}

export default App;

For some reason my content within an array is not printing out to the screen

I am currently following a tutorial on PERN stack and whenever I try to print out the contents of an array to the screen to be under title and content, nothing prints out.

Here is my code where the error relies somewhere within:

import React, { Fragment, useState, useEffect } from "react";

const ListBlog = () => {
  const [blogs, setBlogs] = useState([]);

  const getBlogs = async () => {
    const res = await fetch('http://localhost:5000/blog');

    const blogArray = await res.json();

    setBlogs(blogArray)
  }

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

  console.log(blogs)
  return <Fragment>
    {" "}
    <table className="table mt-5">
    <thead>
      <tr>
        <th>Title</th>
        <th>Content</th>
        <th>Edit</th>
        <th>Delete</th>
      </tr>
    </thead>
    <tbody>
    {/* <tr>
        <td>John</td>
        <td>Doe</td>
        <td>[email protected]</td>
</tr>*/}
     {
       blogs.map(blog => {
         <tr>
           <td>
             {blog.title}
           </td>
           <td>{blog.content}</td>
           <td>Edit</td>
           <td>Delete</td>
         </tr>
       })
     }
    </tbody>
  </table>
  </Fragment>
}

export default ListBlog;

I believe the state is causing errors as it is printing out the following:

(2) [{…}, {…}]0: {post_id: 1, title: 'hi', content: 'howdy'}1: {post_id: 11, title: 'eat', content: 'yogurt'}length: 2[[Prototype]]: Array(0)
[object Object],[object Object]

I just want to print out the array but for some reason [Object object] is printing out as well which may be causing my contents not to print to my localhost page.

Here is what my page looks like when I try to have my contents within the array print underneath title, content, Edit, and Delete but nothing gets displayed…

Nothing displays on screen

react blank page while using material ui style

I’m creating a react page and I have some problems with the styles. here is my react code:

import React from "react";
import { Typography, Container, AppBar, Grow, Grid } from "@mui/material";

import Posts from './components/Posts/Posts.js';
import Form from './components/Form/Form.js';
import memories from "./Images/memories.png";

const App = () => {
  return (
    <Container maxwidth="lg">
      <AppBar position="static" color="inherit">
        <Typography variant="h2" align="center">
          khatere ha
        </Typography>
        <img src={memories} alt="memories" height="100" />
      </AppBar>
      <Grow in>
          <Container>
              <Grid container justify="space-between" alignItems="stretch" spacing={3}>
                    <Grid item xs={12} sm={7}>
                      <Posts />
                    </Grid>
                    <Grid item xs={12} sm={4}>
                      <Form />
                    </Grid>
              </Grid>
          </Container>
      </Grow>
    </Container>
  );
}
export default App;

here is my style codes:

import { makeStyles } from "@mui/material";
import { breakpoints } from "@mui/system";

export default makeStyles(() => ({
    appBarSearch: {
        borderRadius: 4,
        marginBottom: '1rem',
        display: 'flex',
        padding: '16px',
      },
      pagination: {
        borderRadius: 4,
        marginTop: '1rem',
        padding: '16px',
      },
      gridContainer: {
        [breakpoints.down('xs')]: {
          flexDirection: 'column-reverse',
        },
      },
}));

I want to use a materialUi style but when I import the style into my react file, everything disappears. the page will become completely blank.
I’m using this line ” import useStyles from ‘./styles.js’; ” to import styles and this line ” const stclass = useStyles(); ” to use those styles. but as soon as I import style file, everything would disappear