Clicking twice to see the value – UseState – UseEffect React using Function Component

I’m having a newbie problem, I really read all the documentations about it, and have seen all the stackoverflow about this issue, and I still can’t get it right.

I need to get a value from a const variable, that I’m seeting without clicking twice, I tried a million things and still can’t make this happen.

    const [GetCode,setGetCode] = useState("");
     const GetCodeMI = () =>{
    Axios.get('http://localhost:3001/GetMICode',{ }).then((response)=>{

            // console.log(response.data[0].ZZE_CODIGO);
             setGetCode(response.data);
         
        });
 }   
  const  InsertInternalMov = () => {
    GetCodeMi2().then(()=>{
        console.log(GetCode[0]);
      })
  }

In this scenario the first time that I click on the function the value of GetCode it’s undefined the second time it shows correclty. I need to get the value the first time I click, My head it still wraping around how react works.

Regex, convert html string to array, issue with languages and and special characters

I am not an expert with regex, and have an issue trying to convert a html string to an array of html elements, so the idea was if we get by example:

Sample String:

<p>Welcome to my awesome website for more info <a href="www.myanotherawesomewebsite.com" target="_blank">click here</a></p> 

(which actually can be any possible combination)

So I wanted to get something like :

'<p>', 'Welcome to my awesome website for more info','<a href="www.myanotherawesomewebsite.com" target="_blank">', 'click here','</a>',</p>'

So this could be achieved with the next regex:

/(<[^>]+>|[a-zè A-Z0-9]+)?/g

So using match function, for testing:

 '<p>Welcome to my awesome website for more info <a href="www.myanotherawesomewebsite.com" target="_blank">click here</a></p>'.match(/(<[^>]+>|[a-zè A-Z0-9]+)?/g)

and this one works, however there is a problem going on with the languages, for everything apart english works okay, but when I have characters in french, or german, this doesn’t work anymore…

The work around was to do something like:

