React Native TextInput sends input on second press

Guys i’m new to React Native and also not good at JavaScript.
In my app i have 2 TextInput and a Pressable button but the output is not making sense.
I’ve tried to change timing of execution of some lines but result is the same.

I’m using:
expo,
react native 0.68.2,
android api 30 (Android Studio)

output:

Android Bundling complete 32ms

First click

LOG description :

LOG identity :

Second click

LOG description :sadasdas

LOG identity :12345678910


Report.js

import { StyleSheet, View, TextInput, Pressable, Text } from "react-native";
import { useState, useEffect } from "react";

import axios from "axios";

export default function Report({ route, navigation }) {
  const [enteredText, setEnteredText] = useState("");
  const [enteredId, setEnteredId] = useState("");
  const [category, setCategory] = useState("");
  const id = route.params.category;

  const [description, setDescription] = useState("");
  const [identity, setIdentity] = useState("");

  const { latitude, longitude } = [0, 0];

  function getById(id) {
    return axios.get("http:10.0.2.2:5000/api/Categories/getbyid", {
      params: { id: id },
    });
  }
  //console.log("id :" + getById(id));

  useEffect(() => {
    getById(id)
      .then((result) => setCategory(result.data.data.categoryName))
      .catch(function (error) {
        console.error(
          "There has been a problem with your fetch operation: " + error.message
        );
        // ADD THIS THROW error
        throw error;
      });
  });

  //console.log(category);

  function descriptionInputHandler(enteredText) {
    setEnteredText(enteredText);
    //console.log("entered text :" + enteredText);
  }

  function identityInputHandler(enteredId) {
    setEnteredId(enteredId);
    //console.log("entered id :" + enteredId);
  }

  function buttonHandler() {
    setDescription(enteredText);
    setIdentity(enteredId);
    setEnteredText("");
    setEnteredId("");
    console.log("description :" + description);
    console.log("identity :" + identity);
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>{category}</Text>
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.longTextInput}
          placeholder="Describe your situation, don't worry we are here."
          onChangeText={descriptionInputHandler}
          value={enteredText}
        />
        <TextInput
          style={styles.textInput}
          placeholder="What is your identity number."
          onChangeText={identityInputHandler}
          value={enteredId}
        />
        <Pressable style={styles.button} onPress={buttonHandler}>
          <Text style={styles.text}>Send report!</Text>
        </Pressable>
      </View>
    </View>
  );
}

Vanilla javascript update a table if a button is clicked

I am trying to update a table once a button is clicked. I have created the table and the button with the following HTML code

<button type="button" onclick="calculateMatrixFact()">Calculate MF!</button>

<table id = "matrix_factorization">
  <tr>
    <th>User</th>
    <th>Movie One</th>
    <th>Movie Two</th>
  </tr>
</table>

While the function that I am calling on the onclick event, is the following:

function calculateMatrixFact(){
    var cache = CacheValues();
  
  // split the array in two single arrays one per each user and movie
    var user_matrix = createGroups(cache.mu, 2);
    var score_matrix = createGroups(cache.ms, 2);

    // remove the string user_name and movie_name
    for (let i = 0; i < user_matrix.length && i < score_matrix.length; i++) {
    user_matrix[i].shift();
    score_matrix[i].shift();
    }

    var dot_matrix = [];

    // perform the dot product
    for (let j = 0; j < user_matrix.length; j++) {
    for (let k = 0; k < score_matrix.length; k++) {
        //console.log(user_matrix[j])
        //console.log(score_matrix[k])
        var dot_product = math.multiply(user_matrix[j], score_matrix[k]);
        dot_matrix.push(dot_product);
    }
    }

    // create the matrix and push back the string (first column of the table)
    var dot_prod_matrix = createGroups(dot_matrix, 2);
    dot_prod_matrix[0].unshift("Anna");
    dot_prod_matrix[1].unshift("Jonny");

    // from array to HTML table
    fetch = document.getElementById('matrix_factorization');
    for (var i = 0; i < dot_prod_matrix.length; i++) {
    var newRow = fetch.insertRow(fetch.length);
    for (var j = 0; j < dot_prod_matrix[i].length; j++) {
        var cell = newRow.insertCell(j);
        cell.innerHTML = dot_prod_matrix[i][j];
    }
    }
}

