useEffect empty dependency array inside a component which gets rendered inside useCallback has no meaning

I have a payment page, the user clicks on the button “PAY”, then a modal opens, it shows loading…, then it either renders the “payment success” component or the “payment failed” component.

When it renders any of the both, it plays a sound effect,

  • on success, it plays the sound effect of CheckTennnn! ✅ “payment success”.
  • on fail, it plays the sound effect of EEeerr.. ❌ “payment failed”.

The way I am implementing it is by having a useCallback which decides which view to render inside the modal, [success, or the fail view].

export default ProcessPaymentModal({ isSuccess, isError, isLoading }){
    const [timer, setTimer] = useState(0)
    
    useEffect(()=> { 
        const intervalId = setInterval(()=> setTimer((previousState)=> previousState + 1), 1000)
        return ()=> clearInterval(intervalId)
    })

    const View = useCallback(()=>{
      switch(true){
         case isSuccess:
           return <PaymentSuccessView timer={timer}/>
         case isError:
           return <PaymentFailView timer={timer}/>
         case isLoading:
           return <LoadingView />
      }
    }, [timer, isSuccess, isError, isLoading])

    return <View />
}

And inside these fail or success components, I have that useEffect which plays the audio only once, on mount (and it must only play the sound once).

export default function PaymentSuccessView({ timer }) {
  useEffect(() => {
    const soundEffect = new Audio('../media/checktennn.mp3')
    soundEffect.play()
  }, []);
  return <button> OK ({timer}) </button>;
}

Here’s a stack blitz instance, a code sandbox to test, (Click me)

However, the problem is that it keeps playing the sound every time the timer changes,

  • CheckTennnn! ✅
  • CheckTennnn! ✅
  • CheckTennnn! ✅

Like this, you know.

Even though I have the dependency array empty in the <PaymentSuccessView /> component, which means this useEffect function must only run once. On mount.

How to sort alphanumeric + special charcters string in ascending and descending order?

I’ve a stringlike this =

{"as110@-qw","qw1230_2", "987wuro","731", "234", "@33", "445qwert"}
case 'staffCode':
  if (sortBy == 1) {
    return a[query.keyName].localeCompare(b[query.keyName], undefined, { numeric: true, sensitivity: 'base' })
  } else {
    return b[query.keyName].localeCompare(a[query.keyName], undefined, { numeric: true, sensitivity: 'base' })
  }

I cannot turn off my extension from button at Popup.html

I am developing extension in manifest version 3. My extenison’s purpose is to notify user if they are using chrome for more than 2 hours. i have created notification via timer in background.js and when a user clicks on the button at notification it must open Break.html in new tab at browser. I have done this functionality. Now, I want to turn off my extension from button at POPUP.HTML via popup.js. So that, when a user clicks on this button it must stop seeing those notifications from my extension. I have used

chrome.management.setEnabled("Extension ID", false);

but this entirely stops my extension from chrome://extensions/ I want some other way to stop my extension.
here is my code:
BACKGROUND.JS

//===creating notification===
  var notifyTimer = setInterval(func,20000);
  function func(){ 
  var opt = {
    type: "image",
    title: "E-Gym",
    message: "You have been working for too long on Chrome. Would you like to take a break?",
    iconUrl: "logo.png",
    requireInteraction: true,
    imageUrl: "background.png",
    buttons: [{
      title: "Let's Begin Workout"  }]
  };
  chrome.notifications.create(opt, creationCallback);
  
  function creationCallback(id){
    myNotificationID = id; 
    }
    
}
//===Opening break page when notification button is clicked======
chrome.notifications.onButtonClicked.addListener(function(notifId) {
  
 
    chrome.tabs.create({ url: "break.html" })
});

POPUP.HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="storyboardstyle.css">
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> 
    </head>
    
    <body style="width: 280px; height: 210px; background-color:#f9c8c4"> 
        <div style="position: absolute; left:5px; top:5px; background-color: none; border: 2px solid rgb(203, 50, 91); color:antiquewhite; width:270px; height: 200px;"></div>  
        <div id="heading-gympass"><h1><b>E-GYM</b></h1>  
        <button  id="stop_btn">Stop Extension</button><div> 
 
            
            
        <script src="popup.js"></script>
        
    </body>
</html>

POPUP.JS

const startBtn = document.getElementById("stop_btn");
startBtn.addEventListener("click", myFunction);
function myFunction() {
  
// I WANT SOME CODE to stop extension 
// I have used chrome.management but it disables my entire extension from chrome://extensions/
// chrome.management.setEnabled("Extension ID", false);
  
}