/(<[^>]+>|[a-zàâäèéêëîïôœùûüÿçäöüÄÖÜÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇß!#.?”“«» A-Z0-9-u00A0]+)?/g

which works but not 100%, also, not working at all with things like ‘sup’ or ‘sub’, etc…

so my question is… there is a way to improve this? Help and advices will be very welcome. Thank you in advance for reading…

i would like to loop through this and get each “transactionReference”

“responseBody”: {
“content”: [{
“paymentMethod”: “ACCOUNT_TRANSFER”,
“createdOn”: “2019-10-29T11:02:00.000+0000”,
“amount”: 22.00,
“flagged”: false,
“currencyCode”: “NGN”,
“completedOn”: “2019-10-29T11:08:11.000+0000”,
“paymentDescription”: “Isoken 001”,
“paymentStatus”: “EXPIRED”,
“transactionReference”: “MNFY|20191029110159|005805”,
“paymentReference”: “MNFY|20191029110159|005805”,
“merchantCode”: “ZETBBQ5Q7VLB”,
“merchantName”: “Lahray LTD ”
},
{
“paymentMethod”: “ACCOUNT_TRANSFER”,
“createdOn”: “2019-10-29T10:45:12.000+0000”,
“amount”: 22.00,
“flagged”: false,
“fee”: 0.18,
“currencyCode”: “NGN”,
“completedOn”: “2019-10-29T10:49:49.000+0000”,
“paymentDescription”: “Isoken 001”,
“paymentStatus”: “PAID”,
“transactionReference”: “MNFY|20191029104511|005830”,
“paymentReference”: “MNFY|20191029104511|005830”,
“merchantCode”: “ZETBBQ5Q7VLB”,
“merchantName”: “Lahray LTD “,
“payableAmount”: 22.00
}
],
“last”: false,
“totalElements”: 258,
“totalPages”: 129,
“first”: true,
“numberOfElements”: 2,
“size”: 2,
“number”: 0,
“empty”: false
}

React Bootsrap Form Unit Testing

I’m new to react js and was trying to unit test my react-bootastrap form but i’m getting an error saying “Unable to find an element by: [data-testid=”input-first-name”].
It would be of great help if someone can suggest something

AddUser.js

  • Here,i’m posting a small part of my code
return (
    <>
      {isLoggedIn === "true" ? (
        <div data-testid="user">
          <NavbarAdmin />
          <div className={styles.body}>
            <h2 className={styles.h2}>Add User</h2>
            <form className={styles.form}
            data-testid="filter-input-form">
              <div className={styles.formField}>
                <label
                  htmlFor="validationServer01"
                  style={{ marginLeft: "-131px", marginBottom: "0px" }}
                  className="form-label"
                >
                  First Name <span style={{ color: "#D22B2B" }}>*</span>
                </label>
                <input
                  style={inputStyle}
                  className="Form control lg is-invalid"
                  type="text"
                  name="FirstName"
                  placeholder="Enter your First-Name"
                  value={fname}
                  onBlur={() => fieldValidation("fname")}
                  onChange={(e) => {
                    setFName(e.target.value);
                  }}
                  data-testid="input-first-name"
                  required
                />
                <br />
                {fNameEmpty === true ? (
                  <div
                    className="invalid-feedback"
                    style={{
                      marginBottom: "15px",
                      marginTop: "-25px",
                      marginLeft: "-30px",
                    }}
                  >
                    Please Enter First Name!
                  </div>
                ) : (
                  ""
                )}
              </div>
              <button
                className={styles.btn}
                type="submit"
                onClick={handleClick}
                disabled={isDisabled}
                data-testid="add-users-button"
              >
                Add User
              </button>
            </form>
          </div>
        </div>
      ) : (
        ""
      )}
    </>
  );

AddUser.test.js

  • This is the test case
import React from "react";
import AddUsers from "../Containers/User/AddUsers";
import {
  render,
  waitFor,
  screen,
  fireEvent,
  act,
  getByTestId

} from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import userEvent from '@testing-library/user-event';

describe('AddUser component', () => {

    it('should render the component onto the screen', () => {
        render(<BrowserRouter><AddUsers show={true}/> </BrowserRouter>);
        expect(screen.getByTestId('input-first-name')).toBe("");
    });

Error
this is the error i’m getting
[I guess the problem is because of bootstrap form, i’m using…because it is working fine with simple html form]

Does the JavaScript interpreter interprets code twice or once?

It doesn’t really say anywhere and I’d really love to know.

Does JavaScript firstly reads a file, assigns memory to the variables, moves their declarations to the top of the stack and then runs the second time with executing, or does it read it all in one go somehow?

Sorry if repeating, but i havent found this specific question or a specific answer to this question either.

Nexjs: can’t handle response from the api

I’m trying to query my sqlite database from the front-end through api (nextjs).

handler side:

export default function handler(req, res) {
  ...
  some code here
  ...
  } else if (req.method == "POST" && req.body.method == "getScore") {
    return new Promise((resolve, reject) => {
      console.log("Get score!");
      db.get(
        "SELECT score FROM db WHERE userAddress = ?",
        [req.body.userAddress],
        (err, row) => {
          if (err) {
            console.log(err);
            reject();
            res.status(204).json({ message: "No content" });
          } else if (row) {
            console.log("im here!");
            console.log(row);
            res.statusCode = 200;
            res.setHeader("Content-Type", "application/json");
            res.setHeader("charset", "utf-8");
            resolve();
            res.json(row);
            //res.status(200).json(row);
          }
        }
      );
    });
  }
}


i have a simple page with user statistics and i’m trying to fetch data from the database with useEffect in the following way:

...
const [data, setData] = useState(null);
const [isLoading, setLoading] = useState(false);
...
useEffect(() => {
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        userAddress: account,
        method: "getScore",
      }),
    };

    setLoading(true);
    fetch("api/hello", requestOptions)
      .then((res) => {
        console.log(res);
      })
      .then((data) => {
        console.log(`DATA: ${data}`);
        setData(data);
        setLoading(false);
      });

    //getData();
  }, []);
....

my problem is: 

I never getting response on the frontend side, nothing printed out, but everything in console.log works in the correct way on the handler side, data fetching from the database in the correct way, the main problem is in response from the api (never getting response). 

It doesnt work even if i'm doing that without returning Promise, just using simple res.status(200.json(row))

What is the correct way to do this?

Infinite Scroll pratice

I’m praticing the infinity sroll follow the source https://cs50.harvard.edu/web/2020/notes/6/ , but instead of calling to sever side, i just append elements form start to end index of datas array and the result as not as my expectation.I think that something related about Javascript’s asynchronous feature. Is that true? How can I fix this problem?