I think the problem is that I do not reset the table each time the button is clicked, is that right? How can I delete the old info and insert the new ones?

Here you can see the full code: https://jsfiddle.net/932ebu0v/7/

Why my ChartJs only Coloring one section?

I have created a Bar Chart. It shows data grouped by Year. I have set the color to each datatype, but the ChartJS only shows it on 1 Year

ChartJS only Coloring 1 Year

Here’s the code:

const data = {
      labels: Syear,
            datasets: [{
                label: 'Jumlah Korban Meninggal 5 Tahun terakhir',
                data: Sdead_total,
                backgroundColor: ['rgba(255, 99, 132, 0.2)'],
                borderColor: ['rgba(255, 99, 132, 1)'],
                borderWidth: 1
            },
            {
                label: 'Jumlah Korban Hilang 5 Tahun terakhir',
                data: Smissing_total,
                backgroundColor: ['rgba(54, 162, 235, 0.2)'],
                borderColor: ['rgba(54, 162, 235, 1)'],
                borderWidth: 1
            },
            {
                label: 'Jumlah Korban Luka Berat 5 Tahun terakhir',
                data: Sserious_woundTotal,
                backgroundColor: ['rgba(255, 206, 86, 0.2)'],
                borderColor: ['rgba(255, 206, 86, 1)'],
                borderWidth: 1
            },
            {
                label: 'Jumlah Korban Luka Ringan 5 Tahun terakhir',
                data: Sminor_injuriesTotal,
                backgroundColor: ['rgba(75, 192, 192, 0.2)'],
                borderColor: ['rgba(75, 192, 192, 1)'],
                borderWidth: 1
            }
          ]
    };

IntersectionObserver always showing as “in view” when its not

I’m trying to get IntersectionObserver working for my page. The HTML looks like:

<div id="feature-blocks">
    <div class="block left">
        <img src="/2022/css/sass/font-awesome/pngs/black/48/solid-icons.png" />
        <h2>Lots of Digital Images</h2>
        <p>foo bar</p>
    </div>
    <div class="block bottom">
            <img src="/2022/css/sass/font-awesome/pngs/black/48/solid-object-group.png" />
            <h2>Online Graphics Editor</h2>
            <p>foo bar</p>
    </div>
    <div class="block right">
            <img src="/2022/css/sass/font-awesome/pngs/black/48/solid-copyright.png" />
            <h2>Copyright Safe Images</h2>
            <p>foo bar</p>
    </div>
    <div class="block left">
            <img src="/2022/css/sass/font-awesome/pngs/black/48/solid-laptop.png" />
            <h2>Access From Any Device</h2>
            <p>foo bar</p>
    </div>
    <div class="block bottom">
            <img src="/2022/css/sass/font-awesome/pngs/black/48/solid-grin-hearts.png" />
            <h2>Unlimited Access</h2>
            <p>foo bar</p>
    </div>
    <div class="block right">
            <img src="/2022/css/sass/font-awesome/pngs/black/48/solid-handshake.png" />
            <h2>Commercial Use</h2>
            <p>foo bar</p>
    </div>

</div>

The JS I have is:

const features_blocks = document.querySelectorAll('#feature-blocks .block');
var observer_features = new IntersectionObserver( entries => {
      entries.forEach(entry => {
        console.log("TEST: "+ entry.intersectionRatio);
        if (entry.intersectionRatio > 0) {
          console.log('in the view');
        } else {
          console.log('out of view');
        }
      });
    }, { root: document.querySelector('#feature-blocks'), rootMargin: '0px', threshold: 0.5 }
);

