Check all checkboxes on DataTables pages

I have the following DataTable, and I need to check / uncheck all checkboxes on all pages. How do I make this happen? Also, just the checkboxes and not the entire row.

enter image description here

I cannot use fnGetNodes, because it is deprecated.

 var table = new DataTable('#example', {
                responsive: true,
                "lengthMenu": [20, 40, 60, 80, 100],
                "pageLength": 10
            }); 

Full HTML :



<!doctype html>
<html lang="en">
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
    <script type="text/javascript" language="javascript" src="//cdn.datatables.net/2.0.2/js/dataTables.min.js"></script>
    <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/2.0.2/css/dataTables.dataTables.min.css">    
  </head>
<body>
    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>

                <th><input type="checkbox" name='all' id="checkAll"> All</th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="1"></td>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011-04-25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="2"></td>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011-07-25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="3" checked></td>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009-01-12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="4"></td>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012-03-29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="5"></td>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008-11-28</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="6"></td>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>61</td>
                <td>2012-12-02</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="7"></td>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>59</td>
                <td>2012-08-06</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="8"></td>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>55</td>
                <td>2010-10-14</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="9"></td>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>39</td>
                <td>2009-09-15</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="10"></td>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>23</td>
                <td>2008-12-13</td>
                <td>$103,600</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="11"></td>
                <td>Jena Gaines</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>30</td>
                <td>2008-12-19</td>
                <td>$90,560</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="12"></td>
                <td>Quinn Flynn</td>
                <td>Support Lead</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2013-03-03</td>
                <td>$342,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="13"></td>
                <td>Charde Marshall</td>
                <td>Regional Director</td>
                <td>San Francisco</td>
                <td>36</td>
                <td>2008-10-16</td>
                <td>$470,600</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="14"></td>
                <td>Haley Kennedy</td>
                <td>Senior Marketing Designer</td>
                <td>London</td>
                <td>43</td>
                <td>2012-12-18</td>
                <td>$313,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="15"></td>
                <td>Tatyana Fitzpatrick</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>19</td>
                <td>2010-03-17</td>
                <td>$385,750</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="16"></td>
                <td>Michael Silva</td>
                <td>Marketing Designer</td>
                <td>London</td>
                <td>66</td>
                <td>2012-11-27</td>
                <td>$198,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="17"></td>
                <td>Paul Byrd</td>
                <td>Chief Financial Officer (CFO)</td>
                <td>New York</td>
                <td>64</td>
                <td>2010-06-09</td>
                <td>$725,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="18"></td>
                <td>Gloria Little</td>
                <td>Systems Administrator</td>
                <td>New York</td>
                <td>59</td>
                <td>2009-04-10</td>
                <td>$237,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="19"></td>
                <td>Bradley Greer</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>41</td>
                <td>2012-10-13</td>
                <td>$132,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="20"></td>
                <td>Dai Rios</td>
                <td>Personnel Lead</td>
                <td>Edinburgh</td>
                <td>35</td>
                <td>2012-09-26</td>
                <td>$217,500</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="21"></td>
                <td>Jenette Caldwell</td>
                <td>Development Lead</td>
                <td>New York</td>
                <td>30</td>
                <td>2011-09-03</td>
                <td>$345,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="22"></td>
                <td>Yuri Berry</td>
                <td>Chief Marketing Officer (CMO)</td>
                <td>New York</td>
                <td>40</td>
                <td>2009-06-25</td>
                <td>$675,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="23"></td>
                <td>Caesar Vance</td>
                <td>Pre-Sales Support</td>
                <td>New York</td>
                <td>21</td>
                <td>2011-12-12</td>
                <td>$106,450</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="24" checked></td>
                <td>Doris Wilder</td>
                <td>Sales Assistant</td>
                <td>Sydney</td>
                <td>23</td>
                <td>2010-09-20</td>
                <td>$85,600</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="25"></td>
                <td>Angelica Ramos</td>
                <td>Chief Executive Officer (CEO)</td>
                <td>London</td>
                <td>47</td>
                <td>2009-10-09</td>
                <td>$1,200,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="26"></td>
                <td>Gavin Joyce</td>
                <td>Developer</td>
                <td>Edinburgh</td>
                <td>42</td>
                <td>2010-12-22</td>
                <td>$92,575</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="employeeID" class="select-employee" value="27"></td>
                <td>Jennifer Chang</td>
                <td>Regional Director</td>
                <td>Singapore</td>
                <td>28</td>
                <td>2010-11-14</td>
                <td>$357,650</td>
            </tr>
        </tbody>
    </table>
    <br/>
   

    <script language="javascript" type="text/javascript"> 
        $(document).ready(function(){
            
            var table = new DataTable('#example', {
                responsive: true,
                "lengthMenu": [20, 40, 60, 80, 100],
                "pageLength": 10
            }); 

                             
           // check / uncheck all somehow? 
        });
    </script>