I want to write some code in popup.js to stop my extension functionality.Can anyone help me to write code to stop extension or stop execution of background.js

(HTML)Load, edit, save config.txt file in web browser

Thanks for read.

I’m very new at html coding. I’m pythone or arduino coder, but my boss make me to work on html too…
I’m trying to make web page (test.html) work as below

  1. page loaded.
  2. click ‘load config’ button
  3. load config.txt file from same folder with html file (server’s root folder)
    -print ‘load done’ when sucess or ‘failed’
  4. show config.txt file on textarea
  5. edit something
  6. click ‘save confgif’ button
  7. textarea overwrite ‘config.txt’ on same folder
    -print ‘save done’ when sucess or ‘failed’

I couldn’t find exact code for this.
The most similar thing I found was this on link

https://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/

<html>
<body>
 
<table>
    <tr><td>Text to Save:</td></tr>
    <tr>
        <td colspan="3">
            <textarea id="inputTextToSave" cols="80" rows="25"></textarea>
        </td>
    </tr>
    <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
    <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad"></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </tr>
</table>
 
<script type="text/javascript">
 
function saveTextAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
 
    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
 
    downloadLink.click();
}
 
function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}
 
function loadFileAsText()
{
    var fileToLoad = document.getElementById("fileToLoad").files[0];
 
    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}
 
</script>
 
</body>
</html>

The security issue is off the table.
(it considered at before loading web page)

I’ve tried to find command line for deignate file’s loot but I’ve failed.

how could I change file loding process from client’s local upload file to server’s root file?

Execute promise after 2 seconds only when previous element is done [duplicate]

I have the following code;

const query1 = Character.findOneAndUpdate(filter, update); // mongoose update query

let queries = [query1, query2, query3, .... query10000]
let chunksArr = [];

while(queries.length){
  const chunk = queries.splice(0, 1000)
   chunksArr.push( chunk )
}

Notice where I defined the query1, I didn’t use await with it. that’s because in later while loop I’m dividing queries array (of 10000) in to 10 smaller arrays so that chunksArr is an array of array where each array contains 1000 unfinished queries. I am aware of Promise.all(chunksArr) which will allow these queries to run in parallel. but I want to execute each element (which is an array) in chunksArr after 2 seconds only when previous element is done. which means sequentially. Is there any way to do this? Any help will be greatly appreciated. Thanks

Not Modify Input Text Value But MODIFY only a part of INPUT TEXT [duplicate]

How to modify the Input Value in React. Suppose the input value is “My name is John Cena”. How do I modify the input value as

“My name is John Cena

John Cena 21

          render() {
              return (
                  <div>
                      <input
                          type="text"
                          value="My name is John Cena"
                      />
                  </div>
              )
          }
      }

      export default Module

I tried

value="My name is <b>John Cena</b>"

value=`My name is ${<b>}John Cena${</b>}`

Nothing works.

Footer Causing React application to not load

i am trying to launch my react app and when i do NPM start the app compiles but chrome will not load the app just gives me Error code: Out of Memory. It has somthing to do with the footer when i remove the footer tag from the portfolio container it loads, but with it i get the above error.

import React, { useState } from 'react';
import NavTabs from './NavTabs';
import Home from './pages/Home';
import Projects from './pages/Projects'
// import About from './pages/Home';
import Resume from './pages/Resume';
import Contact from './pages/Contact';
import Footer from './Footer';
export default function PortfolioContainer() {
  const [currentPage, setCurrentPage] = useState('Home');

  // This method is checking to see what the value of `currentPage` is. Depending on the value of currentPage, we return the corresponding component to render.
  const renderPage = () => {
    if (currentPage === 'Home') {
      return <Home />;
    }
    if (currentPage === 'Projects') {
      return <Projects />;
    }
    if (currentPage === 'Resume') {
      return <Resume />;
    }
    return <Contact />;
  };

  const handlePageChange = (page) => setCurrentPage(page);

  return (
    <div>
      <div className="portfolio-container">
      {/* We are passing the currentPage from state and the function to update it */}
      <NavTabs currentPage={currentPage} handlePageChange={handlePageChange} />
      {/* Here we are calling the renderPage method which will return a component  */}
      {renderPage()}
    </div>
    <Footer />
    </div>
  );
}

Proses kerja input output komputer