features_blocks.forEach(f => {
observer_features.observe(f);
});

The problem is, it always shows as “in view” even when its not!

enter image description here

I’ve tried playing with the thresholds, but it doesn’t seem to make a difference. What am I doing wrong?

Bar chart with min height and zero values – ChartJs

I have a bar chart in chartjs which displays four different values. I also want these bars to have a minimum height, so that small values are better visible. For this i used the minBarLength option. The problem is that i don’t want the bars which have the value zero to be affected by this option.

Is there a way to have a minimum bar length but exclude zero values or certain values in general?

Im using chartjs version 3.7.1 with the datalabel plugin 2.0.0.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js" integrity="sha512-R/QOHLpV1Ggq22vfDAWYOaMd5RopHrJNMxi8/lJu8Oihwi4Ho4BRFeiMiCefn9rasajKjnx9/fTQ/xkWnkDACg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<canvas id=chart1 height="75"></canvas>
<script>
  let chart = document.getElementById('chart1').getContext('2d');
  var dataset = {
    "labels": ["OK", "Critical", "Warning", "Unknown"],
    "datasets": [{
      "label": "Example",
      "minBarLength": "40",
      "backgroundColor": ["rgba(58, 255, 0, 0.4)", 'rgba(255, 45, 0, 0.4)', 'rgba(255, 185, 0, 0.4)', 'rgba(161, 161, 161, 0.4)'],
      "borderColor": ["rgb(58, 255, 0)", 'rgb(255, 45, 0)', 'rgb(255, 185, 0)', 'rgb(161, 161, 161)'],
      "borderWidth": 2,
      "fill": true,
      "data": [34, 0, 1, 0],
    }]
  };
  var myChart = new Chart(chart, {
    plugins: [ChartDataLabels],
    type: 'bar',
    data: dataset,
    options: {

      indexAxis: 'x',
      scales: {
        y: {
          gridLines: {
            display: false
          },
          ticks: {
            display: false
          }
        }
      },
      plugins: {
        datalabels: {
          display: function(context) {
            return context.dataset.data[context.dataIndex] !== 0;
          },
          font: {
            size: 20,
          }
        },
        legend: {
          labels: {
            boxWidth: 0
          }
        }
      }
    }
  });
</script>

Accumulate value by types in objects

I have an array containing an object for each object has a different type (wall type).
I am trying to accumulate the total value for each type in order to sort by type.

const walls = [
  {
    typeName: "Sandwichelement - 480mm",
    area: 28.165,
  },
  {
    typeName: "Sandwichelement - 480mm",
    area: 22.165,
  },
  {
    typeName: "Beton vægelement - 150mm",
    area: 89.15,
  },
  {
    typeName: "Beton vægelement - 150mm",
    area: 165,
  },
  {
    typeName: "Fundament - 900mm",
    area: 45.2,
  },
  {
    typeName: "Fundament - 900mm",
    area: 16.5,
  },
];

const result = walls.reduce((acc, val) => {
  acc[val.typeName] = { totalArea: 0 };

  acc[val.typeName]["totalArea"] += val.area;

  //I need the sum of Each wall type?!
  return acc;
}, {});

console.log(result);

Multiple plus and minus buttons need to use the same function

I have 3 plus and minus buttons on my page. I need all of them to do the same thing once clicked.

this is my html code:

  ```<div class="product1">
        <div class="product1-lable"></div>
        <div class="product1-price"></div>
        <button class="minus">+</button>
        <input class="amount" type="amount" value="0"></input>
        <button class="plus">-</button>
        </div> ```

and my JavaScript:

```         let btnAdd = document.querySelector('.plus');
            let btnSubtract = document.querySelector('.minus');
            let input = document.querySelector('input');
            btnAdd.addEventListener('click', () =>{
            input.value = parseInt(input.value) + 1;
            });
            btnSubtract.addEventListener('click', () =>{
            input.value = parseInt(input.value) - 1;
            }); ```

