How to use Callback in useState hook (if useEffect didn’t work for logic) [duplicate]

As setState is async method in react. Is there any alternate to work with callback.

Note : I can use useEffect as it cause to unlimited function call.

const [state,setState] = useState([]);


const data = []; // data of 1000 
const function1 = (name) => {
    const tempState = data.filter(ele => ele.name == name);
    setState(tempState);
    function2(tempState[0])
 }

const function2 = (element) => {
    const tempState = state.filter(ele => ele.id == element.id);
    setState(tempState);
} 


Above code always returns [] . possible reason I can find is function2 has called before setState. That is filtering empty array that’s why I’m getting mpty array.

As mention in code if I use useEffect then to call function2(state[0]). But inside function2 we have setState method call which makes re-render again & again.

is there any possibility where I can use callback method like this

setState(tempState,() => function2(state[0]) );

Unable to plot column graph using google chart

I have this script which should plot google chart from the json data kept at wwwroot-

<html>
<head>
    <title>DevOps Monitoring Application</title>
    <link rel="icon" type="image/png" href="https://icons.iconarchive.com/icons/martz90/circle/256/plex-icon.png" />
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <style>
        tr > th::first-line {
            font-size: 1.5em;
            font-weight: bolder;
            text-decoration: underline;
        }
    </style>
    <script type="text/javascript">
        google.charts.load("current", {
            packages: ["corechart"]
        }).then(function () {
            $.ajax({
                type: "GET",
                url: "http://localhost/TestExecutionResult.json",
                dataType: "json"
            }).done(function (jsonData) {

                var data = new google.visualization.DataTable();
                data.addColumn('string', 'Execution State');
                data.addColumn('number', 'Number of tests');

                $.each(jsonData, function (key, value) {
                    data.addRow([key, parseInt(value)]);
                });


                var options = {
                    title: 'Execution Result',
                    is3D: true,
                    colors: ['green', 'red', 'gray', 'orange']
                };

                var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
                chart.draw(data, options);
            }).fail(function (jqXHR, status, errorThrown) {
                // add fail callback
                alert('error: ' + errorThrown);
            });
        });
    </script>

</head>

<body>
    <table border="1">
        <tr>
            <td>
                
                <div id="piechart_3d" style="width: 1000; height: 600;"></div>
            </td>
     </tr>
    </table>
</body>
</html>

The json file has following data –

{"NewAdvisorAccountCreation":4,"AccountActivation":13,"OrganizationCreationForAdvisor":31,"AddingWidgetForDashboard":0}

I’m unable to understand why the graph is not getting plotted. Also, how do i plot a stacked column chart something like this –
enter image description here

Any help, pointers indicators would be much appreciated. Thank you in advance!

JAVA algorithm for printing correct rebuild order given a package to rebuild

Imagine a software repository that contains packages, packages need to be built or be compiled in a certain order,create an algorithm that prints out the correct rebuild order given a package to rebuild:

and how would you represent the software repository?

example:

R = { A -> C , D , B
B->G 
C->E,F
D->E
E->G
F->H
G->H
H ->
}
-> == depends on

The return order of the package is called "rebuild order" 
say you made a code change to G , G would need to be re-built, B, E , C , D and A would also need to be re-built and the re-built order could be G, B , E , C , D , A


so output would be:
G , B , E , C , D , A 

Trying to implement it using arraylist hashmap isn’t working well for me, any ideas to solve this question?

how I can resolve a async problem with vue3-google-map

We are using a library for Vue to manage Maps vue3-google-map and I try to define some polylines that when taking the center of the marked area, it does not allow me to select it:

