Promise resolve not working but data is returned

I have this JS function that will get data from my API

function loadNotification() {
        const loadNotif = new Promise(function (resolve, reject) {
            $.ajax({
                url: "/Vendor/NotificationAPI/GetNotification",
                success: function (data) {
                    resolve(data)
                },
                error: function (data) {
                    reject(data)
                }
            });
        });

        loadNotif.then((data) => {
            console.log(data);
            let template = document.querySelector('template#notif-template');
            var parent = document.querySelector('#notif-parent');

            parent.innerHTML = "";
            if (data.length > 0) {
                $.each(data, function (i, item) {
                    let clone = template.content.cloneNode(true);

                    clone.querySelector("a").innerHTML = "<i class="fas fa-bell mr-2"></i> " + item.Message;

                    parent.appendChild(clone);
                });
            } else {
                console.log("no comment");
                parent.innerHTML = "<p>No notifications.</p>";
            }
        }).catch((data) => {
            var parent = document.querySelector('#notif-parent');
            parent.innerHTML = "<p>No notifications.</p>";

        });
    }

But when I call that function in ready method of jquery

$(document).ready(function () {
        loadNotification();
    });

There is data returned but the what happened is, it throws and execute reject function.

In JSX, Why does a boolean return its self (checkbox scenario)?

I am brand new to React/JSX and don’t understand why things work the way they do.

<input type="checkbox" checked=true /> returns <input type="checkbox checked />
<input type="checkbox" checked=false /> returns <input type="checkbox" />

If checked=true, the HTML is returned like <input type="checkbox" checked>. If checked=false, checked is omitted. What this looks like to me is that if a JSX property is set to true, it displays its self inline with the html. If false, it doesn’t.

I can’t wrap my head around how this works… because we could use the same thing for passing a value up, which would magically not be displayed in the HTML, would it?

I am having a hard time articulating myself but don’t know where else to ask!

Thank you!

Adding (vscode like) extension support to an electron app

I am working an an electron app and would like to integrate vscode like extension support. I’m aware that this is no easy task, however, i am wondering about how it works. I am using react and electron with a backend built in go.

I know that I have to make an extensions api, but the thing that I am wondering the most about is how users would install the extensions and how the app would run them.

Avoid calling a method in a loop

I have a table that has expandable rows with more details in each expanded row. Currently my methods below get the data correctly but the loop in async getData loads the details from the start. Is there a way to loop without loading the data from the start. I want to make another method that calls the data when the row is clicked but I’m not sure how to fix the async getData method.

async getData(currPage) 
        {
            const skip = (currPage - 1) * this.page.top;
            const response = await this.axios.get(`/s/audiences`, {
                params: {
                    skip: skip,
                    top: this.page.top,
                },
            });
            this.page = response.data.pages;

            for (const audience of response.data.data) 
                await this.getNetworks(audience.id); //this calls the details
            
            this.audiences = response.data.data;
        },
        async getNetworks(audId) // details
        {
            try
            {
                const response = await this.axios.get("/s/audiences/network-audiences?audId=" + audId);
                               
                if (!this.networkAudiences[audId])
                {
                    this.$set(this.networkAudiences, audId, {});
                    this.$set(this.networkAudiences[audId], 'isExpanded', false);
                }
                    
                this.$set(this.networkAudiences[audId], 'data', response.data ? response.data.data : []);
            }
            catch (error)
            {
                if (error.message && error.message.includes("404"))
                {
                    if (!this.networkAudiences[audId])
                    {
                        this.$set(this.networkAudiences, audId, {});
                        this.$set(this.networkAudiences[audId], 'isExpanded', false);
                    }
                        
                    this.$set(this.networkAudiences[audId], 'data', []);
                }
                else
                {
                    console.log(error.message);
                }
            }
                
        },
          toggle(audId) //button for details 
        {
            this.$set(this.networkAudiences[audId], 'isExpanded', !this.networkAudiences[audId].isExpanded);
        },
                  <div class="ex_btn"> // expand button
                  <span @click.prevent="toggle(audience.id)">
                    <font-awesome-icon
                      :icon="
                        (networkAudiences[audience.id].isExpanded)
                          ? 'caret-down'
                          : 'caret-right'
                      "
                      :class="[
                        'dropdown--arrow fa-2x cl-blue-primary relative t-3 g-link',
                      ]"
                    />
                  </span>
                </div>

