React Native: Counter not showing correct updated state

Im trying to put together a simple counter which changes the quantity of an item. Using Hooks to manage its state, i update the value on screen correctly. However, the value the state holds when i console log is always one less than the value on the screen.

For example:

If starting value is 1, after pressing the plus button, the value on screen changes to 2 but in console the state value is still 1.

Setup of Hooks and functions controlling the count:

//Set Item price
const [itemPrice, setItemPrice] = useState(itemOptions[0].price)

//Counter Control
 const [disableMinus, setDisableMinus] = useState(true);

const addQuantity = () => {
    if (quantity === 1) {
        setQuantity(quantity + 1);
        setDisableMinus(false);
    } else {
        if (quantity > 1){
            setItemPrice(itemOptions[0].price * quantity);
            setQuantity(quantity + 1);
            setDisableMinus(false);
        }
    }
}
const minusQuantity = () => {
   if (quantity === 1){
       setDisableMinus(true);
   } else {
       if (quantity > 1) {
           setQuantity(quantity - 1);
           setDisableMinus(false);
       }
   }
} 

return (
    <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: "center", paddingVertical: 20}}>

    <TouchableOpacity disabled={disableMinus} onPress={() => minusQuantity()}>

        <AntDesign style={{color: '#37BD6B'}} name="minuscircle" size={30}/>

    </TouchableOpacity>

    <Text style={{paddingHorizontal: 10, fontWeight: '700', fontSize: 30}}>{quantity}</Text>

    <TouchableOpacity onPress={() => addQuantity()}>

        <AntDesign style={{color: '#37BD6B'}} name="pluscircle" size={30}/>

    </TouchableOpacity>

)

Thanks in advance

Sorting an object of an object by value in typescritpt

I have an object that contains object and need to sort it by count

var obj={
  "error1":{
    "count":45,
    "ids":['123','352']
  },
  "error2":{
    "count":3,
    "ids":['13','2']
  },
  "error3":{
    "count":15,
    "ids":['42','7']
  }
}

I want to sort by count that the result would be

var obj={
   "error2":{
    "count":3,
    "ids":['13','2']
  },
   "error3":{
    "count":15,
    "ids":['42','7']
  },
  "error1":{
    "count":45,
    "ids":['123','352']
  }
}

How can I do that

I don’t know how to make zoom out animation for multiple photos

<div class="hero_apartment">
 <img src="imghero_1.svg", alt="">
 <img src="imghero_1.svg", alt="">
 <img src="imghero_1.svg", alt="">
</div>
.hero_apartment > img{
    max-width: 100%;
    animation: zoomout 3s linear;
}
  
@keyframes zoomout {
    0% {
      transform: scale(1.3);
    }
    100% {
      transform: scale(1);
    }
}

I want to make the animation like the hero section of this website, http://igisresidencereit.com/. I know how to make zoom out animation for one photo, but I don’t know how to make the animation for multiple photos. Please Help!

text blinking in textarea

I have the following code :

<!doctype html>
<html  lang="en">
<head>
    <title>list application</title>
    <meta charset="utf-8" />
    <!--<script src="../js/task.js" ></script>-->
    <style>
    #pos{
        position: absolute;
        bottom: 25px;
        text-align:center;
        }
    
    form{
        padding-left:70px;}
        
    h1{padding:50px; color:blue}
    
    #body {border:5px solid black;}
    </style>
    <script>
i = 0;
function add_task(){
    return document.getElementById("tasklist").value += (document.getElementById("addtask").value+"n");
}
    </script>
</head>
<body>
    <header>
    <h1>To Do list</h1>
    </header>
    
    <form name="form1">
        <label for="addtask">Add task : </label>
        <input type="text" id="addtask"/>
        <button id="ad" onclick="add_task()">Add task</button><br><br>
        <label style="vertical-align:top;">Task list :</label>
        <textarea id="tasklist" rows=10>
        </textarea>
        <div id="pos">
            <label for="nexttask">Next task : </label>
            <input type="text" id="nexttask"/>
            <button id="nt" onclick="next_task">Show Next task</button><br>
    
    </div>
    </form>
</body>
</html>

I need to copy the text entered in textbox and paste in the textarea. But the text is displayed and erased immediately like blinking. I want that to be displayed permanently.

Please guide me!

How to exclude sub div in javascript

I have two div. <div class="item__head"> and sub div <div class="card__btn">

If someone clicks on my root div they will get redirected to example.com and when someone clicks sub div they are redirecting to example.com & example.net, they are getting redirected two both link. one in same tab and another in new tab.

I want, if someone clicks on root div they should get redirect to example.com and when someone clicks on sub div button they should only be redirected to example.net not example.com

how to exclude sub div <div class="card__btn"> from javascript.

Code :