This is my map template:

 <template>
  <GoogleMap
    ref="mapRef"
    class="mimapa"
    :api-key="apiKey"
    :center="center"
    :zoom="16"
    :zoomControl="controls"
    :fullscreenControl="controls"
    :streetViewControl="controls"
  >
    <q-icon class="pin" :name="pin.icon" :size="pin.size" :color="pin.color" />
    <q-btn
      class="full-width btnMio"
      color="secondary"
      :label="btnLabel"
      @click="getLocation()"
      :disable="btnPosition"
      v-close-popup
    />
       <Polygon v-for="(zone, Index) in DeliveryZones" :key="Index" :options="zone"/>
  </GoogleMap>
  <div class="text-subtitle1 text-center">
    Ubica tu posición exacta en el mapa.
  </div>
</template>

this in my map Javascript code

<script>
import { computed, defineComponent, ref, inject, onUpdated } from "vue";
import { GoogleMap, Polygon } from "vue3-google-map";
import { useGeolocation } from "../boot/useGeolocation";
import axios from 'axios'
var pointInPolygon = require('point-in-polygon');
export default defineComponent({
  name: "Map",
  components: { GoogleMap, Polygon },
  setup() {
    onUpdated(() => {
    // window.setTimeout(() => {
         setGeocerca() <------ HERE PROBLEM 
    // }, 3000); 
    })
    const mapPoint = inject('mapPoint')
    const { coords } = useGeolocation();
    const center = computed(() => ({
      lat: coords.value.latitude,
      lng: coords.value.longitude,
    }));
    const pin = ref(
      {
        color: 'secondary',
        icon: 'person_pin_circle',
        size: 'xl'
      }
    );
    const apiKey = ref('MY_API_KEY')
    const mapRef = ref();
    const controls = ref(false);
    const btnPosition = ref();
    const btnLabel = ref('Estoy Aquí...');
    const DeliveryZones =
    [
      {
        name: 'Zona1',
        strokeColor: "#00ff7a",
        strokeOpacity: 0.5,
        strokeWeight: 1,
        fillColor: "#00ff7a",
        fillOpacity: 0.05,
        price: 2,
        paths: [
        {lat: 10.3816643, lng:-66.9812285 },
        {lat: 10.3549424, lng:-66.9818722 },
        {lat: 10.3549002, lng:-66.9317471},
        {lat: 10.382213, lng:-66.9317471 },
        {lat: 10.3816643, lng:-66.9812285 },
        ]
      },
      {
        name: 'Zona2',
        strokeColor: "#ff0000",
        strokeOpacity: 0.5,
        strokeWeight: 1,
        fillColor: "#ff0000",
        fillOpacity: 0.05,
        price: 3,
        paths: [
          {lat: 10.38, lng:-66.98 },
          {lat: 10.35, lng:-66.99 },
          {lat: 10.36, lng:-66.93},
          {lat: 10.37, lng:-66.95},
          {lat: 10.38, lng:-66.98 },
        ]
      }

    ]
    let centerCurrent = null;
    let tarifa = null;
    function setPoligonToArray(poligon){
       let arreglo = []
       let arr=[]
       for (let cords of poligon){
         arr = [cords.lat, cords.lng]
         arreglo.push(arr)
       }
       return arreglo
    }
    let prueba = 0
    function setGeocerca() {

      if(mapRef.value.ready) {
       mapRef.value.map.addListener("center_changed",() => {
       let activo = 0
       for (const zone of DeliveryZones) {
        const selectedPoint = [mapRef.value.map.getCenter().lat(), mapRef.value.map.getCenter().lng()]
       if(pointInPolygon(selectedPoint, setPoligonToArray(zone.paths)) === true)
         {
           activo++
         }
       }
       if(activo > 0) {
        btnPosition.value = false
        btnLabel.value = "Estoy Aquí..."
        pin.value = {
          color: 'secondary',
          icon: 'person_pin_circle',
          size: 'xl'
          }
       }else {
        btnPosition.value = true
        btnLabel.value = "Delivery no disponible para esta zona"
        pin.value = {
          color: 'primary',
          icon: 'location_off',
          size: 'xl'
          }
       }
      });
     }else{
       console.log('Afuera' + prueba)
     }
    }
    function getLocation() {
      if (mapRef.value.ready) {

        // mapPoint.value = mapRef.value.map.getCenter();

       const selectedPoint = [mapRef.value.map.getCenter().lat(), mapRef.value.map.getCenter().lng()]
       for (const zone of DeliveryZones) {
         if(pointInPolygon(selectedPoint, setPoligonToArray(zone.paths)) === true)
         {
           tarifa = zone.price;
           console.log(tarifa)
         }
          console.log(zone.name + ' = '+ pointInPolygon(selectedPoint, setPoligonToArray(zone.paths))); // true
       }
      const mapQuery = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+selectedPoint+"&key=" + apiKey.value
      console.log(mapQuery)
      axios.get(mapQuery).then((result) => {
        mapPoint.value = result.data.results[3].formatted_address;
      })
      }
    }
    
    return { center, getLocation, mapRef, controls, mapPoint, DeliveryZones, btnPosition, btnLabel, pin, apiKey};
  },
});
</script>