</body>
</html>

JSON.stringify(data) me devuelve ‘{‘ [closed]

Tengo el siguiente fragmento de codigo:

const data = JSON.stringify({
         email: "[email protected]",
         password: "1234567890"
      })

Cuando miro data tengo '{' como resultado.

Probe con ” “, con ‘ ‘, probé de todo. Obviamente la consulta fetch o axios que quiero hacer se rompe. Pero sin llegar a eso ya me llama la atención que pase ésto. Nunca me pasó. Lo estoy probando en el inspector hermes de una app en react-native corriendo en un dispositivo físico. La verdad que ya no se como intentarlo.

Use external file js in robot-framework

I have a file js in my project

export function myFunction(parametro) {
  return "This is result  " + param;
}

and my file .robot

*** Settings ***
Library    SeleniumLibrary

*** Test Cases ***
Carregar Funções JavaScript
    Open Browser    https://google.com    Firefox
    Execute JavaScript    var script = document.createElement('script');
    ...    script.src = '/external-libs/robot-shared-function/index.js';
    ...    document.head.appendChild(script);

Usar Função JavaScript
    ${resultado}=    Execute JavaScript    return minhaFuncaoGlobal('algumParâmetro');
    Log    ${resultado}

But in results I have :

Usar Função JavaScript                                                | FAIL |
JavascriptException: Message: ReferenceError: myFunction is not defined
------------------------------------------------------------------------------
Teste-Lib                                                             | FAIL |
2 tests, 1 passed, 1 failed

I would like know how to use external function of file js

How can I get scrolling event to register?

I’m trying to program a webpage animation where a user can have the choice of clicking & dragging or simply scrolling using the mouse wheel to view a vertical stack of images. Click & drag works fine, however the scrolling input doesn’t work as desired. When I attempt to scroll though the pictures, input doesn’t seem to register. When I click & drag first, and then scroll, the scroll feature works.

Html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>CoolEffect</title>
</head>
<body>
    <div id = "image-track" data-mouse-down-at = "0" data-prev-percentage = "0">
        <img class="image" src="assets/photo-1542051841857-5f90071e7989.jpeg" draggable="false">
        <img class="image" src="assets/photo-1533050487297-09b450131914.jpeg" draggable="false">
        <img class="image" src="assets/photo-1564284369929-026ba231f89b.jpeg" draggable="false">
        <img class="image" src="assets/photo-1528360983277-13d401cdc186.jpeg" draggable="false">
        <img class="image" src="assets/photo-1492571350019-22de08371fd3.jpeg" draggable="false">
        <img class="image" src="assets/photo-1532884928231-ef40895eb654.jpeg" draggable="false">
        <img class="image" src="assets/photo-1540959733332-eab4deabeeaf.jpeg" draggable="false">
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS

body{
    height: 100vh;
    width: 100vw;
    background-color: black;
    margin: 0rem;
    overflow: hidden;
}

#image-track > .image {
    width: 150vmin;
    height: 50vmin;
    object-fit: cover;
    object-position: 100% 0%;
}

#image-track {
    display: flex;
    flex-direction: column;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

JavaScript

const track = document.getElementById("image-track");

window.onmousedown = e => {
    track.dataset.mouseDownAt = e.clientY;
}

window.onmouseup = () => {
    track.dataset.mouseDownAt = "0";
    track.dataset.prevPercentage = track.dataset.percentage;
}

window.onmousemove = e => {
    if(track.dataset.mouseDownAt === "0") return;

    const mouseDelta = parseFloat(track.dataset.mouseDownAt) - e.clientY,
    maxDelta = window.innerHeight;

    let percentage = (mouseDelta / maxDelta) * -100,
    nextPercentage = parseFloat(track.dataset.prevPercentage) + percentage;

    nextPercentage = Math.max(-100, Math.min(0, nextPercentage));

    track.dataset.percentage = nextPercentage;

    track.animate(
        {transform :`translate(-50%, ${nextPercentage}%)`}, 
        {duration: 1200, fill: "forwards"});

    for(const image of track.getElementsByClassName("image")){
        image.animate(
            {objectPosition : `50% ${nextPercentage + 100}%`}, 
            {duration: 1200, fill: "forwards"});
    }
} 