I know if probably something simple but i cant get it right!!
only the first button is working not the other 2.

Any ideas??

Loading icon not disappearing in bokeh/heroku app

I have bokeh apps deployed via heroku that take a while to load.

Using this How to show Page Loading div until the page has finished loading? I created a loading icon, adding the suggested css and html to the existing style.css and index.html files in my app. I also included the js as a separate file in my app.

But the loading icon doesn’t disappear when the app loads, as can be seen in this simple example: https://ckgsb-new.herokuapp.com/app. I assume I’m doing something wrong with the js to remove the icon once loading is complete. Can someone tell me how I should be handling that?

How to protect access key in the client?

I made a component that show data from my server.

The data from my server can only retrieve by access key.

So I tell my clients to pass the access key into the component: <cmp access-key="xxx" />.

The problem is anyone can see the access key in their websites and can use it.

I wounding if it possible to hide the key or some indication that tell me “this is my client” and not fake?

How to play 2 videos one after the other in ReactJS?

I want to play intro video just once followed by another video which loops. I have this code to detect when first video ends but how do i load the second video and set it to play in loop?

const vidIndex = 0;
const videos = [videoIntro, videoLoop];
return (
    <div className="main">
        <video src = {videos[vidIndex]} autoPlay muted onEnded={() => vidIndex++} />
    </div>
);

Thanks.

Capture entire html element which is inside the scroll area also

React code to capture html element and generate image

    import html2canvas from "html2canvas";
    import FormatUrl from "../utils/UrlFormatter";
    import { Toaster } from "../utils/toaster";

    export function pdfReport(id, fileName = "default", folderName) {
    applyShadow(false);
    scrollTo(0, function () {
        let parent = document.getElementById("report_container");
        html2canvas(parent).then((canvas) => {
        applyShadow(true);
        downloadFile(canvas, fileName, folderName);
        });
    });
    }

    function downloadFile(canvas, fileName, folderName) {
    const data = canvas.toDataURL("image/png", 1.0);

    const report_data = {
        report_name: fileName,
        report_url: data,
        folder_name: folderName,
    };

    let url = FormatUrl(`/pdfs/`);
    fetch(url, {
        method: "POST",
        headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        },
        body: JSON.stringify(report_data),
    })
        .then((response) => response.json())
        .then((res) => {
        document.getElementById("after-report-save").click();
        document.getElementById("loader-modal").classList.remove("show");
        })
        .catch((err) => {
        Toaster(2, "failed to save report");
        // document.getElementById("after-report-save").click();
        // document.getElementById("loader-modal").classList.remove("show");
        });
    }

    function scrollTo(offset, callback) {
    const onScroll = function () {
        const scrollTop = window.scrollTop || window.pageYOffset;

        if (scrollTop === offset) {
        window.removeEventListener("scroll", onScroll);
        callback();
        }
    };
    window.addEventListener("scroll", onScroll);
    onScroll();
    window.scrollTo({
        top: offset,
        behavior: "smooth",
    });
    }

    function applyShadow(status) {
    let root = document.documentElement;
    if (!status) {
        // Remove box shadows
        root.style.setProperty("--my-form-control-shadow", "none");
        root.style.setProperty("--my-box-shadow", "none");
        root.style.setProperty("--my-sumary-table-bottom-border", "none");
    } else {
        root.style.setProperty(
        "--my-form-control-shadow",
        "1px 1px 8px -3px rgba(6, 6, 6, 0.15)"
        );
        root.style.setProperty("--my-box-shadow", "4px 4px 30px 1px #e0dfe2");
        root.style.setProperty(
        "--my-sumary-table-bottom-border",
        "0px 4px 0px -3px white"
        );
    }
    }

I am using above code to capture html element it is working but coming as cut the area is inside the scrollbar .
How can i capture which is hidden behind scroll bar also.
Please take a look .

I am already using scrollto function but it is not helping.
Still coming only the shown area