onUpdated(() => {
// window.setTimeout(() => {
setGeocerca() <—— HERE THE PROBLEM IS JUST THIS FUNCTION DOES NOT WAIT FOR THE MAP TO LOAD AND GIVE ERROR THAT THE MAP REF OBJECT DOES NOT EXIST, OF COURSE IF I ACTIVATE THE TIMEOUT IT WORKS BUT IF THE LOAD TIME OF THE MAPREF COMPONENT IS GREATER THAN 3000 THE ERROR COMES BACK.
// }, 3000);
})

How do I use drag events (dragover) in a #document embeded in an tag?

An HTML file that I created is being displayed in an HTML object on the parent page. I am creating some drag events on my page and they work fine when calling my html file directly. But, when displayed inside an HTML <object> , the drag events (specifically trying dragover), do not fire, even though I see them listed in my event listeners. During my troubleshooting, I noticed this is not an issue when showing the page inside an <iframe>.

I don’t have the option to me to use <iframe>, is there something I can do to allow the dragover event when displayed through the object tag?

<html>
  <head>

  </head>
  <body>
    <iframe frameborder="0" width="100%" height="100%" src="mytest.html"></iframe>
    <object width="100%" height="100%" data="mytest.html"></object>
  </body>
</html>
document.addEventListener("dragover", function(event) {
  event.preventDefault();
  dragovertest();
});

function dragovertest(){
  alert("popup");
}

All wishlist items text changes when only one should change on click

Sorry guys I need help. I want to make a wish list toggle were clicking on the icon – fa-heart changes from outline to solid. I have achieved that. My problem is, that the tooltip (add to wish list) should change on the target element to “added to wish list”. But instead, it is changing on all elements of the array. How can I stop this behavior to make it change only on the target element?
Thanks.

let i, j, toolTip;
let addItem;

for (i = 0; i < addToWish.length; i++) {
  let addItem = addToWish[i];

  function addToWishList() {

    addItem.classList.add('fas');
    addItem.classList.add('far');
    favIconData++;
    favDataOutput.textContent = favIconData;
    navActionBadge.setAttribute('value', `${favIconData}`);

    if (favIconData >= 1) {
      favoriteIcon.classList.add('fas');
      favoriteIcon.classList.remove('far');
    } else {

      favoriteIcon.classList.remove('fas')
      favoriteIcon.classList.add('far')
    }
  }

  function removeWishList() {
    addItem.classList.remove('fas');
    addItem.classList.add('far');
    favIconData--;
    favDataOutput.textContent = favIconData;
    navActionBadge.setAttribute('value', `${favIconData}`);

    if (favIconData >= 1) {
      favoriteIcon.classList.add('fas');
      favoriteIcon.classList.remove('far');

    } else {

      favoriteIcon.classList.remove('fas')
      favoriteIcon.classList.add('far')
    }
  }

  addItem.addEventListener('click', () => {

    if (addItem.classList.contains('fas')) {
      for (let j = 0; j < cardLabel.length; j++) {
        let label = cardLabel[j];

        label.textContent = 'Add to wishlist';
      }

      removeWishList()
    } else {
      for (let j = 0; j < cardLabel.length; j++) {
        let label = cardLabel[j];

        label.textContent = 'Added to wishlist';
      }

      addToWishList()
    }
  })

}
<html>
<li class="card-action-item">
  <button class="card-action-btn" aria-labelledby="card-label-2">
    <i id="fav"  class="far fa-heart">.</i>
  </button>
  <div class="card-action-tooltip" id="card-label-3">Add to Wishlist</div>