Perangkat input mengirimkan informasi ke sistem komputer untuk diproses, sedangkan perangkat output menghasilkan atau menampilkan hasil dari proses tersebut. Contoh dari perangkat output antara lain: monitor, speaker, printer, amplifier, proyektor.

I just to do my homework, so just ignore this question

HTTP fetch in react native gives 304 error on fetch and does not show database data

My backend REST api is written in Node.Js and MongoDB

So i am trying to make the request from a React native application and I am getting Http 304, for some reasons i do not seem to understand and hence, I decided to come on here to see if there was a possibility of a resolve. Sought the internet, it seems its a known problem, but no viable solution.

My source code is looking like this

import React, {useEffect, useState} from 'react';
import {
  ActivityIndicator,
  Button,
  Image,
  ImageBackground,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {Header, Avatar, Icon, Card} from '@rneui/themed';
import {FlatList, ScrollView} from 'react-native-gesture-handler';
import {useNavigation} from '@react-navigation/native';
import {Tab} from '@rneui/base';
import AsyncStorage from '@react-native-async-storage/async-storage';

const HomePage = () => {
  const [transaction_details, setTransaction_details] = useState([]);
  const [isLoading, setLoading] = useState(true);

  const navigation = useNavigation();

  const Item = ({title}) => (
    <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );

  FlatListItemSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: 350,
          backgroundColor: '#D3D3D3',
        }}
      />
    );
  };

  showdata = async () => {
    let token = await AsyncStorage.getItem('token');
    alert(token);
  };

  getTransactionsList = async () => {
    let token = await AsyncStorage.getItem('token');
    let email = await AsyncStorage.getItem('email');

    fetch('https://***********/api/user-data/get-transactionby-email/' + email, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
    })
      .then(response => response.json())
      .then(responseJson => {
        setTransaction_details(responseJson.results);
        setLoading(false);
      });
  };

  useEffect(() => {
    //showdata();
    getTransactionsList();
  });

  /*useEffect(() => {
    fetch('https://brotherlike-navies.000webhostapp.com/people/people.php', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-type': 'application/json',
      },
    })
      .then(response => response.json())
      .then(responseJson => {
        setTransaction_details(responseJson);
        setLoading(false);
      });
  }, []);
  */

  return (
    <View style={{flex: 1}}>
      <Header
        containerStyle={{
          backgroundColor: 'transparent',
          justifyContent: 'space-around',
        }}
        leftComponent={
          <Avatar
            small
            rounded
            source={{
              uri: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSiRne6FGeaSVKarmINpum5kCuJ-pwRiA9ZT6D4_TTnUVACpNbzwJKBMNdiicFDChdFuYA&usqp=CAU',
            }}
            onPress={() => console.log('Left Clicked!')}
            activeOpacity={0.7}
          />
        }
        rightComponent={
          <Icon
            name={'mail-outline'}
            color={'#00BB23'}
            size={32}
            onPress={() => navigation.navigate('Accounts')}
          />
        }></Header>

      <ImageBackground
        source={{
          uri: 'asset:/logo/bg.JPG',
        }}
        imageStyle={{borderRadius: 6}}
        style={{
          top: 15,
          paddingTop: 95,
          alignSelf: 'center',
          width: 328,
          height: 145,
          borderadius: 9,
          justifyContent: 'center',
          alignSelf: 'center',
          alignItems: 'center',
        }}>
        <View>
          <Text style={styles.accText}>Wallet Balance</Text>
          <Text style={styles.text}> 250,000 </Text>
        </View>
      </ImageBackground>
      <View>
        <Text
          style={{
            fontFamily: 'Poppins-Bold',
            flexDirection: 'row',
            paddingTop: 55,
            fontSize: 15,
            left: 18,
            color: 'gray',
          }}>
          Recent Transactions
        </Text>
      </View>
      <View style={{flex: 1, marginTop: 35}}>
        {isLoading ? (
          <ActivityIndicator />
        ) : (
<FlatList
    data={transaction_details}
    ItemSeparatorComponent={this.FlatListItemSeparator}
    renderItem={({ item }) => {
      return (
        <View>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text>{item.narration}</Text>
            <Text>{item.amount}</Text>
          </View>
          <Text>{item.date}</Text>
        </View>
      )
    }}
    keyExtractor={(item) => item.id.toString()}
 />
        )}
      </View>
    </View>
  );
};