How to delete an object with a windows.confirm?

I have a template that lists all the activities of a client. In this template, I have a button to delete any activity I choose. This button has a confirmation to delete through a windows.confirm. But it’s not working the way you expect. Sometimes the button works, sometimes it doesn’t.

{% for servico in object_list %}                   
     {{ servico.refferring_funcionario }}
     {{ servico.get_lista_servico_display }}
     {{ servico.data_servico }}
     R$ {{ servico.valor_servico }}
     <a href="{% url 'servico:editar-servico' servico.id %}" class="btn btn-secondary btn-sm">Edit</a>
     <a href="" class="btn btn-danger btn-sm" onclick="return myFunction()">Delete</a>
{% endfor %}

Js

<script>
   function myFunction() {
        if (window.confirm("Você tem certeza que deseja excluir ?")) {                                      
            window.location.href="{% url 'servico:excluir-servico' servico.id %}";
        }
   }

Add new Featute Point to existing layer with select interaction Openlayers

My idea was make user able to write comment, after click i try to add a new Point to existing layer with select interaction and tooltip where user can write comment, cancel (remove tooltip) or draw point in another place.
After set draw to map and set layer.getsource() to draw interaction and drawing something, i have error that feature already exists. I noticed that OL does not take another free id, simply this id is alredy used. It happens after a few drawings. Can anyone help?

let commentLayer = this.map.getLayers().getArray().find((layer) => layer.get('title') === 'Comments')        
const writeComments = () => {
          if (this.mode === 'read') {
            this.map.getInteractions().forEach((interaction) => {
              if (interaction && interaction.get('name') === 'select comment') this.map.removeInteraction(interaction);
            });
          }
          this.mode = 'write'
            if (commentLayer) {
              draw = new ol.interaction.Draw({ 
                source: commentLayer.getSource(),
                type: "Point",
              });
              draw.set('name', 'comments interaction')
              this.map.addInteraction(draw);
            };

          draw.on('drawstart', (evt) => {
            // if last draw was not saved delete tooltip and features
              if (commentLayer) {
                const layerArr = commentLayer.getSource().getFeatures();
                if (feature !== null) {
                  if (document.getElementById('OutputElement')) {
                    const elem = document.getElementById('OutputElement');
                    elem.parentNode.removeChild(elem);
                  }
                  if (document.getElementById('InputElement')) {
                    commentLayer.getSource().removeFeature(feature);
                    feature = null
                    const elem = document.getElementById('InputElement');
                    elem.parentNode.removeChild(elem);
                  };
                };
              };
          });

          // create tooltip on draw end
          draw.on('drawend', (evt) => {
            if (tooltip) this.map.removeOverlay(tooltip);
            feature = evt.feature
            const pointCoordinates = feature.getGeometry().getFlatCoordinates();
            feature.set('type', 'comment');
            tooltipElement = document.createElement('div');
            tooltipElement.id = 'InputElement';
            tooltipElement.className = 'ol-tooltip ol-tooltip-measure';
            tooltipElement.appendChild(createTooltip(feature));
            tooltip = new ol.Overlay({
              element: tooltipElement,
              offset: [0, -15],
              positioning: 'bottom-center'
            });
            tooltip.setPosition(pointCoordinates);
            this.map.addOverlay(tooltip);
          });
        };

How to get string inside react-bootstrap’s textarea and send to function on button-click?

I have the following react-bootstrap code;

<Form>
  <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
    <Form.Label>Example textarea</Form.Label>
    <Form.Control as="textarea" rows={3} />
  </Form.Group>
</Form>
    
<Button
  variant="outline-primary"
  size="lg"
  active
  onClick={() => wave("String inside textarea")}
>
  Wave at Me
</Button>

The webpage looks like this;

enter image description here

When the button is clicked, I would like the function wave(textarea_string) to run. textarea_string is the string inside the textarea.

I am using React-bootstrap v2.4 and React v18