MenuItem with onClick={popupState.close} in Material-ui V 5.0 how to execute a Link to open the component?

Hi folks after spending the hole sunday trying to make a dropdown menu at the AppBar menu, I got all types of errors. The only menu that a could run without breaking the application was with “PopupState helper” https://mui.com/material-ui/react-menu/#basic-menu.
My question is how to implement a link to redirect to the selected component to execute the functions. Is it clear? On the code bellow will get clear enough. The problem is that onClick closes the menu, and I could’n include any “.newFunction”, because it don’t close.
I’m accepting other suggestions to make a dropdown menu at the toolBar that works.

 <AppBar className={classes.appbar} elevation={1} position="fixed">    
            
                <Toolbar style={ { margimleft: 1000 }}  width="1250px" className="toolbar">
                    <Typography className={classes.date} ml={3}>
                        Bem Vindo ao CashFlowBR - Hoje:  {format(new Date(), 'do MMMM Y')}
                    </Typography>
                   {/* sx={{ bgcolor: "#1483dd", color: "#ffffff", mr: 2, mt: 1 }} */}
                   <PopupState variant="popover" popupId="demo-popup-menu">
                        {(popupState) => (
                          <React.Fragment>
                            <Button variant="text" {...bindTrigger(popupState)}
                            sx={{ bgcolor: "#1483dd", color: "#ffffff", mr: 3, mt: 1 }}
                            >
                              Consultas
                            </Button>
                            <Menu {...bindMenu(popupState)}>
                              <MenuItem onClick={popupState.close.newFunction}>Títulos a Pagar</MenuItem> // doesn't work
                              <MenuItem onClick={popupState.close}>Títulos a Receber</MenuItem>
                              <Divider color="#616161" mt={1} /> 
                              <MenuItem onClick={popupState.close}>Lançamentos Bancários</MenuItem>
                              <Divider color="#616161" mt={1} /> 
                              <MenuItem onClick={popupState.close}>Títulos Pagos</MenuItem>
                              <MenuItem onClick={popupState.close}>Títulos Recebidos</MenuItem>
                            </Menu>
                          </React.Fragment>
                        )}
                  </PopupState>
                    
                                  
                   {/* Final */}
                    <Button
                        id="basic-button"
                        aria-controls={open ? 'basic-menu' : undefined}
                        aria-haspopup="true"
                        aria-expanded={open ? 'true' : undefined}
                        // onClick={handleClickAppBarReports}
                        sx={{ bgcolor: "#1483dd", color: "#ffffff", mr: 23, mt: 1 }}
                    >
                      Relatórios
                    </Button>
                    <Typography mr={4}>
                        Login
                    </Typography>
                </Toolbar>

            </AppBar>

Integrating a package/library in a single page React app

I’m using this tutorial to create what I understand is called a “single page” React application.

$ npx create-react-app first-react-app

Creating a new React app in /home/username/first-react-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

...

Success! Created first-react-app at /home/username/first-react-app

Here’s what src/App.js looks like:

$ cat src/App.js
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

I ran it and I can open the default page in my browser from my local machine:

$ cd first-react-app
$ npm run start
$ npm run start

> [email protected] start
> react-scripts start

Compiled successfully!

You can now view first-react-app in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.56.1:3000

Ultimately I want to test the draft.js WYSIWYG editor, so I attempted to install it as a package(?)– I’m new to React so I’m not sure about the nomenclature. So I’m following the docs for installing draft.js from here.