window.addEventListener("wheel", e => {

    e.preventDefault();
    
    const deltaY = e.deltaY;
    const maxDelta = window.innerHeight;
    
    let percentage = (deltaY / maxDelta) * -100,
        nextPercentage = parseFloat(track.dataset.percentage) + percentage;
    
    nextPercentage = Math.max(-100, Math.min(0, nextPercentage));
    
    track.dataset.percentage = nextPercentage;
    
    track.animate(
        { transform: `translate(-50%, ${nextPercentage}%)` },
        { duration: 1200, fill: "forwards" }
    );
    
    for (const image of track.getElementsByClassName("image")) {
        image.animate(
            { objectPosition: `50% ${nextPercentage + 100}%` },
            { duration: 1200, fill: "forwards" }
        );
    }
    scrollStartY = e.pageY;
});

What I expected to happen was regardless of previous input, the user can scroll or click & drag to view the images. Without clicking and dragging first, the user is unable to do so. I first thought the issue lied in the default scrolling behaviour of the page, so I added to e.preventDefault() to negate this. This however wasn’t the issue. Any suggestions as to what could be causing the issue?

Javascript that displays different page every hour needs to open in new window

I have javascript on my page which opens a different page every hour of the day. This example uses a text link in the code. It opens in the same window it is displayed on. Works fine except I need it to open the click result in a new window. I’d like to keep it really simple code wise. I’d also like to use graphics as the link instead of text.

Any suggestions?

RightNow = new Date();
document.write("<a href='" + RightNow.getHours() 
  + ".html'>NON PASSKEY ENTRANCE</a>")

I’ve tried numerous ways trying to put a target in the code, and I’ll either break it where it will not show on the page at all or it still opens in the parent. Tried calling it as a function too without success.

Is there a better way other than this.$forceUpdate() to update elements?

I am using vueJS to handle a function which reloads my element.

We have our HTML elements here, a dropdown list to display the option

<el-select v-model="row.display_name_uuid">
  <el-option v-for="(item, i) in displayNameList" 
           :key="i" :value="item.uuid" 
           :label="item.display_name">
   </el-option>
</el-select>

Then we have our method here list is our array data and DisplayNameList contains the dropdown list’s select options

getExclusiceUuid (data, val) {
              this.refreshDisplayNameList() // refresh the newly added data

                this.list.forEach((item, index) => { //loop until key paired 
                    if (item.key == data.key) {
                        let obj = JSON.parse(JSON.stringify(item))

                        this.list.splice(index, 1)//we try to remove it first         

                        this.displayNameList = [...this.displayNameList]
            
                        this.list = [...this.list]
                        
                        this.$forceUpdate()

                        obj.display_name_uuid = val

                        this.list.splice(index, 0, obj) //then we add it back here to try to force update

                        this.$forceUpdate()
                    }
                })
            },

After we update the Display Name List content we would also like to update the contain within the select box, but it doesn’t seem like it updates normally even we confirm the function runs after his.refreshDisplayNameList(), the select element doesn’t seem to refresh even we use this.list.splice(index, 1) remove it and recreate.

and
enter image description here

How to use const createBrowserRouter inside class based app component: ReactJS

When I try loading useBlocker inside a class based component It throws the following error Error: useBlocker must be used within a data router. S to fix this, we have to replace BrowserRouter with createBrowserRouter. How do I replace with the following structure when class based component are involved. I have added withRouter custom HOC to support router v6

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import { Provider as ReduxProvider } from "react-redux";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ReduxProvider store={store}>
      <App />
    </ReduxProvider>
  </React.StrictMode>
);
import {
  Location,
  NavigateFunction,
  Params,
  useLocation,
  useNavigate,
  useParams,
} from "react-router-dom";

export interface RouterProps {
  location: Location;
  navigate: NavigateFunction;
  params: Params;
}

export interface WithRouter {
  router: RouterProps;
}

function withRouter(Component: any) {
  function ComponentWithRouterProp(props: any) {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();
    return <Component {...props} router={{ location, navigate, params }} />;
  }

  return ComponentWithRouterProp;
}

export default withRouter;