</li>

</html>

Can I write HTML tags inside of a React code?

Sorry I’m newbie to React. It might be a stupid question but can I write HTML code inside of a React code? I’m trying to make a custom block for my wordpress theme and found a example code of JavaScript.

/* This section of the code registers a new block, sets an icon and a category, and indicates what type of fields it'll include. */
  
wp.blocks.registerBlockType('coin-info/border-box', {
    title: 'color-info',
    icon: 'money-alt',
    category: 'common',
    attributes: {
      content: {type: 'string'},
      color: {type: 'string'}
    },
    
  /* This configures how the content and color fields will work, and sets up the necessary elements */
    
    edit: function(props) {

      function updateContent(event) {
        props.setAttributes({content: event.target.value})
      }
      function updateColor(value) {
        props.setAttributes({color: value.hex})
      }
      return (
        "div",
        null,
        React.createElement(
          "h3",
          null,
          "Simple Box"
        ),
        React.createElement("input", { type: "text", value: props.attributes.content, onChange: updateContent }),
        React.createElement(wp.components.ColorPicker, { color: props.attributes.color, onChangeComplete: updateColor })
      );

    },
    
    save: function(props) {

      return wp.element.createElement(
        "h1",
        { style: { border: "3px solid " + props.attributes.color } },
        props.attributes.content
      );

    }
  })

I inserted some div tags and p tags inside of the code like HTML, but keeps giving me error. I think I need to study it later LOL

Getting errors while executing code in different IDE other than VS Code

I’m learning JavaScript and was working on some DSA problems. Here is one such problem along with my code. I understand that the solution is not efficient but I believe that logic is proper. However, when I run it on an IDE of Udemy, I get an error saying that ‘expected false to be true’, whereas when I ran it on VS code, there was no issue. Please let me know where I did the mistake.

/* write a code isSubsequence which takes in two strings and checks whether the characters in the first string
form a subsequence of the characters in the second string. In other words, the function should check whether the
characters in the first string appear somewhere in the second string, without their order changing
1. isSubsequence('hello','hello world') //true
2. isSubsequence('sing','sting') //true
3. isSubsequence('abc','abracadabra') //true
4. isSubsequence('abc', 'acb') //false */

const isSubsequence = (str1, str2) => {
  const createCharObj = (string) => {
    let outputObj = {};
    for (let i = 0; i < string.length; i++) {
      if (outputObj[string[i]]) {
        outputObj[string[i]]++;
      } else {
        outputObj[string[i]] = 1;
      }
    }
    return outputObj;
  };
  let charObj1 = createCharObj(str1);
  let charObj2 = createCharObj(str2);
  let compare = "";

  for (let key in charObj2) {
    if (charObj2[key] < charObj1[key]) {
      return false;
    } else {
      let exceed = charObj1[key];
      let i = 0;
      while (i < exceed) {
        compare += key;
        i++;
      }
    }
  }
  return compare === str1;
};

console.log(isSubsequence("hello", "hello world"));
console.log(isSubsequence("sing", "sting"));
console.log(isSubsequence("abc", "abracadabra"));
console.log(isSubsequence("abc", "acb"));

How can I enable only certain dates when using q-date?