<!DOCTYPE html>
<html>
    <head>
        <title>Infiniti Scroll</title>
    </head>
    <body>
        <div id="data"></div>
        <script>
            let start = 0
            let end = 100
            const datas = []
            for (let index = 0; index < 1000; index++) {
                datas.push(`<p>${index}</p>`);
            }
            document.addEventListener("DOMContentLoaded",function(){
                load();
                window.onscroll = ()=>
                {
                    
                    if (window.innerHeight + window.scrollY >= document.body.offsetHeight)
                    {
                        setTimeout(load,1000);
                        
                    }
                }
            });
            function load(){
                // for (let index = start; index <= end; index++) {
                    document.querySelector("#data").innerHTML+=datas.slice(start, end+1);
                    end=end+10;start =end;
                    
                // }
            }
        </script>
    </body>
</html>

Try to do a progress bar in javascript

I’m starting to code this year and sorry if my english is not good enough,
I have a problem with a progress bar with JS,
I have on my console an “uncaught TypeError who charge infinitly and say to me that we can charge the properties on style…
The first step was working but when the bar is supposed to become interactive it’s not working

 <script>
        const tll = gasp.timeline({
            paused: true
        });
        tll.to("#percent", "#bar", {
            duration: .2,
            opacity: 0,
            zIndex: -1
        });
        tll.to("#preloader", {
            duration: .8,
            width: "0%"
        });
        tll.from(".container", {
            duration: 1.5,
            y: "-150%"
        }, "-=.2");
        tll.to("container h1", {
            opacity: 1,
            textShadow: "12px 20px rgba(255, 255, 255,0.23)",
            skewY: 10,
            y: "10%",
            stagger: {
                amount: .4
            }
        });
        var width = 1;
        var bar = document.getElementById("barconfirm");
        var id;

        function move() {
            id = setInterval(frame, 10);

        }

        function frame() {
            if(width > 100){
                clearInterval(id);
                tll.play();
            } else {
                width++;
                bar.style.width = width + "%";
                document.getElementById("percent").innerHTML = width + "%";
            }
        }
    </script>
*{
    margin: 0;
    padding: 0;
    overflow: hidden;
}


#preloader{
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100vh;
    z-index: 100;
    background-color: #0f0f0f;
    flex-direction: column;
}

#percent{
    color: white;
    font-family: "Neutral Face";
}
#bar {
    width: 60%;
    margin-top: 20%;
}
#barconfirm{
    width: 1%;
    padding: 1px 0px;
    background-color: white;

}
.container {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100vh;
    background-color: gray;
}
.container h1{
    font-family: 'Monument';
    text-transform: uppercase;
    font-size: 40px;
    opacity: 0;
}
<body onload="move()">

    <div id="preloader">
        <div id="percent">1%</div>
        <div id="bar">
            <div id="barconfirm"></div>

        </div>
    </div>
    <div class="container">
        <h1>Leo Clemente</h1>
    </div>

Thanks to you all for your help, I want if you can an explanation more than just a code because I’m here to learn too and have a great day!

Mouse-Following Tooltip gets Farther Away the Smaller the Window

I’ve just revamped my tooltip code due to issues with the position altering depending on the size of it’s parent (mostly due to using offsetX/Y instead of pageX/Y, but page was being weird, too). So I decided to just have one tooltip for each of my site’s pages, parented to the main div, and just feed it different text depending on what the mouse is hovering over (I’ll be dealing with the visibility part later).

And it’s worked quite well so far, but the only issue is that, the smaller I make my window, the farther the tooltip is from my mouse, until it’s not even in view anymore.

Here’s the Javascript coding I’ve done for it. Apologies for any messy coding, it’s 6AM and I’ve been at this since midnight.

      var body = document.getElementsByClassName("test");
      
      var tooltip = document.getElementById("tooltip");
      
      body[0].addEventListener("mousemove", tooltipMove)
      
      function tooltipMove(event) {
        
        var x = event.pageX;
        var y = event.pageY;
        
        tooltip.style.top = (y + -900) + "px";
        tooltip.style.left = (x + -875) + "px";
        
      }

The CSS coding for the tooltip:

.tooltip {
    visibility: hidden;
    width: 170px;
    background-color: white;
    background-image: url("images/tooltipbackground.png");
    color: black;
    text-align: center;
    border-style: groove;
    border-color: #f4bb4c #ffd966 #ffd966 #f4bb4c;
    border-radius: 2px;
    padding: 5px 5px;
  
    position: absolute;
    z-index: 1;
 }