$ npm install draft-js react react-dom

added 12 packages, and audited 1428 packages in 4s

So that seems to have run okay. To ensure I still have a good project, I ran npm run start again, and I get a working local website still.

So now onto actually creating a draft.js WYSIWYG. The default page from the react app says Edit src/App.js and save to reload. So now I’m copy/pasting the instructions from the draft.js documentation, to try to get the WYSIWYG in my react app. Here’s my attempt to add draft:

$ cat src/App.js
import logo from './logo.svg';
import './App.css';
import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';
import 'draft-js/dist/Draft.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = editorState => this.setState({editorState});
  }

  render() {
    return (
      <Editor editorState={this.state.editorState} onChange={this.onChange} />
    );
  }
}

ReactDOM.render(<MyEditor />, document.getElementById('container'));

export default App;

And I also added <div id="container"></div> to public/index.html, since that’s what the instructions are targeting. When I run this, it compiles without error or warning. However when the react app loads in the browser, there is no draft.js WYSIWYG displayed.

In the console, I get this error message on reload: Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot

So I updated my code to this:

+import { createRoot } from 'react-dom/client';
 import {Editor, EditorState} from 'draft-js';
 import 'draft-js/dist/Draft.css';

@@ -40,7 +41,9 @@ class MyEditor extends React.Component {
   }
 }

-ReactDOM.render(<MyEditor />, document.getElementById('container'));
+const container = document.getElementById('container');
+const root = createRoot(container);
+root.render(<MyEditor />);

And now when I run it, I get this error in the console:

Uncaught Error: createRoot(…): Target container is not a DOM element.

I believe it’s trying to target <div id="container">, but I’m not 100% sure.

So, long story long, how do I integrate the draft.js library into my React project? Am I even starting off on the right foot?

Here are the relevant versions of installed software:

$ npm --version
8.5.5

$ node --version
v16.15.0

$ npm list
[email protected] /home/slefevre/first-react-app
├── @testing-library/[email protected]
├── @testing-library/[email protected]
├── @testing-library/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

Como usar o setInterval acionando com o click usando addEventListener no javascript? [closed]

javascript.js
explicação – já está funcioando o codigo e ele mostraa resposta “bahia” letra por letra de 2 em 2 segundo, porem não preciso nem clicar pra aparecer a resposta(está funcionando como se tivesse onLoad). alguem sabe o porque a função está sendo acionada de imediato e não aguarda o addEventListener ?

let resposta01 = "bahia";
let resp01 = resposta01.split('');
let i = 0; 

let whereAnser01 = document.querySelector(".resp01")
whereAnser01.addEventListener("click", slowAnser(resp01, whereAnser01));

