Increase qty by 1 if item already exist in cart – Reactjs/NextJS

I have found many questions similar to the subject, however, I couldn’t understand the logic, as most of these are asked/explained in the PHP/ MySQL community.

I’m building an eCommerce store, where I need to handle cart items. The problem is already mentioned in the subject. Below is a short snippet of my code.

const [cartItems, setCartItems] = useState([]) // initial state of cartItems array
const handleCartUpdate = (id,title, price, qty) => {
  // first checking if  cart is empty or not
  const cartLength = cartItems.legnth >=1 ? true : false
  // Check if item exist with the id as given in parameters
  if(cartLength) {
    const checkItemExist = cartItems.find(item => item.id == id)
    // Now, if item exist, update the propert 'qty' , My approach is as under:
    if (checkItemExist) {
      cartItems.map(product => {
        if(product.id == id) {
          return {product, qty: qty+1
        }
      }
      return product
      setCartItems(...cartItems, product)
    }
  } else {
    setCartItems(...cartItems, {...})
  }
}

After that, I am unable to understand how to update the cartItems

file JS untracked on React JS

I got this error when creating functional component i got this error:
enter image description here

the error said cannot find dile Buku.js .srccomponentsBukuBuku.Js’. but the JS file what i imported is exist and i’m sure not write wrong directory
enter image description here

How will i take product with same category into a string or an array?

How will i take product with same category into a string or an array?


<ul>
  <li class="product_cat-category-1"></li>
  <li class="product_cat-category-3"></li>
  <li class="product_cat-category-2"></li>
  <li class="product_cat-category-5"></li>
  <li class="product_cat-category-1"></li>
  <li class="product_cat-category-2"></li>
  <li class="product_cat-category-3"></li>
  <li class="product_cat-category-5"></li>
  <li class="product_cat-category-4"></li>
  <li class="product_cat-category-1"></li>
  <li class="product_cat-category-2"></li>
  <li class="product_cat-category-3"></li>
  <li class="product_cat-category-4"></li>
</ul>

what I want exactly is, to filter them and append them into a new div to create a filterable animation using gsap.
this is actually a wordpress woocommerce product page.

last time i created a popup using gsap, and in that i used something called split() function

triggers.each(function(){
    let listClassName = $(this).attr('class').split(' ');
    let revealClassName = String(listClassName[listClassName.indexOf(listClassName.find(element => element === 'dasrgsap__reveal-trigger')) + 1]);
    const sectionReveal = $('.dasrgsap__reveal-content.' + revealClassName);
    const colReveal = $('.dasrgsap__reveal-content.' + revealClassName + ' .et_pb_column');

});


the trigger was (“dasrgsap__reveal-trigger sandra”) and the popup content container was (“dasrgsap__reveal-container sandra”). both were given two separate classs, which made eaiser to split and access them.

but in this case, woocommerce products list items are given too many classes, so the only class i can play with to get a specific category is the “product_cat-‘product-category'”,

I’m want to get a string or array of the same product category,
i’m want to split “product_cat-” and “category-1” and get an array of that category but i’m not able to do it.

is this even possible?

Method to identify max and min values (or swing high / low) from a series

I’m trying to find swings / pivots in a series of data (value over time), and it seems it’s a much harder task than what it initially seemed…

I have only been able to find local max and min values (peaks). After literally seven different attempts (my own code and also adapting code from others) have failed… I don’t seem to understand how to identify a SWING (higher high or lower low).

This is is what I have:

Sample data:

const values = [{"time":1650211200,"value":40471.8},{"time":1650214800,"value":40257.5},{"time":1650218400,"value":40130},{"time":1650222000,"value":40419.9},{"time":1650225600,"value":40420},{"time":1650229200,"value":40252.4},{"time":1650232800,"value":40299.9},{"time":1650236400,"value":39999},{"time":1650240000,"value":39773.3},{"time":1650243600,"value":39800},{"time":1650247200,"value":39800},{"time":1650250800,"value":39838.8},{"time":1650254400,"value":39815.8},{"time":1650258000,"value":38970.6},{"time":1650261600,"value":39063.8},{"time":1650265200,"value":39055.6},{"time":1650268800,"value":39048.3},{"time":1650272400,"value":38986},{"time":1650276000,"value":39105.7},{"time":1650279600,"value":39099.9},{"time":1650283200,"value":39459.6},{"time":1650286800,"value":39562.4},{"time":1650290400,"value":39520.9},{"time":1650294000,"value":39355.3},{"time":1650297600,"value":39609},{"time":1650301200,"value":40378},{"time":1650304800,"value":41030.6},{"time":1650308400,"value":40700},{"time":1650312000,"value":40866.5},{"time":1650315600,"value":41067.9},{"time":1650319200,"value":40972},{"time":1650322800,"value":40950.8},{"time":1650326400,"value":41229.7},{"time":1650330000,"value":40918.9},{"time":1650333600,"value":40759.3},{"time":1650337200,"value":40773.2},{"time":1650340800,"value":40848},{"time":1650344400,"value":40850.4},{"time":1650348000,"value":40803.4},{"time":1650351600,"value":40736.7},{"time":1650355200,"value":40853.9},{"time":1650358800,"value":40759.4},{"time":1650362400,"value":40821.2},{"time":1650366000,"value":40974.8},{"time":1650369600,"value":41079.3},{"time":1650373200,"value":41460.2},{"time":1650376800,"value":41678.5},{"time":1650380400,"value":41730},{"time":1650384000,"value":41533.6},{"time":1650387600,"value":41367.5}]

Code that will detect peaks:

type Point = {
    time: string,
    value: number
}

const peaks: Point[] = [];
enum directionEnum {
    Ascending = 'up',
    Descending = 'down'
}

let direction: directionEnum = directionEnum.Ascending;
let prevVal = values[0];


for (let i=1,len=values.length; i<len; i++) {       
   
    const curVal =  values[i];

    if (prevVal.value < curVal.value) {  // (still) ascending?
        direction = directionEnum.Ascending;
    
    } else if (prevVal.value > curVal.value) { // (still) descending?

        if (direction != directionEnum.Descending) { // starts descending?

            peaks.push(prevVal);

            direction = directionEnum.Descending;
        }
    }

    prevVal = curVal;
}

Graphical example:

Results in a Chart

All the red points are the peaks (highs and lows) identified by my code. Marked in green are the ones I really need to identify, the “pivots” or “swing high and low”.

How should I do this?

Thanks in advance!

How to replace ‘undefined’ with an text message in JavaScript

I made a statement in the options. However, some options that I don’t show in the text statement will appear undefined

Instead of displaying the word undefined, I want to replace it with a text message.

Here’s my code below:

function idenmalaria() {
  var a, b, c, d, text;

  a = document.getElementById("rbc_size").value;
  b = document.getElementById("rbc_dis").value;
  c = document.getElementById("dot").value;
  d = document.getElementById("distribusi").value;
   
  if (a == 1 && b == 1 && c == 1 && d == 1) {
    text = "Plasmodium falciparum";
  } else if (a == 1 && b == 2 && c == 3 && d == 2) {
    text = "Plasmodium malariae";
  } else if (a == 2 && b == 1 && c == 2 && d == 2) {
    text = "Plasmodium vivax";
  } else if (a == 2 && b == 2 && c == 2 && d == 2) {
    text = "Plasmodium ovale";
  }

  document.getElementById("result").value = text;

}

HTML code :

<select id="rbc_size">
    <option value="1">RBC normal</option>
    <option value="2">RBC big</option>
</select>
<select id="rbc_dis">
    <option value="1">RBC distorted</option>
    <option value="2">RBC undistorted</option>
</select>
<select id="dot">
    <option value="1">Maurer dots</option>
    <option value="2">Schüffner dots</option>
    <option value="3">None</option>
</select>
<select id="distribusi">
    <option value="1">Homogeneous</option>
    <option value="2">Heterogeneous</option>
</select>

<button onclick="idenmalaria()" type="submit">Parasit</button>
<input type="text" id="result" />

Any help would be appreciated. Thank you.

What is the difference between Crypto and CryptoJS AES encryption? The results are different. (javascript

The encryption results of the two libraries are different.
Can someone give me some advice?

//Crypto
const enCrypt = (plainText, key, iv) => {
    plainText = Buffer.from(plainText);
    let cipher = Crypto.createCipheriv("AES-128-CBC", key, iv);
    let encrypted = cipher.update(plainText, "", "");
    return Buffer.concat([encrypted, cipher.final()]).toString("base64");
}

//Crypto-js
const encryptAES = (pText, init_key, init_iv) => {
    const key = CryptoJS.enc.Utf8.parse(init_key);
    const iv = CryptoJS.enc.Utf8.parse(init_iv);
    
    const cipherData = CryptoJS.AES.encrypt(pText, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return cipherData.ciphertext;
  }

//crypto-js result
ba0a16dc341853969069249a74649a865403d8887816479f3b4d907eb6f827d96364a6960009a548edae9997037cc5718e8a3655bd7181d017983cba8d8b6e798905a7bd90741569f72bfc8677e8f3e97c0bfeafef1a22aa1c3e3e0711a53cdb54f6ec088b54ed77d08914f33f86f4fdd7dd8afd95894b64d33ff5f50c226e179e35b8a5018615624b992ef6b2b8ab9a8fa08bb6052445b5baa27737fac0896930e260f3c26d129b0bfa66bc381d3e0859f0bf37713af7541ff25651119894ff

//crypto result
ugoW3DQYU5aQaSSadGSahlQD2Ih4FkefO02Qfrb4J9ljZKaWAAmlSO2umZcDfMVxjoo2Vb1xgdAXmDy6jYtueYkFp72QdBVp9yv8hnfo8+l8C/6v7xoiqhw+PgcRpTzbVPbsCItU7XfQiRTzP4b0/dfdiv2ViUtk0z/19QwibheeNbilAYYVYkuZLvayuKuaj6CLtgUkRbW6onc3+sCJaTDiYPPCbRKbC/pmvDgdPghZ8L83cTr3VB/yVlERmJT/

toggle button not functioning

I’m creating a to-do list app for my portfolio and I’d like to add a dark-mode feature for my body/background. however, my toggle button looks fine but the switch doesn’t seem to function and I can’t seem to figure out why anyone sees anything wrong or that may be interfering?

function dark() { // setting up dark-mode 
  var element = document.body;
  element.classList.toggle("dark-mode"); //dark-mode class
}
label {
  margin: 10px;
  cursor: pointer;
  width: 50px;
  height: 30px;
  display: block;
  border-radius: 50px;
  position: relative;
  color: white;
}

.switch {
  position: relative;
  display: inline-block;
  width: 110px;
  height: 10px;
  margin: 0 10px;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: aqua;
  transition: .4s;
  border-radius: 35px;
  ;
}

.switch input {
  display: none
}

.slider::before {
  position: absolute;
  content: "";
  height: 20px;
  width: 20px;
  left: 5px;
  bottom: 5px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50px;
}

input:checked+.slider {
  background-color: blue;
}

input:checked+.slider::before {
  transform: translateX(0px);
}

input:checked+.slider::after {
  transform: translateX(8px);
}
<div class="toggle">
  <label for="switch">
        <input type="checkbox" onclick="dark()" checked>
        <span class="slider"></span>
        </label>
</div>

Create array from table rows with multiple cell data

I’m trying to create a simple array with jquery from a table with only rows, but a row can contain multiple time elements.

I could only find solutions for tables with single td values and no children…

This is my table:

<div id="customhours">
    <table>
      <tbody>
        <tr>
          <td>Tuesday</td>
          <td>
            <time>17:00 - 18:00</time>
          </td>
        </tr>
        <tr>
          <td>Friday</td>
          <td>
            <time>16:00 - 17:00</time>
            <time>17:00 - 18:00</time>
          </td>
        </tr>
      </tbody>
    </table>
</div>

The array I’m looking for is:

[["Tuesday", "17:00 - 18:00"], ["Friday", ["16:00 - 17:00, 17:00 - 18:00"]]]

Any help would be appreciated.

Why aren’t my IF conditions being met? (checkbox.isChecked(), and checkbox == true methods not working)

I’m attempting to apply borders to cells conditionally via apps script, but my code is not registering the two (obviously met) conditions. Looking for a logic and syntax check <3

Sheet:
stackoverflow noobs can’t attach images so here’s a link

Code:

function doBorders() {
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let sss = ss.getActiveSheet();
  let doBorder = sss.getRange("A5");
  let checkBox = sss.getRange("B5");
  let checkState = checkBox.isChecked();
    let bRow1 = sss.getRange("A1:B1");
    let bRow2 = sss.getRange("A2:B2");
    let bRow3 = sss.getRange("A3:B3");

  if (doBorder == "Do Borders:" && checkState == true) {
    bRow1.setBorder(false, false, true, false, false, false,'Black', SpreadsheetApp.BorderStyle.SOLID);
    bRow2.setBorder(false, false, true, false, false, false,'Black', SpreadsheetApp.BorderStyle.SOLID);
    bRow3.setBorder(false, false, true, false, false, false,'Red', SpreadsheetApp.BorderStyle.SOLID);
    Logger.log('Conditions met. Borders added.');

    } else
      bRow1.setBorder(false, false, false, false, false, false);
      bRow2.setBorder(false, false, false, false, false, false);
      bRow3.setBorder(false, false, false, false, false, false);
      Logger.log('Conditions not met. No borders.');
}

I’ve tried both checkBox == true and checkState == true. Same result.

Execution Log:
“Conditions not met. No borders.”

How to remove local storage item for duration so modal doesn’t show?

Goal is to remove local storage item after 24 hours, meaning show modal only once per day everyday. The local storage value is set. However, my condition to check if local storage item does not exist and 24 hours have passed then show modal is only half way working. I need it to expire the modal (not show) if the local storage value has been set for less than 24 hours. Currently, it is not removing the local storage item and showing the modal only once on load. If refresh page after time frame the local storage item is still there. Using Sweet Alert for modal, but that should not matter I don’t think. Also not sure if I need a for loop or set time interval for this.

To make testing easier for a one minute duration you can also use:

 expires = expires.setMinutes(expires.getMinutes() + 1);

Here is what I tried:

$(document).ready(function() {
      if (window.localStorage) {
        var currentUser = '<%= current_user %>';
        var swal_alert = localStorage.getItem('alert');
        var currentTime = new Date($.now());
        var expires = new Date();
        expires = expires.setHours(expires.getHours() + 24);
          if (currentUser && swal_alert !=1 && currentTime < expires) {
              swal ({
                  icon: 'warning',
                  text: 'Notice text here.',
                  closeOnClickOutside: false,
                  button: 'ok'
              })
          } else {
              localStorage.removeItem('alert');
          }

          localStorage.setItem('alert', '1');
      }
}

How to apply styles to react native component with array map

I can’t get the application to work due to errors, unfortunately I did not find a solution on the Internet, so I ask here, what is the error?

This is my App.js code:

const users = [
    {
        name: 'Benedict Cumberbatch',
        phone: '+1 17 327 13 89',
        total: 91
    },
    {
        name: 'John Wick',
        phone: '+4 77 623 76 89',
        total: -98
    },
    {
        name: 'Ryan Thomas Gosling',
        phone: '+1 37 717 24 11',
        total: 3902
    }
];

const Footer = () => {
  return 'wefwefwefwe';
};

const BackButton = () => {
  return '<Button title="Back">';
}

const Users = () => {
    let userIconLetter = 'A';

    return users.map((user, index) => {
        return (
            <div style={styles.userCard} key={index}>
                <div style={styles.userIcon}>
                    <span style={styles.userIconLetter}>
                        {userIconLetter}
                    </span>
                </div>
                <div style={styles.userData}>
                    <div style={styles.userName}>
                        {user.name}
                    </div>
                    <div style={styles.userPhone}>
                        {user.phone}
                    </div>
                </div>
                <div style={styles.userValue(props.props.total > 0)}>
                    {user.total}
                </div>
            </div>
        )
    })
}

export default function App() {
  return (
    <View style={styles.container}>
        <ScrollView>
            <Users />
        </ScrollView>
        <Footer>
            <BackButton style={styles.navigationButton} />
        </Footer>
    </View>
  );
}

and main.js in styles:

import { StyleSheet} from 'react-native';
const styles = StyleSheet.create({
    container: {
        flex: 1,
        fontFamily: "'Roboto', sans-serif",
    },
    navigationButton: {
        padding: "10px 15px",
    },
    userIcon: {
        width: "50px",
        height: "50px"
    },
    userCard: {
        color: 'black'
    },
    userIconLetter: {
        color: 'black'
    },
    userData: {
        color: 'black'
    },
    userName: {
        color: 'black'
    },
    userPhone: {
        color: 'black'
    },
    userValue: (positive) => {
        let color = positive ? 'green' : 'red';
    
        return {
            color: color,
        };
    },
})

export { styles }

I’ve got errors for every user block:

The above error occurred in the component:

div div div Users div
./node_modules/react-native-web/dist/exports/View/index.js/View<@http://localhost:19006/static/js/bundle.js:35666:19
div
./node_modules/react-native-web/dist/exports/View/index.js/View<@http://localhost:19006/static/js/bundle.js:35666:19
./node_modules/react-native-web/dist/exports/ScrollView/ScrollViewBase.js/ScrollViewBase<@http://localhost:19006/static/js/bundle.js:32894:18
ScrollView ScrollView div
./node_modules/react-native-web/dist/exports/View/index.js/View<@http://localhost:19006/static/js/bundle.js:35666:19
App
ExpoRootComponent@http://localhost:19006/static/js/bundle.js:4196:83
div
./node_modules/react-native-web/dist/exports/View/index.js/View<@http://localhost:19006/static/js/bundle.js:35666:19
div
./node_modules/react-native-web/dist/exports/View/index.js/View<@http://localhost:19006/static/js/bundle.js:35666:19
AppContainer@http://localhost:19006/static/js/bundle.js:32304:18

Consider adding an error boundary to your tree to customize error
handling behavior. Visit https://reactjs.org/link/error-boundaries to
learn more about error boundaries.

And one error at the end:

Uncaught Error: The style prop expects a mapping from style
properties to values, not a string. For example, style={{marginRight:
spacing + ’em’}} when using JSX.

CSS HTML Split paragraph text to column in single tag

I wanna make dynamic paragraph column text like this
enter image description here

but only display in html with :

<div>
  <p>
    Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit amet consectetur adipisci[ng] velit, sed quia non numquam [do] eius modi tempora Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit amet consectetur adipisci[ng] velit, sed quia non numquam [do] eius modi tempora 
  </p>
</div>

is that possible to do that in only using single tag p on html?

the text will be split when the content height exceeds 125px

How to convert pdfFileFormat string to a blob in Javascript (for uploading it to firebase)?

I get a response of pdf file format as shown below:

'%PDF-1.5rn4 0 objrn<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 612 792]/Resources<</Font ....

It seems to be some encoded string and all I want is to be able to create Object Url or the blob out of it that I could use to upload in firebase. I am not sure how to do that. Can someone help?

JS – Make [].includes case sensitive [duplicate]

Task:

I need to check, if from given string(characters) document can be made(document) if at least 1 character is missing in characters then it is not possible to create document

Occuring problem:

When comparing ‘a’ and ‘A’ with [].includes method, it returns ‘false’ in the function.

Code:

function generateDocument(characters, document) {
    document = Array.from(new Set(document));
    characters = Array.from(new Set(characters));

    for(let i = 0; i < document.length; i++) {
        if(characters.includes(characters[i]) == false)
            return false;
    }
    return true;
}

console.log(generateDocument("A","a"));

Expected result: To return false, because ‘a’ and ‘A’ are not equal