.notfound:hover .tooltip {
    visibility: visible;
  }

And the HTML:

    <div class="test" style="top: 70px; position: relative; height: 100%; width: 100%;">
      <h1>TEST</h1>
      <img src="images/pagenotfound.png">
    </div>
    
    <div style="width: 1px; height: 1px; position: relative;">
      <span class="tooltip" id="tooltip">testing</span>
    </div>

I should mention the body’s (which has the “notfound” class) height is 900px, and it’s width 600px, in case that’s one of the problems.

The 1 pixel div is just what I’m using to “host” the tooltip, not sure if it’s causing any problems as well. I inspected the page in order to see it, and it never seemed to slide around with the window size.

Any sort of help would be greatly appreciated. I’ve tried to switch it from pageX/Y to clientX/Y, but it’s the same issue. And using offset causes it’s position to shift depending on what I’m hovering over, which is the reason I’m revamping the code in the first place.

I’ve also tried to change the tooltip’s position from absolute to, well, anything else (after resizing it’s parent so it doesn’t get squashed), but that hasn’t helped.

Another thing I should mention is that, for some reason, the shifting doesn’t seem to happen in the Y axis, it’s only when I squish the window horizontally that the tooltip shifts, at least from what I’ve noticed.

Sorry if there’s any misspellings or obvious solutions here, I wanted to get this question out there before I go to bed.

Transforming object data in JS

I’ve got an issue transforming data in JS.

The data looks like this :

const data = [
{
    "idPopulation": 1,
    "namePopulation": "Population 1",
    "idStrategy": 1,
    "nameStrategy": "Strategy 1",
    "priority": 1
},
{
    "idPopulation": 1,
    "namePopulation": "Population 1",
    "idStrategy": 2,
    "nameStrategy": "Strategy 2",
    "priority": null
},
{
    "idPopulation": 1,
    "namePopulation": "Population 1",
    "idStrategy": 3,
    "nameStrategy": "Strategy 3",
    "priority": 2
},
{
    "idPopulation": 2,
    "namePopulation": "Population 2",
    "idStrategy": 1,
    "nameStrategy": "Strategy 1",
    "priority": null
},
{
    "idPopulation": 2,
    "namePopulation": "Population 2",
    "idStrategy": 2,
    "nameStrategy": "Strategy 2",
    "priority": null
},
{
    "idPopulation": 2,
    "namePopulation": "Population 2",
    "idStrategy": 3,
    "nameStrategy": "Strategy 3",
    "priority": 1
},
{
    "idPopulation": 3,
    "namePopulation": "Population 3",
    "idStrategy": 1,
    "nameStrategy": "Strategy 1",
    "priority": 1
},
{
    "idPopulation": 3,
    "namePopulation": "Population 3",
    "idStrategy": 2,
    "nameStrategy": "Strategy 2",
    "priority": 2
},
{
    "idPopulation": 3,
    "namePopulation": "Population 3",
    "idStrategy": 3,
    "nameStrategy": "Strategy 3",
    "priority": 3
}

]