i am using q-date component in my quasar project. My purpose of use is to have the user select only the days that are enabled and I want to show the other days as disabled. I wrote it with pug by the way

             q-input.q-ma-md(readonly clearable v-model="options.date" dense outlined)
              template(v-slot:prepend)
                q-icon.cursor-pointer(name="event")
                  q-popup-proxy(transition-show="scale" transition-hide="scale")
                    q-date(v-model="options.date" :options="dataActiveOrNot" mask="YYYY-MM-DD")

  data() {
return {
  options: [
    {
      id: 1,
      title: 'Event 1',
      time: '10:00',
      details: 'This is a test event',
      date: '2022-06-03',
      type: 'active'
    },
    {
      id: 2,
      title: 'Event 2',
      time: '11:00',
      details: 'This is a test event',
      date: '2019-10-01',
      type: 'closed'
    },
    {
      id: 3,
      title: 'Event 3',
      time: '12:00',
      details: 'This is a test event',
      date: '2019-10-01',
      type: 'active'
    },
    {
      id: 4,
      title: 'Event 4',
      time: '13:00',
      details: 'This is a test event',
      date: '2019-10-01',
      type: 'active'
    },
    {
      id: 10,
      title: 'Event 10',
      time: '19:00',
      details: 'This is a test event',
      date: '2019-10-01',
      type: 'active'
    }
  ],
}

  methods: {
    dataActiveOrNot() {
      for (let i = 0; i < options.length; i++) {
        console.log(options[i].date)
        if (options[i].type == 'active') {
          return options[i].date
        }
      }
    },

I can’t find where I am doing wrong, can you help? your answers will be rewarded

Resize text inside element like

I want to resize my text inside pre element like textarea, for example if you set columns of textarea equal to 10 and your text exceeds that, then the text will go to next line.

How can I do that with pre element? What is the technical term?

Note that I need to use pre element because it reads n and r, and textarea does not allow to append a button under it (why?).

An example:

enter image description here

I present a dummy scenario below (working code) to illustrate my issue(s).

Thnamks.
Thanks.

  <!DOCTYPE html>
    <html>
        <head>
            <button onclick="call()">Click</button>
        </body>
        <script>
     function call(){
    view = window.open("","Viewer", "width=400,height=600, resizable=no");
    view.document.write('<div id="id_1"</div>');
        t=["asdf", "sasdfasdfasdfasdfasd", "sasdfasdfasdfasdfasd"]
        id = view.document.getElementById("id_1");
        for (var i = 0; i < 3; i++){
    
            if (i % 2 == 0){
            
            ed_1 = document.createElement("pre");
            ed_1.id = "edt_"+i;
            ed_1.textContent = t[i];
            id.appendChild(ed_1);
            
            prnt = view.document.getElementById("edt_"+i);
            edb_1 = document.createElement("button");
            nextline_gap_1 = document.createElement("br");      
            edb_1.innerHTML = "Button no = "+i;
            edb_1.id = i;
            prnt.appendChild(nextline_gap_1);           
            prnt.appendChild(edb_1);    
                              }
                              else{
           text_a = document.createElement("textarea");     
            text_a.readOnly = "true";
            text_a.cols = "10"; 
            text_a.id = "edt_"+i;
            text_a.textContent = t[i];
            id.appendChild(text_a);
            
            
            prnt = view.document.getElementById("edt_"+i);
            edb_1 = document.createElement("button");
            nextline_gap_1 = document.createElement("br");      
            edb_1.innerHTML = "Button no = "+i;
            edb_1.id = i;
            prnt.appendChild(nextline_gap_1);           
            prnt.appendChild(edb_1);          
                             } } }
        </script>
    </html>

Unable to set multiple color for google bar char

I have the following code where I am able to load the graph from the database, but I am trying to apply multiple colors which is not working

function drawStatuChart() {
show('loading3', true);
var data = JSON.stringify({
    'GraphId': 5,
    'startDt': $("#from-date").val(),
    'endDt': $("#to-date").val()
});
$.ajax({
    type: "POST",
    url: url,
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (r) {
        var data = new google.visualization.DataTable();
        var cols = r.splice(0, 1);
        cols[0].forEach(function (col, index) {
            if (index === 0) {
                data.addColumn('string', col);
            } else {
                data.addColumn('number', col);
            }
        });
        if (r.length > 0) {
            data.addRows(r);
        } else {
            data.addRow(['', null]);
        }
        show('loading3', false);
        var view = new google.visualization.DataView(data);
        view.setColumns([0, 1,
            {
                calc: "stringify",
                sourceColumn: 1,
                type: "string",
                role: "annotation",
            }
        ]);

        var options = {
            width: '350',
            height: '300',
            'overflow': 'hidden',
             bar: { groupWidth: "65%" },
            legend: { position: "none" },
            colors: ['#f8aa00', '#00778d'],
            fontName: 'Montserrat',
            chartArea: {
                left: "17%",
                top: "2%",
                height: "250",
                width: "250"
            }
        };

        var chart = new google.visualization.BarChart($("#status")[0]);
        chart.draw(view, options);
    },
    failure: function (r) {
        alert(r.d);
    },
    error: function (r) {
        alert(r.d);
    }
});

}

I get the following data from db, but some how I am not able to apply different colors

enter image description here

Showing only one color

enter image description here

Threejs move mesh with a scroll

I wanna create an app that moves mesh y position with scroll so that at the top of the page mesh y position is 0 at center and at the bottom of the page mesh position is -3, but I don’t know how I can calculate that, I figured I need “scrollY” position to get current scroll position, but I don’t know how I can convert current scroll position so it goes in range from 0 to -3

let scrollY = window.scrollY
window.addEventListener('scroll', () => {
 // code
    
})

ReferenceError: document is not defined; Grab a button and add function to it

I want to grab a button on my webpage and add functions to it, but I get this error:

ReferenceError: document is not defined

Apparently, every answer I found is that Node.js is a server-side runtime, so we can’t use the document variable in Node. Should I uninstall Node.js? if I do so, then I cant run JavaScript on vscode anymore. If I don’t uninstall Node.js it keeps throwing the error. what am I supposed to do? here’s the code:

const button = document.getElementById("add-btn")

button.addEventListener('click', function(){
    console.log("clicked")
})

I cannot import fontawesome icons in my react project. (reactv6)

This is my code snippet.

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; 
import { faQuestionCircle, faExclamationCircle, faCog,} from "@fortawesome/free-solid-svg-icons";

 <div className="action-btn">
        <FontAwesomeIcon className="icon-block" icon={faQuestionCircle} />
        <FontAwesomeIcon className="icon-block" icon={faExclamationCircle} />
        <FontAwesomeIcon className="icon-block" icon={faCog} />
</div>

I installed the required packages yet I received the error “Module not found: Error: Can’t resolve ‘@fortawesome/react-fontawesome’ “

How do i prevent formik yup ( regex ) validation from disappearing

This is my validation

     const validationSchema = Yup.object().shape({
    email: Yup.string()
      .email(ENTER_VALID_EMAIL_MESSAGE)
      .required(EMAIL_IS_REQUIRED_MESSAGE),
    firstname: Yup.string()
      .trim()
      .matches(
        firstNameSpecialChars,
        'These characters are not allowed in name fields',
      ),
        const firstNameSpecialChars = /[^/\#+()$~%.":;*<>{}@]+$/;
  

this is my regex

I want an error to be shown when there is a regex match.
This works, but there is a problem…
As soon as i type after the hash symbol the error disappears
but when there is a symbol the error shows up

enter image description here

which is not what i want
if there is special char i want the error to be there till the user removes the special char


This is how my error looks like when I type regex chars

enter image description here

Below is my validation schema

  const validationSchema = Yup.object().shape({
    email: Yup.string()
      .email(ENTER_VALID_EMAIL_MESSAGE)
      .required(EMAIL_IS_REQUIRED_MESSAGE),
    firstname: Yup.string()
      .trim()
      .matches(
        firstNameSpecialChars,
        'These characters are not allowed in name fields',
      ),
  });