How to remove Event Listener using MutationObserver?

I have a problem, I can’t remove the event listener in the condition inside the callback function.

I have the impression that the syntax is correct. But the event is still active.

Does anyone know how to remove the event touchstart?

mutation.target.removeEventListener("touchstart",(e) => { handleClickButton(e) }, true);
const headerSearchBox = document.querySelector(".search-box");

function handleClickButton(event) {
    event.preventDefault();
    alert("You Clicked on the button")
}
    
const mutationCallback = function (mutationList) {
  mutationList.forEach((mutation) => {
    let isSearchOpen = mutation.target.classList.contains("search-container");

    if (mutation.type === "attributes" && isSearchOpen && mutation.oldValue.includes("open")) {
      console.log("Search Bar is Open");
      mutation.target.addEventListener("touchstart",(e) => { handleClickButton(e) }, true);
    } else {
      console.log("Search Bar is Close");
      mutation.target.removeEventListener("touchstart",(e) => { handleClickButton(e) }, true);
    }
  });
};

const observer = new MutationObserver(mutationCallback);

observer.observe(headerSearchBox, {
  attributes: true,
  attributeOldValue: true,
  attributeFilter: ["class"],
});

Thanks for your support

Retrun data from the function when it is executed

async function bringData() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(con.query('SELECT company, industry FROM my_table', function (err, result) {
                if (err) {
                    console.error(err);
                    throw 'Error getting data from google_businesses table';
                } else {
                    return result;
                }
            }));
        }, 1000);
    });
}

(async () => {
    // return data from brindData function
    let getData = await bringData();
    console.log(getData);
})();

I am calling this function in main but I am always getting error. I am kind of new to node so if please anybody can guide me or is there any other way to do this such that when I have got my result I can return it.

JS script searches text in HTML

I need a JS script for Chrome extension which searches certain text in the HTML code of the page.

YouTube page of the channel contains channel id in the source code: “channelId”:”UCsNGtpqGsyw0U6qEG-WHadA”

The script should find this peace of text and return only channel ID: UCsNGtpqGsyw0U6qEG-WHadA

How can I do it?

Keyboard covers input text (one long vertical input), text also runs off the screen without actively being scrolled to (react native)

It’s been 7 hours, I’ve read all the docs and similar SO questions, so any help would be appreciated.

My goal: have an app screen where the top 1/3 of the screen is made up of custom components (not the problem), and then the bottom 2/3 of the screen is a giant full-width super-long scrollable textfield for the user to enter several paragraphs (the problem)

The problem: Either the on-screen keyboard covers the text from the textfield, the textfield isn’t scrollable, or when typing and you go off the bottom of the screen you aren’t scrolled along with what you’re typing – or a mix of all the 3.

Here is a rough image of what I desire:
enter image description here

Currently, my code looks like this:

export default function Post() {

    const [text, setText] = useState("");
    return (

        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <SafeAreaView >
        <KeyboardAvoidingView enabled behavior='height' keyboardVerticalOffset={40} >

                <View>
                    <TextInput scrollEnabled={true} placeholderTextColor={LIGHT} maxLength={300000} placeholder="enter text" multiline={true} onChangeText={(newVal) => setText(prev => {prev + newVal})} value={text}/>
                </View>
           
        </KeyboardAvoidingView>

        </SafeAreaView>
        </TouchableWithoutFeedback>

    );
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: WHITE,
      alignItems: 'center',
      justifyContent: 'flex-center',
      alignItems: "center",
      marginHorizontal: 15,
    //   height: "100%",
    },
    textfield: {
        textAlign: "left",
        textAlignVertical: "top",
        backgroundColor: "lavender",
        height: "100%",
        flex: 1,
    },
    scroll: {
        // width: "100%"
    }
});

Can not access props.history in reactjs

So I used to pass data between different pages in react using the state inside the link component but now the props.history seems to be undefined.
here is my router:

<Router>
        <Routes>
          <Route path="/auth/admin" exact element={<Login />} />
          <Route path="/admin" exact element={<AdminPage />} />
          <Route path="/admin/faculties" exact element={<Faculty />} />
          <Route path="/admin/addNewFaculty" exact element={<AddNewFaculty />} />
          <Route path="/admin/facultyEdit" exact element={<EditFaculty />} />
        </Routes>
</Router>

this is the link that I am using:

<Link
   to={{
         pathname: "/admin/facultyEdit",
         state: { id: item._id }
      }}
      style={{ marginRight: "10px" }}>

and this is what I am getting when trying to log the history in the faculty element:

console.log(this.props.history);