function slowAnser(resp, whereAnser){
    
    var intervalo = setInterval(function() {
        
        whereAnser.innerHTML += resp[i];
        i++
    }, 2000);            

    setTimeout(() => {
        clearInterval(intervalo);
    }, resp.length *2000);  

Remove duplicate from array of objects based on value of properties in JavaScript

How can I remove duplicates from an array someArray like below based on the name property given the condition that if name is the same for two elements but for one them the type is new, the original one (without type new) will be retained?

someArray = [{id: 1, name:"apple"}, {id: 2, name:"mango"}, {id: 3, name:"apple", type: "new"}, {id: 4, name:"orange"}, {id: 5, name:"orange", type: "new"}, {id: 6, name: "pineapple", type: "new"}]

to

[{id: 1, name:"apple"}, {id: 2, name: "mango"}, {id: 4, name:"orange"}, {id: 6, name: "pineapple", type: "new"}]

Issue with element positioning via JS in HTML

I’m trying to make a ray directed from the center of the game to the mouse cursor, but there were problems with the offset of top and left. The line is somewhere near the mouse and I don’t understand what it is connected with. I don’t know much about JS/CSS, it’s necessary for Python programs. The game – https://moomoo.io.

Debug video.

JS code:

let line = document.createElement('div');
line.id = 'line';
document.body.appendChild(line);
let x = 0;
let y = 0;
document.querySelector('html').onmousemove = function(event) { // I wrote in the html selector so you can run here. There should be a gameCanvas
  event = event || window.event;
  console.log(event.offsetX, event.offsetY);
  x = event.offsetX;
  y = event.offsetY;
}
let canvas = document.getElementById('gameCanvas')
setInterval(function draw_line() {
  delta_x = x - (document.documentElement.clientWidth / 2);
  delta_y = y - (document.documentElement.clientHeight / 2);
  theta_radians = Math.atan2(delta_y, delta_x);
  console.log(theta_radians);
  line.setAttribute('style', `border: 2px solid lime; width: 200px; -webkit-transform: rotate(${theta_radians}rad); position: absolute; top: ${y}px; left: ${x}px; height: 0`);
}, 1);

WordPress – How to add condition “if user logged in” for html/css/js menu

I’m working with elementor, in the html widget I wrote some code to create a menu and it works fine. Now I want to hide a part of the menu to make it visible only to logged in users. I understand that this is done with php, but elementor’s html widget does not support php. So I’m wondering if there is an alternative to php or if there is a way to indirectly apply php to my menu ?

I’m working with elementor, in the html widget I wrote some code to create a menu and it works fine. Now I want to hide a part of the menu to make it visible only to logged in users. I understand that this is done with php, but elementor’s html widget does not support php. So I’m wondering if there is an alternative to php or if there is a way to indirectly apply php to my menu?

Here is my test menu, it’s just a test so there are only two items. Can anyone help me understand how I can accomplish this? Sorry but I’m new and I’m trying to learn.

I appreciate any response, thanks.

var menu = document.querySelector(".mob_menu_button");
      function mobile_menu(e) {
        e.stopPropagation();
        var x = document.getElementById("mts_mobile_menu");
        if (!x.classList.contains("active")) {
          x.classList.add("active");
          menu.innerHTML = "<span>Close menu</span>";
        } else {
          x.classList.add("side_hide");
          menu.innerHTML = "<span>Open menu</span>";

          setTimeout(function () {
            x.classList.remove("active");
            x.classList.remove("hide");
          }, 100);
        }
      }
      
      document.addEventListener("click", function (e) {
        var x = document.getElementById("mts_mobile_menu");
        if (e.target.id !== "mts_mobile_menu" && x.classList.contains("active")) {
          x.classList.add("hide");
          menu.innerHTML = "<span>Open menu</span>";

          setTimeout(function () {
            x.classList.remove("active");
            x.classList.remove("hide");
          }, 400);
        }
      });
* {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      /*Items menu*/
      .user_menu {
        display: flex;
        flex-direction: column;
      }

      /*Menu header info*/
      .display.name {
        font-size: 15px;
        font-weight: 500;
        color: #303238;
      }

      .display.mail {
        font-size: 13px;
        color: #3d5afe;
      }

      hr.solid {
        border-top: 1px solid #e0e0e0;
        margin: 10px 0px 10px 0px;
      }

      /*Text Link css*/
      .user_menu.item > a {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 8px 0;
        font-size: 13px;
        color: #75777d;
      }

      .user_menu.item:hover > a {
        color: #2e323a;
      }

      /*Icon Button Toggle Menu*/
      .mob_menu_button {
      
       position: absolute;
       top: 15px;
       right: 15px;
       width: 20%;
       background: #fcfcfc!important;
       font-weight: 500!important;
      }

      .icn_button {
        margin: 0;
        font-size: 14px;
      }

      .icn_button:before {
        margin: 0;
      }

      .icn_button:after {
        margin: 0;
      }

      /*Icon Items Menu*/
      .icn_menu:before,
      .icon_menu:after {
        margin: 0px;
        padding: 0px;
        font-size: 16px;
      }

      .icn_menu {
        margin-right: 10px;
        display: flex !important;
        align-items: center;
        justify-content: center;
        width: 22px;
        height: 22px;
      }

      /* User Menu For header website */
      .mts_mob_container {
        display: flex;
        position: fixed;
        z-index: 999;
        /* height: 100%; */
        top: 0;
        left: 0;
        width: 100%;
        background: #000000d6;
      }
      
     .mts_sidenav_box {
        display: block;
        width: 100%;
      }

      .mts_sidenav_content {
        display: none;
        padding: 20px;
        background-color: #fff;
        min-width: 160px;
        width: 280px;
        border-radius: 3px;
        overflow-x: hidden;
        overflow-y: auto;
        z-index: 999;
        position: relative;
        animation: animateFromLeft 0.4s;
      }

      @keyframes animateFromLeft {
        from {
          left: -500px;
          opacity: 0;
        }
        to {
          left: 0;
          opacity: 1;
        }
      }

      @keyframes animateToLeft {
        from {
          left: 0;
          opacity: 1;
        }
        to {
          left: -500px;
          opacity: 0;
        }
      }

    .active {
      display: block !important;
      height: 100vh;
      overflow: hidden;
      width: 75%;
   }

      .mts_sidenav_content.hide {
        animation: animateToLeft 0.8s;
      }
<button onclick="mobile_menu(event)" class="mob_menu_button">Open menu</button>

      <div class="mts_mob_container">
         <div id="mts_mobile_menu" class="mts_sidenav_content"> 
          <div class="mts_sidenav_box">
          
            <div class="user_menu header">
              <span class="display name">Hello User</span>
              <span class="display mail">[email protected]</span>
            </div>

            <hr class="solid" />

            <!--Anyone can see, so there is no need for conditions-->
            <div class="user_menu item">
              <a href="/account">
                <i class="icn_menu fa-regular fa-user">1</i>
                <span class="link_text">Public Link</span>
              </a>
            </div>
            
            <!--Only who is logged in can see-->
            <div class="user_menu item">
              <a href="ordini">
                <i class="icn_menu fa-regular fa-basket-shopping">2</i>
                <span class="link_text">Private Link</span>
              </a>
            </div>
            
          </div>
        </div>
      </div>

How can I send my web scrapped data from my node js backend to my React frontend without having to first send the scraped data to my database?

I have a question regarding how I can take my web scrapped data from my node js backend and send it to my React frontend without having to first send it to my database.

I feel like there should be a way to get my web scrapped data to my frontend without having to first send it to the db. But I haven’t found anything online that has helped implement something like that. I want to take the 4 different values (car, link, price, and groomedPicture) and send them to the frontend to create listings.

I was thinking I could create 4 arrays one for car, link, price, and groomedPicture then send those to my frontend and could use some JS to organize all the data into a listing. The only issue I have with this plan is that I’m not sure how to send arrays through HTTP.

Backend Code

app.get('/listings', (req, res) => {

    // BaT Scraper
    request('https://bringatrailer.com/bmw/e46/?q=e46', async (error, response, html) => {
        if(!error && response.statusCode == 200) {
            const $ = cheerio.load(html);

           var counter = 0;
           var counter1 = 0;
           $(".featured-listing-title-link").each(async (a, title) => {
           const car = $(title).text();
           const link = $(title).attr("href");
           const pricetag = cheerio.load($(".featured-listing-meta-value")[counter]);
           const price = pricetag.text().replace(/,/,"");
           const rawpicture = ($(".featured-listing-image-container img")[counter1]);
           const picture = cheerio.load($(rawpicture).attr("src"))
           const groomedPicture = picture.text().replace(/?resize=470%2C318/,"");

           counter += 2;
           counter1 += 1;
            
           console.log(car)
           console.log(link)
           if (!price) {
               console.log("No Reserve")
           } else {
               console.log(price)
           }
           console.log(groomedPicture)
           console.log()
           
         });

        res.status(200).send();
          
      } else {
        res.status(404).send();
      };

 
    });

});

Result from the above code that I want to send to my frontend

enter image description here

failing WebSocket opening handshake (‘WebSocket connection denied: origin ‘file://’ not allowed’)

I’m facing this error when i’m trying to connect to a websocket server

dropping connection to peer tcp4:127.0.0.1:49528 with abort=False: WebSocket connection denied: origin 'file://' not allowed

while I’m running my python server on localhost and I have a .exe electron app trying to connect to the python server using websockets
However the connection is done correctly if I’m running the electron app using npm start
I need it to work also from the .exe
My server code

class Server():
    def __init__(self, ip, port):
        log.startLogging(sys.stdout)
        self.factory = WebSocketServerFactory("ws://{}:{}".format(ip, port))
        self.factory.protocol = protocol.MainServerProtocol

        # there should only be one connection at a time
        self.factory.setProtocolOptions(maxConnections=1)
        self.factory.setProtocolOptions(allowedOrigins="*")
        self.ip = ip
        self.port = port

    def run(self):
        try_to_listen(True, reactor, self.port, self.factory)
        reactor.run()

Place the cards and suits in two separate arrays, generating a random index number for each array to choose the card and suit [closed]

Implement the five properties of the card object following the instructions in the TODO comments included in the file Implement and test the countdown timer, following the comments provided in the file p3.js. Implement and test the random image functionality, following the comments provided in the file p3.js.

const cardObject = {
  /*
       TODO: Add the following properties (remember to start properties with an underscore):
       - timer ID property used to stop timer, initialized to null.
                  Example: _intervalID: null
       - initial counter property starting value
       - counter property that will count down to zero
       - cards array initialized using a string and the split() method
       - suits array initialized using a string and the split() method
    */
  getRandomCard: function () {
    // TODO: Return a random card value from the cards array
    // TODO: If card is 0, then use 10 to account for actual image file
    // Hint: Generate a random array index value for the cards array
  },
  getRandomSuit: function () {
    // TODO: Return a random suit value from the suits array
    // Hint: Generate a random array index value for the suits array
  },
  loadImages: function () {
    // TODO: Update img element src attribute with a randomly generated card and suit image file name
    // Hint: You will need to call getRandomCard() and getRandomSuit() to create image filename
  },
  countDown: function () {
    // TODO: Decrement and display count down value, and upon reaching 0 stop timer and display card image
    // Hint: You will need to call displayCountdown(), stopCountDownTimer() and loadImages()
  },
  displayCountDown: function () {
    // TODO: Update countdown span element with current countdown value
    // Hint: Get a reference to count down span and set the span textContent property with the counter
  },
  startCountDownTimer: function (start) {
    // TODO: Start timer, setting any appropriate object properties, with an interval of one second
    this._startCount = start;
    this._counter = this._startCount;
    this.displayCountDown();
    this._intervalID = setInterval(this.countDown.bind(this), 1000);
  },
  stopCountDownTimer: function () {
    // TODO: Stop timer using object timer property
    // Hint: Will need to call clearInterval()
  },
  getRandomNumber: function (min, max) {
    // Generate a random integer between min (included) and max (excluded)
    let randomNum = Math.random() * (max - min) + min;
    return Math.floor(randomNum);
  },
};
const timedCard = Object.create(cardObject);
timedCard.startCountDownTimer(5);

Show and Hide mutiple ID’s when click icon

IF I use just one ID with queryselectorById it works fine, but if I use multiple ID’s with querySelectorAll it does not work.

Please see my script:

document.getElementById("_bar_Id_").onclick = function(c1) {
  let x = document.querySelectorAll("#dois,#tres");
  if (x.style.visibility === "hidden") {
  x.style.visibility = "visible";
  } else {
    x.style.visibility = "hidden";
    }
  }