I need to transform it into this for it to be usable in by front-end package (https://devexpress.github.io/devextreme-reactive/react/grid/docs/guides/editing/):

    const testRows = [
    {
      nameStrategy: 'Strategy 1',
      priorityPopulation1: 1,
      priorityPopulation2: null,
      priorityPopulation3: 1,
    }, 
{...}]

I’m trying to reduce and stuff but can’t figure it out yet. So far, I’ve done this :

  const result = data.reduce((groupedStrat, strat) => {
  const stratName = strat.nameStrategie;
  if(groupedStrat[stratName] == null) groupedStrat[stratName] = []
    groupedStrat[stratName].push(strat)
    return groupedStrat
}, {})

console.log(result).

Let me know if my issue is clear and understandable.

Thanks !

How to lookup a product in a HTML table (shopping cart) and target the row its in to change it

I have this list of products (just a simple array of objects) which can be added to a shopping cart. The shopping cart is a HTML table to which rows are added with each product that is added to the cart. The user selects the products and specifies the desired amount. A button adds it to the table.

When I add the same product more than once, its listed in the cart more than once. I am looking for a way to search in the table if a product was already added and if so, to target that specific table row to increase the amount and change the subtotal accordingly. Any help is greatly appreciated! 🙂

My code so far:

let totalAmount = 0;

let products = [{
    id: "882735",
    name: "Pencil",
    price: 1.19
  },
  {
    id: "214576",
    name: "Eraser",
    price: 0.89
  },
  {
    id: "349987",
    name: "Notebook",
    price: 2.99
  },
  {
    id: "166482",
    name: "Ruler",
    price: 1.69
  },
  {
    id: "446799",
    name: "Marker",
    price: 1.39
  }
];

function addProduct(id, product, price, productAmount) {
  let showTotal = document.getElementById("showTotal");
  let cartContent = document.getElementById("cartContent");
  let productTotal = productAmount * price;
  totalAmount = totalAmount + productTotal;
  template = `
    <tr>
        <td>${product}</td>
        <td>${id}</td>
        <td>$${price}</td>
        <td>${productAmount}</td>
        <td>$${productTotal.toFixed(2)}</td>
    </tr>`;
  cartContent.innerHTML += template;
  showTotal.innerHTML = `<b>$${totalAmount.toFixed(2)}</b>`;
}

function loadProducts() {
  let productList = document.getElementById("productList");
  let productPrice = document.getElementById("productPrice");
  let sel = document.createElement("select");
  for (let i of products) {
    let opt = document.createElement("option");
    if (i.disabled) {
      opt.disabled = true;
      opt.selected = true;
      opt.innerHTML = `${i.name}`;
    } else {
      opt.innerHTML = `${i.name}`;
    }
    sel.appendChild(opt);
    productList.appendChild(sel);
  }

  let addBtn = document.getElementById("addBtn");
  addBtn.onclick = () => {
    let product = sel.value;
    let productAmount = parseInt(document.getElementById("productAmount").value);
    if (product === "Select a product") {
      alert("Please select an article first.");
    } else if (productAmount === 0) {
      alert("Please specify the desired amount of " + product.toLowerCase() + "s!");
    } else {
      for (let i of products) {
        if (i.name === product) {
          let price = i.price;
          let id = i.id;
          addProduct(id, product, price, productAmount)
        }
      }
    }
  }

  productList.onchange = () => {
    let productSelection = sel.value;
    for (let i of products) {
      if (i.name === productSelection) {
        productPrice.innerHTML = `$${i.price}`;
      }
    }
  }
}

products.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
products.unshift({
  name: "Select a product",
  disabled: true
});

loadProducts();
.input {
  width: 35px;
}

th,
td {
  padding: 5px 20px;
  border: 1px solid #000000;
  text-align: center;
}

.divider {
  margin-top: 20px;
  margin-bottom: 20px;
}

.no-border {
  border: none;
  background: #ffffff;
}

th,
tfoot {
  background: #e6e6e6;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <title>Shopping Cart Example</title>
</head>

<body>
  <span id="productList">Add product: </span> <span id="productPrice"></span><br /><br /> Amount: <input type="number" class="input" id="productAmount" min="0" max="10" value="0" /> <button id="addBtn">Add to cart!</button>

  <hr class="divider" />

  <h2>Shopping cart</h2>
  <table>
    <thead>
      <th>Product name</th>
      <th>Product ID</th>
      <th>Unit price</th>
      <th>Amount</th>
      <th>Subtotal</th>
    </thead>
    <tbody id="cartContent"></tbody>
    <tfoot>
      <tr>
        <td class="no-border"></td>
        <td class="no-border"></td>
        <td class="no-border"></td>
        <td><b>Totaal</b></td>
        <td id="showTotal"><b>$0.00</b></td>
      </tr>
    </tfoot>
  </table>
  <script type="text/javascript" src="script.js"></script>
</body>

</html>

How to disable a DIV when accessing site through PWA

I have developed a site and want to use it as PWA (Progressive Web App) as well.

But I want to hide specific elements in the PWA.
I have tried the CSS approach:

@media all and (display-mode: standalone) {
.noShowApp {
    display: none;
}

}

And the JS approach:

function isRunningStandalone() {
    return (window.matchMedia('(display-mode: standalone)').matches);
}

if (isRunningStandalone()) {
    alert('hi');
    hide(document.getElementById('features'));
}

I get my ‘alert’ in the App, but the section I want to hide, is not hidden….

This is the section I want to hide:

<section class="py-5 border-bottom noShowApp" id="features">

Can someone point me in the right direction on how to get any of these methods (CSS or JS) to work. I prefer the CSS approach, but if that’s not possible, JS will do just fine.