output:
“undefined”
Thank you in advance.

GET AND POST METHOD NOT WORKING ON JOOMLA

I am trying to get the value of the text field but I get null result

Heres the code of form

    <form name="form" action="" method="post">
    <input type="text" name="del_id" id="del_id" value="2"> 
    </form>

then here’s my code but when i print $idpass i get null.

    $idpass = $_POST['del_id']; 

Parse string in JavaScript to array

I have string in Javascript with same nested tags like:

<Text>
  <Text param={1}>Test Text 1</Text>
  <Text> Test Text 2</Text>
  <Text param={3}> Test Text 3
    <Text>Test Text 4</Text>
    Test Text 5
  </Text>
</Text>

and I need to parse it to array

array[0] = "<Text param={1}>Test Text 1</Text>"
array[1] = "<Text>Test Text 2</Text>"
array[2] = "<Text param={3}>Test Text 3</Text>"
array[3] = "<Text>Test Text 4</Text>"
array[4] = "Test Text 5"

Is there a way to parse it via regex?

Appreciate any help!

How to count how many times a value is true in an hour/day in React?

I’m coding an alarm app and want to count how many times the alarm has been triggered in an hour and in a day. I use redux toolkit to handle the state of the alarm (true/false) and the reducer countAlarm to increment the count. Right now handleCount dispatches countAlarm every time alarmValue is true. I would like to count how many times the alarmValue is true in an hour and in a day. How do I do that?

      const dispatch = useDispatch();
      const countValue = useSelector((state) => state.count.value);
      const alarmValue = useSelector((state) => state.alarm.active);

      const handleCount = () => {
        if (alarmValue) {
        dispatch(countAlarm());
      }}

      useEffect(() => {
        handleCount()
      }, [alarmValue])

      return (
        <View>
          <Text>{countValue}</Text>
        </View>

        ...

countAlarm:

    import { createSlice } from '@reduxjs/toolkit';

    const initialStateValue = {
        value: 0
    }

    const countSlice = createSlice({
        name: 'count',
        initialState: initialStateValue,
        reducers: {
            countAlarm: (state = initialStateValue) => {
                state.value++;
            },
        }
    });

    export const {countAlarm} = countSlice.actions;
    export default countSlice.reducer;

How do you consume the latest message from Kafka topic?

I’m using KaafkaJS to connect and consume the kafka messsages.
I’m using the following code to consume messages. But it fetches all the messages but I would like to store the last message in the variable messageValue. Can someone help me with it please.

await consumer.run({ 
            eachMessage: async (data) => {
                    messageValue = data.message.value.toString('utf8').trim()
            }
        })
console.log(messageValue)

Problem with React useState (Changing between new & old value of state)

I want to make app for display live app on big devices.
I just create the function for checking time for every second (just for sim).

Time state work fine in display, but if I check the artist “right now” here is a problem.
Every time when state is updated, displayed name is jumping between new and old state.

Where is the problem? Thanks…

import React, { useState } from "react";
import Artist from "../Artist";
import Database from "../Data.json"


const Engine = () => {


    const [data, setData] = useState(Database);

    const [hour, setHour] = useState(null);
    const [minute, setMinute] = useState(null);
    const [second, setSecond] = useState(null);


    const [nowArtist, setNowArtist] = useState('');


    // Update time every second //
    const updateTime = () => {
        // const h = new Date().getHours(); //
        const h = 16;
        const m = new Date().getMinutes();
        const s = new Date().getSeconds();

        setHour(h);
        setMinute(m);
        setSecond(s);
    }



    const updateArtis = () => {
        data.stage1.filter(el => {
            if(el.startHour === hour) {
                setNowArtist(el)
            }
        })
    }


    setInterval(() => {
        updateTime();
        updateArtis();
    }, 1000);




    return (

        <Artist name={nowArtist.name} />
        
    )

}



export default Engine;

Firestore Collections – recursiveDelete() vs batched deletions

What is considered most efficient when deleting a Firestore collection?

Performing deletions using batches?

async function deleteCollection(db, collectionPath, batchSize) {
  const collectionRef = db.collection(collectionPath);
  const query = collectionRef.orderBy('__name__').limit(batchSize);

  return new Promise((resolve, reject) => {
    deleteQueryBatch(db, query, resolve).catch(reject);
  });
}

async function deleteQueryBatch(db, query, resolve) {
  const snapshot = await query.get();

  const batchSize = snapshot.size;
  if (batchSize === 0) {
    // When there are no documents left, we are done
    resolve();
    return;
  }

  // Delete documents in a batch
  const batch = db.batch();
  snapshot.docs.forEach((doc) => {
    batch.delete(doc.ref);
  });
  await batch.commit();

  // Recurse on the next process tick, to avoid
  // exploding the stack.
  process.nextTick(() => {
    deleteQueryBatch(db, query, resolve);
  });
}

Or using the firestore’s default recursiveDelete() method.

await firestore.recursiveDelete(collectionRef);

-Note: The collection I am trying to delete doesn’t have nested sub-collections. Also, I am running this code in a cloud function.

/messages (C)
  -message_id_1 (D)
  -message_id_2 (D)
  -message_id_3 (D)
  ...
  -message_id_10000 (D)

How to use javascript after fetch call

I am loading a PHP file into a div using fetch. The code is:

let FC =    fetchphp ('contents/my_stuff/my_work.php', LNG, main_place);
}