class App extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
  }

  render() {
    return (
      <div className='container'>
        <Navbar />
        <Suspense>
        <Routes>
          <Route path="/" element={ <Home /> } />
          <Route path="/team" element={ <Team /> } />
          <Route path="/about" element={ <About /> } />
        </Routes>
        </Suspense>
      </div>
    );
  }
}

export default withRouter(App);
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useBlocker } from "react-router";
import Dialog from "../Dialog";

const RouterPrompt = (props) => {
  const { when } = props;
  const [showPrompt, setShowPrompt] = useState<boolean>(false);
  const blocker = useBlocker((props): any => {
    const { pathname } = props.nextLocation;
    if (when && pathname !== "/login") {
      setShowPrompt(true);
      return true;
    }
    return false;
  });

  const handleOK = () => {
    (() => {
      blocker.proceed();
    })();
  };

  const handleCancel = () => {
    blocker.reset();
  };

  return (
    <Dialog
      onSuccess={handleOK}
      onCancel={handleCancel}
    />
  );
};


Stupid error! Yes i know, but i need help ( Javascript) [closed]

i started learning javascript and i decided to try to make a thing with modules, i want to loop from then and execute functions using a for loop!I know this is not the best way… but i learning okay?

document.addEventListener("DOMContentLoaded", function() {
  //Pegamo o butão
  const RunButton = document.getElementById("Run");

  RunButton.addEventListener("click", () => {
      // Fetch the JSON data
      

      fetch('Codes.json')
          .then(response => {
              if (!response.ok) {
                  throw new Error('Network response was not ok');
              }
              return response.json();
          })
          .then(data => {
            //Pegamos... o obvio né murilo!
              const levelData = data[level];
              //Blocks :)
              const blocks = levelData.blocks;
          
              // Loop pelo cade bloco e seu nome
              for (let i = 0; i < levelData.BlocksIn; i++) {
                //Block é o bloco atual!
        
                  const blockWord = blocks[i];
                  var Paramater = SectionDiv.querySelector("#Block_" + i);
                  
                  // Pegamos o nome do bloco... e agora é so usar!
                  import('./blocks.js')
                      .then(module => {
                        //Pegamos do modulo
                          console.log("sex")
                          const FunctionOrClass = module.default[blockWord];
                        //Cria uma instacia ( pois é uma classe ) 
                        const Class =  new FunctionOrClass()
                          //E executa uma função :) 
                          Class[Paramater.value]()
                          alert(Paramater.value )
                        
                      })
                      .catch(error => {
                          console.error('Error importing module:', error);
                      });
              }
          })
          .catch(error => {
              console.error('Error fetching JSON:', error);
          });
  });
});

Ler arquivo .TXT e passar como variável – HTML [closed]

Boa tarde pessoal,

Sou extremamente leigo no assunto, mas preciso passar um link que seja dinâmico para um iframe. Eu pesquisei e cheguei a dar uma olhada na fetch api, porém pelo que eu vi ela precisaria de um serviço pra rodar. É isso mesmo? Porque a ideia seria deixar um html em uma pasta no servidor da empresa que acesse um link de acordo com o usuario que executou. (A execução vem de um software interno que executa um script ahk e abre o arquivo.)

É uma gambiarra só para evitar que as pessoas acessem o link (do bi) a reveria, obviamente a segurança é muito falha, mas no mundo real do dia a dia da empresa essa vulnerabilidade seria aceitável no momento, dada as outras alternativas que foram propostas.

Hoje eu gravo o link em um arquivo .txt temporário, eu teria que ler esse arquivo e gravar no src.

Tenho outras preocupações: Eu abri o relatório, atualizei a página, filtrei… Se nesse meio tempo alguém executar o arquivo, vai impactar na minha “aplicação”? Queria algo que não perdesse o relacionamento com esse link até ser fechado.

Preciso dessa luz para saber se estou viajando muito ou se funcionaria. Se puderem me ajudar eu agradeço!

Bootstrap 5 (5.3.2-5.3.3) navbar problem with scroll spy

I got an issue with bootstrap 5 navbar scroll-spy.
Scroll-spy works fine when I remove data attributes.
And also when I try it on codeply I don’t have any problem over there what I don’t understand why.