export default HomePage;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
  },

  paragraph: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  text: {
    top: -85,
    fontSize: 30,
    color: 'white',
    textAlign: 'center',
    fontFamily: 'Poppins-Bold',
  },
  mainContainer: {
    paddingTop: 90,
    justifyContent: 'center',
    alignItems: 'center',
  },
  accText: {
    top: -85,
    paddingTop: 10,
    justifyContent: 'center',
    alignItems: 'center',
    fontFamily: 'Poppins-Medium',
    color: 'white',
    textAlign: 'center',
  },
  PayeeName: {
    justifyContent: 'flex-start',
    flexWrap :'wrap',
    fontFamily: 'Poppins-Medium',
    size: 800,
    fontWeight: 'bold',
  },
  amountValue: {
    textAlign:'right',
    fontFamily: 'Poppins-Medium',
    size: 800,
    fontWeight: 'bold',
  },
});

I do not seem to understand why this is not working as expected. Someone should please give a guide as to what is going on.

How to get value from an object searched key is in string

I have an object

const lead = {
  companies: [{
    schoolName: "ABC",
    education: "Graduation"
  }, {
    schoolName: "DEF",
    education: "Graduation2"
  }],
  hello: 'world',
  education: {
    graduation: 'true',
  },
  nameArray: ['hello', 'world']
}

Variable I am getting from frontend

‘companies[0].schoolName’

I just have to send the value if it exists in the object

Javascript Points Edits

I have searched many pages and I have not found anything, I already have points that form a 3d shape, I just need to fill them in with the method of editing these Points of the Rects, I don’t know if there will be a way.

The way I can think of is to deform the Points of the Rects and place them at each point. but I don’t know how to edit these coordinates.

If possible without libraries, I Request Answers!

Display controller variable on a Laravel blade using jQuery

In my laravel app, I have a div on a blade to display total number of daily orders.

<div class="row mt-3" id="shopify_row1">
        <div class="col-md-2" id="shopify_widget1">
            <div class="jumbotron bg-dark text-white">
                <img class="img-fluid pull-left" src="https://cdn0.iconfinder.com/data/icons/social-media-2092/100/social-35-512.png" width="32" height="32">
                <h6 class="text-secondary mt-2 px-4">Shopify</h6>
                <hr class="border border-white">
                <h5 class="text-white">Total Orders</h5>
                <span class="tot_o" id="tot_o">{{ $tot_o }}</span> 
            </div>
        </div>
</div>

I get this $tot_o via controller.

Following is my index() in the controller

if($request->has('selected_date')){
                $selected_date=$request->selected_date;
                $url = "https://[email protected]/admin/api/2022-10/orders/count.json?status=any&created_at_max=".$selected_date."";
            }else{
                $selected_date = date('Y-m-d');
                $url = "https://[email protected]/admin/api/2022-10/orders/count.json?status=any&created_at_min=".$selected_date."";
            }
            $curl = curl_init( $url );
            curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $json_response = curl_exec($curl);
            curl_close($curl);
            $result_1 = json_decode($json_response, TRUE);
            $tot_o = $result_1['count'];
  return view('dashboard.index', ['sum' => $sum, 
                'tot_o' => $tot_o]);

Now I’m trying to implement a date picker, so does the value of $tot_o should be changed according to the picked date, on change.

This is my date picker.

<td>
      <input id="date" class="date form-control" type="date">
</td>

And this is my JavaScript.

<script>
        $(document).on('change', '#date', function (e) {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            type: 'GET',
            url : '/home',
            data : {selected_date : $('#date').val()},
            success:function(data){

            $('#tot_o').empty(); 
            var total_orders = JSON.parse("{{ json_encode($tot_o) }}")
            console.log(total_orders);

            },
            timeout:10000
        });

    });    
    </script>

But here when I console.log my output it always gives me 0, even though the total is greater than the 0…

How can I correct my JS to display the value inside the <span class="tot_o" id="tot_o"></span> correctly…

I am using app script to generate an automated email but I need to exclude Column O, T , V , W , Y

function onFormSubmit(e) {
  var values = e.namedValues;
  var htmlBody = '<ul>';
  for (Key in values) {
    var label = Key;
    var data = values[Key];
    htmlBody += '<li>' + label + ": " + data + '</li>';
  };
  htmlBody += '</ul>';
  GmailApp.sendEmail('', "New Document Request", "", {htmlBody:htmlBody})
}

//GET DATA FROM GOOGLE SHEET AND RETURN AS AUTOMATED EMAIL