function fetchphp (XX, LNG, main_place) {
  
  let place = document.getElementById(main_place);
 
  fetch(XX, { method: "POST", body: LNG })
  .then(res => res.text())
  .then((txt) => {
    console.log(txt);
     place.innerHTML = txt;
  })
  .catch((err) => { console.error(err); });
  return false;
}

The PHP code produces the output properly, but none of the console.log calls in the PHP file (head section) e.g.:

<script> console.log('HEAD Top of mywork A -- from my_work.php'); </script>

produce anything in the browser (Chrome) console. And no JS works either.

This seems rather bizarre. All the file content shows in the console in the above:

console.log(txt);

But that is not much use. How does one get JS to work on a page/file has been loaded with fetch?

PhilB

Can not modify variable and get new value outside a function (in a class) Javascipt

I want to modify a variable which is inside a function in a class. If I move alert to inside the function block it works. But If it stand outside the {} it doesn´t work.

class test {


    my_test(){

  var var_a = 50;
  var var_b;

    $("input[name='my_input']").click(function() {
    if ($("#radio1").is(":checked")) {
     var_b = 100;

    }else if ($("#radio2").is(":checked")){
    var_b = 0;
}
});

alert(var_b);
}
}

can’t insert data into firebase realtime database

I am trying to enter and then read data from a firebase realtime database through a web application. The read function (getData) works perfectly, since I have tested it by entering test data, but the enter function (submit) it does not work. This is the complete code:

<html>
<head>
<title>firebase editable table </title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

</head>

<body>

<div class="col-md-6">
  <form>
    <div class="form-group">
    <label>First name</label>
    <input type="text" class="form-control" id="first-name" placeholder="first name">
  </div>
  <div class="form-group">
    <label>Last name</label>
    <input type="text" class="form-control" id="last-name" placeholder="last name">
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="email" placeholder="Enter email">
  </div>
  <button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>
</div>

  <button type="submit" id="getData" class="btn btn-primary">Search data</button>

<div class="col-md-6">
<table class="table table-striped" id='dataTbl'>
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>
</div>


</body>
</html>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>

<script type="module">
  // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";
    import { getDatabase, set, ref ,push, child, onValue} from "https://www.gstatic.com/firebasejs/9.8.1/firebase-database.js";

  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  const firebaseConfig = {

//here goes my firebase data


  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  
  // Get a reference to the database service
  const database = getDatabase(app);
  // write data
 submit.addEventListener('click',(e) => {
    var firstName = document.getElementById('first-name').value;  
    var lastName = document.getElementById('last-name').value;  
    var email = document.getElementById('email').value;  

    const userId = push(child(ref(database), 'users')).key;
   
    set(ref(database, 'users/' + userId), {
    firstName: firstName,
    lastName: lastName,
    email : email
   });
   alert("data saved");
  });     

  // read data
  getData.addEventListener('click',(e) => {
    
    $('#dataTbl td').remove();
    var rowNum = 0; 
    //const dbRef = ref(database, 'Mensajes/');
    const dbRef = ref(database, 'users/');

    onValue(dbRef, (snapshot) => {
      snapshot.forEach((childSnapshot) => {
      const childKey = childSnapshot.key;
      const childData = childSnapshot.val();
      // ...
      rowNum += 1; 
      var row = "<tr><td>" + rowNum + "</td><td>" + childData.firstName + "</td><td>" + childData.lastName + "</td><td>" + childData.email + "</td></tr>"
      //var row = "<tr><td>" + rowNum + "</td><td>" + childData.texto + "</td><td>" + childData.lastName + "</td><td>" + childData.email + "</td></tr>"
      $(row).appendTo('#dataTbl');
      
      });
    }, {
       onlyOnce: true
    });


  });

</script>