This is my code:
“`

Test

</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light sticky-top">
        <div class="container">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#test1" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Test1</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#test2" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Test2</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#test3" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Test3</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#test4" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Test4</a>
                    </li>
                </ul>
                <form class="d-flex my-2 my-lg-0">
                    <input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
                    <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
                </form>
            </div>
        </div>
    </nav>
    <section style='padding: 450px' class='bg-dark' id='test1'>
        <h1 class="text-white">Test 1</h1>
    </section>
    <section style='padding: 450px' class='bg-white' id='test2'>
        <h1 class="text-dark">Test 2</h1>
    </section>
    <section style='padding: 450px' class='bg-dark' id='test3'>
        <h1 class="text-white">Test 3</h1>
    </section>
    <section style='padding: 450px' class='bg-white' id='test4'>
        <h1 class="text-dark">Test 4</h1>
    </section>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>

“`
Codeply code:
https://www.codeply.com/p/7ONKirE8Z2

Why is TBT on PSI so different from my local machine?

When I test the performance of my SSR SPA on localhost, I get a low TBT (total blocking time)
enter image description here

When I use PSI (pagespeed insights) to test the performance of the site, I get a very high TBT

enter image description here

How can I decrease the TBT on PSI? What might cause the main thread to be blocked only on PSI but not on lighthouse? Is it possible the service worker caches the main bundle and PSI doesn’t use SWs?

Can I work around this somehow?

Error loading preview on images saved to firebase storage

I’m developing a react native app and I am having a hard time reading an image saved to storage in firebase cloud. It says error loading preview and when I click on the link it also opens a missing image url. What am I doing wrong? According to other questions it has to do with the rules. And this was suggested.

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read;
      allow write: if request.auth != null;
    }
  }
}

Yet, no cigar

I’m also following their suggested method to save the image, or at least it appears I am

const sendToBackend = () => {
  const metadata = {
    contentType: `image/${get_extension(image)}`
  };

  function get_extension(url) {
    let extension = url.toLowerCase().split(".").pop();

    return extension; // png, mp4, jpeg etc.
  }
  const filename = new Date().getTime() + image.substring(image.lastIndexOf("/")+1);

  console.log("image", filename);

  const storageRef = ref(storage, 'profileimages/' + filename);

  const uploadTask = uploadBytesResumable(storageRef, image, metadata );

  uploadTask.on('state_changed', 
    (snapshot) => {
      const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case 'paused':
          console.log('Upload is paused');
          break;
        case 'running':
          console.log('Upload is running');
          break;
      }
    }, 
    (error) => {
      console.error(error);
    }, 
    () => {
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
        console.log('File available at', downloadURL);
        const userId = auth.currentUser.uid;
        const docRef = doc(db, 'useraccounts', userId);
        updateDoc(docRef, {
          image: downloadURL,
        })
        .then(() => {
          console.log("Document successfully updated!");
          getUser();
        })
        .catch((error) => {
          console.error("Error updating document: ", error);
        });
      });
    }
  );
};

My problem is simple.

I want to be able to select an image from my phone or camera – DONE
I want to save it to firestore cloud storage – DONE (It seems so at least)
I want to be able to pass the URL for the image to the document in firebase collection (DONE)
I want to be able to read the downloadURL when I read {user.image} – (NOT Working)

enter image description here

Unnecessary Rerender Using Memo React

i am trying to understand react memo and i created a simple interface in my react native app. the app consists of two elements:

MainApp.tsx -> controls the list of the user

User.tsx -> displays user object

my plan is to have all user information displayed on first render and each user should have some sort of “update” button which would case it to re-render. The user would be passed to the list item component along with a description. If the description changes, the whole list should be re-rendered. The current implementation looks like this:

mainapp:

// MainApp component
import React, { useState } from 'react';
import { StyleSheet, Button, SafeAreaView, FlatList } from 'react-native';
import User from './User';

export interface IUser {
  name: string;
  id: number;
  age: number;
}

const initialUsers: IUser[] = [
  { id: 1, name: 'Ivan', age: 20 },
  { id: 2, name: 'Elena', age: 25 },
  { id: 3, name: 'John', age: 30 },
];