const webPage = document.querySelectorAll("#openWebsite");
webPage.forEach((e) => {
    e.addEventListener("click", () => {
        const site = e.getAttribute("data-site");
        window.open(site, "_blank") || window.location.replace(site);
    });
});
<div class="item__container">
            <div class="card" id="openWebsite" data-site="https://example.com">
                
                <div class="card__btn">
                    <a href="https://example.net">

                        Visit Site
                     
                    </a>
                </div>
                </div>
                </div>

Already tried from jQuery exclude elements with certain class in selector

document.querySelectorAll("#openWebsite").not(".card__btn");

openai api Cannot read properties of undefined (reading ‘0’) on res

openai api Cannot read properties of undefined (reading ‘0’) on res

not sure if I made a mistake on a portion of fetch? I hope someone can lookover–

I see the submit works fine through curl. On network log, the request shows the input correctly though still 500 error.

submit comp:

import React, { useState, useEffect } from 'react'
import { useAppDispatch, useAppSelector } from '../../../../hooks/useRedux'
import { setTemplateOutput } from '../../../../redux/features/templatesSlice'
import GenerateButton from '../generate-button.component'

interface RootState {
  menu: any
  utils: any
}

const DefaultTemplate = () => {

  const amtOfInputChars = 380
  const [charCount, setCharCount] = useState(0)
  const [templateInput, setTemplateInput] = useState('')

  const textAreaHandler = (e: any) => {
    setCharCount(e.length)
    setTemplateInput(e)
  }

  const onSubmit = async (e: any) => {
    e.preventDefault()
    console.log('submit')

    const response = await fetch('/api/templates/default', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        promptData: templateInput,
      }),
    })

    const data = await response.json()
    useAppDispatch(setTemplateOutput(data.result))
    setTemplateInput('')
  }

  useEffect(() => {}, [templateInput])

  return (
    <div>
      <p className="pt-6 text-sm font-light">
        {/* amtOfInputChars - count */}
        <span
          className={`rounded-xl px-3 py-1 font-semibold text-white ${
            amtOfInputChars - charCount === 0 ? 'bg-red-600' : 'bg-gray-400'
          } shadow-xl`}
        >
          {amtOfInputChars - charCount}
        </span>{' '}
        - Input characters left!
      </p>
      <form>
        <div className="pt-4">
          <textarea
            maxLength={amtOfInputChars}
            className=" form-input text-md transition-color h-44 w-full resize-none rounded-lg border-2 border-gray-300/80 p-4 font-light outline-none duration-300 ease-in-out focus:border-accent2"
            placeholder="Enter your text here"
            onChange={(e) => textAreaHandler(e.target.value)}
            value={templateInput}
          />
        </div>
        {/* generate content */}
        <div className="flex justify-center">
          <div className="fixed bottom-16 z-20 pt-36 lg:bottom-0 ">
            <div className=" items-center space-x-3 px-6 py-5">
              <GenerateButton onClick={(e: any) => onSubmit(e)} />
            </div>
          </div>
        </div>
      </form>
    </div>
  )
}

export default DefaultTemplate

API:

const { Configuration, OpenAIApi } = require('openai')

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
})
const openai = new OpenAIApi(configuration)

export default async function (
  req,
  res
) {
  let promptData = req.body.text
  const completion = await openai.createCompletion('text-davinci-002', {
    // prompt: generatePrompt(req.body.text),
    prompt: promptData,
    temperature: 0.6,
    max_tokens: 500,
  })
  res.status(200).json({ response: completion.choices[0].text })
}

// function generatePrompt(text: string) {
//   return `Suggest three names for an animal that is a superhero.
//
// Animal: Cat
// Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
// Animal: Dog
// Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
// Animal: ${text}
// Names:`
// }

after submit I get the error:

TypeError: Cannot read properties of undefined (reading '0')
  17 |     max_tokens: 500,
  18 |   })
> 19 |   res.status(200).json({ response: completion.choices[0].text })
     |                                                      ^
  20 | }
  21 | 
  22 | // function generatePrompt(text: string) {

Hiding multiple select menus in a form

I have a form that contains 5 select menus. Each menu has different ID / contents etc, but they all have an intial default option value of None. For example…

<select id="Menu_One" name="Menu_One">
<option value="None">None</option>
<option value="SomeValue">A value</option>
</select>

<select id="Menu_Two" name="Menu_Two">
<option value="None">None</option>
<option value="SomeValue">A value</option>
</select>

…and so on.

Once a user has completed the form, I’d like to feature a button that, when clicked, hides any select menu that has been left at the default value of “None”.

Have racked my brain to work this one out, but am obviously missing something simple. Ideally needs to be a Javascript / jQuery solution.

Any ideas?

Two toggles for dark mode – one of the toggles not changing when prompt but the function is working

So I am making a dark mode for a shopify. So far everything has worked but I want to have the same toggle in two locations, one for mobile, and one for desktop, since I have a sidebar menu on mobile. I added a forloop.counter on my elements ID=”” and For=”” so that I could use the same ID twice and everything works fine but the desktop toggle does not change the icon.
Instead of going Moon -> Sun it stays a Moon.