export const MainApp = () => {
  const [users, setUsers] = useState<IUser[]>(initialUsers);
  const [description, setDescription] = useState<string>(
    'A passionate developer',
  );

  const updateUserAge = (userId: number) => {
    setUsers(
      users.map(user =>
        user.id === userId
          ? { ...user, age: Math.floor(Math.random() * (100 - 20 + 1)) + 20 }
          : user,
      ),
    );
  };

  const updateDescription = () => {
    setDescription(
      (Math.floor(Math.random() * (100 - 20 + 1)) + 20).toString(),
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={users}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => (
          <User
            user={item}
            description={description}
            onUpdateAge={updateUserAge}
          />
        )}
      />
      <Button onPress={updateDescription} title="Update Description" />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default MainApp;

user.tsx

import React, { memo } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { IUser } from './MainApp';

interface UserProps {
  user: IUser;
  description: string;
  onUpdateAge: (userId: number) => void;
}

export const User = memo(
  ({ user, description, onUpdateAge }: UserProps) => {
    console.log('Rendering User', user.name);

    const handleUpdateAge = () => {
      onUpdateAge(user.id);
    };

    return (
      <View style={styles.container}>
        <Text>Name: {user.name}</Text>
        <Text>Age: {user.age}</Text>
        <Text>Description: {description}</Text>
        <Button onPress={handleUpdateAge} title="Update Age" />
      </View>
    );
  },
  (prevProps, nextProps) => {
    return (
      prevProps.user.age === nextProps.user.age &&
      prevProps.description === nextProps.description
    );
  },
);

const styles = StyleSheet.create({
  container: {
    margin: 10,
    padding: 10,
    backgroundColor: '#eee',
  },
});

export default User;

since the object reference stays the same, i specify what props to compare. When i click on the first element i get:

LOG Rendering User Ivan

which is correct and the whole list was not re-rendered, only one item is updated.

however, if i click on another list item after that i get this:

 LOG  Rendering User Ivan
 LOG  Rendering User Elena

For some reason two list items were updated and it keeps going if i click on another users. Can you help me understand why the list items are re-rendered?

Issues Connecting WalletConnect in a React Application

community! I’ve been encountering issues when trying to integrate WalletConnect into my React application. Attempting to connect a wallet via WalletConnect, I face WebSocket connection errors and fail to load resources from bridge.walletconnect.org.

Ensured I’m using the latest version of @walletconnect/web3-provider.
Verified the bridge URL is correctly specified in my code (bridge: ‘https://bridge.walletconnect.org’).
Restarted the development server and cleared the browser cache.


import React, { useState } from 'react';
import Web3Modal from 'web3modal';
import WalletConnectProvider from '@walletconnect/web3-provider';

function WalletConnect() {
  const [account, setAccount] = useState('');

  const providerOptions = {
    walletconnect: {
      package: WalletConnectProvider,
      options: {
        bridge: 'https://bridge.walletconnect.org',
        rpc: {
          1: 'https://mainnet.infura.io/v3/мой_INFURA_API_KEY'
        }
      }
    }
  };

  async function connectWallet() {
    const web3Modal = new Web3Modal({
      network: "mainnet",
      cacheProvider: true,
      providerOptions
    });

    try {
      const connection = await web3Modal.connect();
      // дальнейшие действия
    } catch (error) {
      console.error("Connection to wallet failed:", error);
    }
  }

  return (
    <div>
      <button onClick={connectWallet}>Connect Wallet</button>
      {account && <p>Connected account: {account}</p>}
    </div>
  );
}

export default WalletConnect;

Errors I’m receiving:

WebSocket connection to ‘wss://bridge.walletconnect.org/?env=browser&…’ failed.
Failed to load resource: the server responded with a status of 404 ().
I’ve searched for solutions in the WalletConnect documentation and forums, but haven’t been able to resolve this issue. Any help or guidance on what I might be doing wrong would be greatly appreciated.

S3 bucket redirect object does not redirect, bus instead downloads a file

I am using the @aws-sdk/client-s3 package to use AWS APIs.
I try to upload redirect objects to my bucket using this code:

import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
const s3Client = new S3Client({ region: process.env.AWS_REGION });
    const putS3Command = new PutObjectCommand({
        Bucket: process.env.S3_BUCKET,
        Key: hashedUrl,
        WebsiteRedirectLocation: validatedRequestBody.url,
    });
await s3Client.send(putS3Command);

The command indeed succeeds, and I see the object in the bucket when I browse AWS S3 service:
enter image description here

However, when I try to access the object (using presigned URL), I don’t get redirected, but I just get download file of size 0.

Is there anything wrong with my PutObjectCommand?

I configured this S3 bucket using Terraform:

module "urls_s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "4.1.0"

  acl                      = "private"
  force_destroy            = true
  attach_policy            = true
  policy                   = data.aws_iam_policy_document.urls_s3_policy.json
  control_object_ownership = true
  object_ownership         = "BucketOwnerPreferred"

  tags = merge(
    var.common_tags,
    {
      Name  = "${var.project}-Client-URLs-S3-Bucket"
      Stack = "Backend"
    }
  )
}