Here is my code. I am mostly a front-end web designer using liquid therefore bare with me if my code is not perfect.

Thank you so much for your help!!!!!!

Lola

this is my two toggles

    <div  class="ml-4 whitespace-nowrap toggle-switcher-1" onclick="toggled(this)">
            <input type="checkbox" id="theme_{{forloop.counter}}" class="toggle-input" checked>
                <label for="theme_{{forloop.counter}}" class="inline-block w-8 h-8 align-middle">
                    <img src="CoterieWebSymbols-04.png"  alt="Dark mode" class="toggle-icon">
                </label>
         </div>

    <div  class="ml-4 whitespace-nowrap toggle-switcher-1" onclick="toggled(this)">
            <input type="checkbox" id="theme_{{forloop.counter}}" class="toggle-input" checked>
                <label for="theme_{{forloop.counter}}" class="inline-block w-8 h-8 align-middle">
                    <img src="CoterieWebSymbols-04.png"  alt="Dark mode" class="toggle-icon">
                </label>
         </div>

this is my javascript

<!-- toogle for dark mode -->
<script type="text/javascript">
const page = document.querySelector('body');
const toggle = page.querySelector('.toggle-input');
const toggleIcon = page.querySelector('.toggle-icon');
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");


// set theme and localStorage on page load
setCheckedState();
  

function setCheckedState() {
  // checks if localStorage has a "checked" value set at all
  if (!(localStorage.checked === undefined)) {
    // if it does, it sets the state of the toggle accordingly
    toggle.checked = isTrue(localStorage.getItem('checked'));
    // after setting the toggle state, the theme is adjusted according to the checked state
    toggleTheme();
  }
}

function toggleTheme() {
  // Toggle theme based on state of checkbox
  replaceClass();
  // replace icons on page
  toggleIconTheme();
  // set the value of the "checked" key in localStorage
  updateLocalStorage();
}

function replaceClass() {
  if (toggle.checked) {
    page.classList.replace('light', 'dark');
  } else {
    page.classList.replace('dark', 'light');
  }
}

function toggleIconTheme() {
  // Replace icons not able to be targeted by css variables
  if (page.classList.contains('light')) {
    toggleIcon.src = 'CoterieWebSymbols-04.png';
    toggleIcon.alt = 'Switch to Dark Mode';
  } else  {
    toggleIcon.src = 'CoterieWebSymbols-05.png';
    toggleIcon.alt = 'Switch to Light Mode';
  }
}


function updateLocalStorage() {
  localStorage.setItem('checked', toggle.checked);
}

function isTrue(value) {
  // convert string to boolean
  return value === 'true';
}

// Toggle theme any time the state of the checkbox changes
toggle.addEventListener('change', toggleTheme);
// This code assumes a Light Mode default
  
</script>

Handle API to not receive value less than 0 (negative values)

I need to treat the API result so that I don’t receive values less than 0, I’ve been trying this way and so far I haven’t been able to:

private handleChart(data: Object): void {
    const series = [];

    for (const [key, value] of Object.entries(data)) {
      series.push({
        name: key,
        data: value,
        type: "line",
      });
    }
    
    if (series[0].data.length < 0) {
      delete series[0].data;
    }
    console.log(data );  

    this.plotChart(series);
  }

Original code:

private handleChart(data: Object): void {
    const series = [];

    for (const [key, value] of Object.entries(data)) {
      series.push({
        name: key,
        data: value,
        type: "line",
      });
    }

    this.plotChart(series);
  }

Sort() in JavaScript

Hello friends

  • how to arrange a number string with several characters?
  • I converted to a number, but it only gives me one 2
     <input type="text" name="numbers" id="numbers" readonly value="2, 4, 14, 10, 90, 23, 16"/>
    
     <button type="button" id="run">Lancer le script</button>
    

Run the script

(() => {
// to get the value of an input: document.getElementById("element-id").value

document.getElementById("run").addEventListener("click", () => {
   
   
});

})();

How do I show one of the divs sequentially when the page is refreshed?

How do I show one of the divs sequentially when the page is refreshed? for example, div 1 will appear when the page is opened, and when the page is refreshed, div 2 will change to 3 – 4 -5 on the next refresh, and when the queue is finished, it will return to the beginning.

example i’m working on :

     <style>
            .category {
                display: none;
            }
        </style>
        <div class="category">1</div>
        <div class="category">2</div>
        <div class="category">3</div>
        <div class="category">4</div>
        <div class="category">5</div>
    <script>
     $(document).ready(function () {
                let divs = document.querySelectorAll(".category");
                console.log(divs.length);
                for (let index = 0; index < divs.length; index++) {
                    $(divs[index]).show()
                }
            });
</script>

but here it shows all when the page is loaded. How can I solve this?