Uncaught TypeError: Cannot destructure property ‘children’ of ‘_ref’ as it is undefined in Context

I created Context to store my user login info and other details but i am getting error
Uncaught TypeError: Cannot destructure property ‘children’ of ‘_ref’ as it is undefined.

I don’t know why this is giving error i read from some article that this children variable is null while i am accessing it, I am not sure about the error and how to fix it.
Please help me fix it.

Here is my Context File

import { createContext, useContext, useEffect, useState } from "react";
import { useHistory } from "react-router-dom";

const ChatContext = createContext();

const ChatProvider = ({children})=>{
    // {children ='empty'}=children||
    const history = useHistory();

    const [user,setUser] = useState();
    const [selectedChat,setSelectedChat] = useState();
    const [chats,setChats] = useState([]);

    useEffect(()=>{
        const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        setUser(userInfo);
        if(!userInfo){
            history.push('/')
        }
    },[history]);

    return(
        <ChatContext.Provider value={{user,setUser,selectedChat,setSelectedChat,chats,setChats}}>
            {children}
        </ChatContext.Provider>
    )
};

export const ChatState=()=>{
    return useContext(ChatContext);
}

export default ChatProvider

Here is the File which is giving error upon accessing this Context

import React from 'react'
import ScrollableFeed from "react-scrollable-feed";
import { isLastMessage, isSameSender } from '../config/ChatLogic';
import ChatState from "../Context/ChatProvider"
import { Avatar, Tooltip } from '@chakra-ui/react'

const ScrollableChat = ({ messages }) => {
    console.log(messages);
    const { user } = ChatState();
    console.log(user);

    return (
        <ScrollableFeed>
            {messages &&
                messages.map((message, i) => (
                    <div style={{ display: "flex" }} key={message._id}>
                        {(isSameSender(messages, message, i, user._id) ||
                            isLastMessage(messages, i, user._id)) && (
                                <Tooltip label={message.sender.name} placement="bottom-start" hasArrow>
                                    <Avatar
                                        mt="7px"
                                        mr={1}
                                        size="sm"
                                        cursor="pointer"
                                        name={message.sender.name}
                                        src={message.sender.pic}
                                    />
                                </Tooltip>
                            )}
                    </div>
                ))}
        </ScrollableFeed>
    )
}

export default ScrollableChat;

From list of elements set opacity to 0 if its a certain tag

I have a list of elements from a querySelectorAll call and i want to set all the elements that are <g> tags to have opacity 0. Im unsure how an if statement like this would work though.

  useEffect(() => {
    var elements = document.querySelectorAll(`[id^='tooth-${props.toothnumber}']`);
    var svg = document.querySelector('svg')
    console.log(svg)
    var elms = svg.querySelectorAll(`:not([id^='tooth-${props.toothnumber}'])`)
    for(var i = 0; i < elms.length; i++) {
        if (elems[i] is a g tag) {
            elms[i].style.opacity = 0
        }
        
    }
  }, [props.toothnumber])

Any Advice

Javascript set delays on return [duplicate]

I have a function as below. The code works fine but the issue is second console.log executes at first and then the first console.log. Which means i am supposed to return null but its returning mtd array because the ac=false inside the else statement executes slow. Because of that second console .log executes at first. How can i make this work in order? Please give me suggestion on how to fix this.

 newQuoteInventoryCheck(newData){
        let mtd = [];
        let ac = true;
        for (let i = 0; i < (newData.product_id).length; i++) {
             let added_quantity = newData.quantity[i];
             let newItem = newData.product_id[i];
             if(added_quantity > 0){
                
                Api.get('materials/get/'+newItem).then((data)=>{
                    let available_quantity = data.quantity;
                    if (added_quantity <= available_quantity){
                        mtd.push([newItem, (available_quantity - added_quantity)]);
                    }
                    else{
                        ac = false;
                        mtd.push([newItem, 0]);
                        $('#maxquantityavailable').text('Total quantity available for "'+ data.name+'" in inventory is: '+available_quantity);
                        $('#maximum-quantity-exceeded-modal').modal('show');
                    }
                    console.log('first: '+ ac) //first log
                });
                
            }
        }
         console.log('Second: '+ ac) //second log
         if(ac){
             return mtd;
         }
         else{
             return null;
         }           
},

Given an integer N. Find the smallest integer greater than N that does not contain two identical consecutive digits

You are given a positive integer N. Your task is to find the smallest integer greater than N that does not contain two identical consecutive digits.

For example, given N = 1765, the smallest integer greater than N is 1766. However, in 1766 the last two digits are identical. The next integer, 1767, does not contain two identical consecutive digits, and is the smallest integer greater than 1765 that fulfills the condition. Note that the second and fourth digits in 1767 can both be 7 as they are not consecutive.

Write a function:

function solution(N);

that, given an integer N, returns the smallest integer greater than N that does not contain two identical consecutive digits.

Example:

  1. Given N = 55, the function should return 56. It is the smallest integer greater than 55 and it does not contain two consecutive digits that are the same.

  2. Given N = 1765, the function should return 1767, as explained above.

  3. Given N = 98, the answer should be 101. Both 99 and 100 contain two identical consecutive digits, but 101 does not.

  4. Given N = 44432, the answer should be 45010.

  5. Given N = 3298, the answer should be 3401.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..1,000,000,000].

How to handle true/false values in JSON object

I have problem where my JSON object has True instead of true and False instead of false. That is causing issues when I parse it to JSON. How do I resolve this issue?
In below script obj2 is not working as I have boolean True but not string.

<!DOCTYPE html>
<html>
<body>

<h2>Creating an Object from a JSON String</h2>

    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const txt1 =  '{"device_state": {"device_name": "iPhone", "is_phone": true, "is_VOX": false}}'
    const obj1 = JSON.parse(txt1);
    document.getElementById("demo1").innerHTML = obj1.device_state.device_name
    const txt2 =  '{"device_state": {"device_name": "iPhone", "is_phone": True, "is_VOX": false}}'
    const obj2 = JSON.parse(txt2);
    document.getElementById("demo2").innerHTML = obj2.device_state.device_name
    </script>
    
    </body>
    </html>

Inject javascript fetch and XHR into Selenium with Python

There are several ways to scrape information from websites. Recently I’ve heard that you can open a selenium webdriver and inject JS on it to fetch specific url from within the website or to replicate AJAX calls.

For example

driver.execute_script("return fetch('www.yoururlhere')")

So, I have a couple of questions regarding it

1 – How do you actually fetch the answer? Inspecting the driver I can see the call but neither in the frontpage nor doing driver.page_source am I able to retrieve it.

2 – How would one replicate more complex requests calls where there is params or data?

requests.get(url=url,headers=headers,params=params)
requests.post(url=url,headers=headers, data=json.loads(data))

How does this work?

Thanks!

Extended Logout in MVC 5

Extending logged in time as per user’s choice.

Scenario:
The ASP.NET MVC 5 web application is hosted in Azure WebApp
WebConfig is set to timeout in 60 minutes of no requests made to the server as shown below

WebConfig:

<authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="60" slidingExpiration="true" name="MYAUTHDV" cookieSameSite="None" requireSSL="true" />
</authentication>

In the login screen, we would like to provide a CHECKBOX and if user ticks it and login, the webapp should not log them out for next 12 hours even if there is no activity.

enter image description here

So far, I have tried a javascript timer running on the _layoutpage.chtml and a local storage time value registered at loggged in time at the client side. The javascript timer will ping to the server every 20 minutes to keep the login alive. This is not always working for multiple reasons like browser, machine sleep mode, hard disk turnoff internet interruptions and other unknown reasons as well etc. There is also an issue we have to overcome regarding sliding expiration vs javascript pinging .https://docs.microsoft.com/en-us/dotnet/api/system.web.security.formsauthentication.slidingexpiration?view=netframework-4.8
I am also open to solutions involving server handling as well. Hoping a client side solution will incur less modification in our existing app.

I cannot show at the DOM properly

I have question. I have this whole code and whent I want to submit the form and to show it at the HTML, the thing is only showed when I refresh the web page. What can I do? Itried putting the code inside of the event but didn´t work properly. Help please. I didn´t add the whole code because was too much.

https://github.com/peladno/JS28160JavierPerez this is the repo if you want to see the complete code

let listaIngredientes = []; 
let recetas = [];

formReceta.addEventListener('submit', (e) => { 

  const ingredienteReceta = new Ingrediente (ingrediente, cantidad, medida, precio);
    listaIngredientes.push(ingredienteReceta);

  let copiaListaingredientes = [...listaIngredientes]

  const receta = new Receta (nombreReceta, procedimiento, descripcion, 
  copiaListaingredientes);
  recetas.push(receta)
  localStorage.setItem('recetasLocales', JSON.stringify(recetas));
  
})
//creacion div container
const divContainer = document.createElement("div");
divContainer.className = "row";

  for (let i = 0; i < recetasLocales.length; i++) {

    //se crea div que contiene una receta
    const divReceta = document.createElement("div");
    divReceta.className = "card border-info mb-3";
    divReceta.style = "max-width: 20rem;";
  
    const titulo = document.createElement("div");
    titulo.textContent = `${recetasLocales[i].nombreReceta}`;
    titulo.className = "card-header";
  
    const subTitulo = document.createElement ("h3");
    subTitulo.textContent = `Ingredientes`
  
    const parrafo = document.createElement("p")
    parrafo.textContent = `${recetasLocales[i].procedimiento}`;
    
      //se crea lista
    const lista = document.createElement("ul");
    for (let j = 0; j < recetasLocales[i].ingredientes.length; j++) {
      const element = recetasLocales[i].ingredientes[j].cantidad + " " + 
    recetasLocales[i].ingredientes[j].unidadDeMedida + " " + 
    recetasLocales[i].ingredientes[j].nombre + " ";
        //se crea nueva lista
      const listaItem = document.createElement("li");
      listaItem.textContent = element;
        //se agrega ingrediente a la lista
      lista.appendChild(listaItem);
    }
    
      //se agrega todo junto a los div en orden
    divContainer.appendChild(divReceta);    
    divReceta.appendChild(titulo);
    divReceta.appendChild(subTitulo);
    divReceta.appendChild(lista);
    divReceta.appendChild(parrafo)
  }
    //se carga contenido al DOM
    document.addEventListener("DOMContentLoaded", function () {
      const content = document.getElementById('listaRecetas');
      content.appendChild(divContainer);
    });

How to make the open in the Modal component false?

I’ve been using NextJS and sometimes, I’m not sure, if it’s about React missconception or the NextJS Framework I needed to understand better to make some simple things work!

Bellow, I have the code which should set false next time I press (F5) in the client side. I’m using NextJS!

import { Modal } from "@mui/material";

import React, { useState } from "react";

const LangModal = () => {

const [open, setOpen] = useState(true);

const handleModal = () => {

setOpen(false);

console.log("[Agora o Model é false]", open);

};

return (

<Modal open={open} onClick={() => handleModal()}>

<div>

       `<h2> Simple React Modal</h2>`

       `<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi accumsan odio enim, non pharetra est ultrices et.</p>`

</div>

</Modal>

);

};

export default LangModal;

Please, could you help me guys???

How can i highlight text word by word in sync with audio [duplicate]

The other posts i saw didn’t really solve my problem and werent were can some make like a simple code on how you could do this. I want like text to highlight word by word and it syncs with audio i dont mind manually finding when to start highlighting and when to stop. It would be very helpful if someone could post like a sample code of how that would work

How do I make a result in same page laravel?

now i create api and done success

but i get result in white page like that

screen : https://i.ibb.co/H2GyFQ8/stylex.png

so how can get result in same page and with modal

Controller

  public function imeiSubmit(Request $request)
    {
        
     $format = "html"; // Display result in JSON or HTML format
     $imei = $_POST['imei']; // IMEI or SERIAL Number
     $apiKey ='EJwka-pKEL9-1Ctnc-iLn67-NWF77-cqkhT';
     $service = $_POST['service']; // Service ID
     
     if(!filter_var($imei, FILTER_VALIDATE_EMAIL)){
         $imei = preg_replace("/[^a-zA-Z0-9]+/", "", $imei);
     }
     if($service != 'demo') {
      $service = preg_replace("/[^0-9]+/", "", $service);
     }
     
     $url = 'https://alpha.imeicheck.com/api/php-api/create?format='.$format.'&key='.$apiKey.'&service='.$service.'&imei='.$imei;
  
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

     $response = curl_exec ($ch);
     $err = curl_error($ch);  //if you need
     curl_close ($ch);
     return $response;
    }

html

<center>
    <form method="POST" action="" style="margin-top:5%">
        @csrf
        <p><input type="text" style="padding: 15px 10px 10px; font-family: 'Source Sans Pro',arial,sans-serif; border: 1px solid #cecece; color: black;box-sizing: border-box; width: 50%; max-width: 500px;" name="imei" autocomplete="off" maxlength="50" placeholder="Write here IMEI or SN"></p>
        <select name="service" id="service" style="padding: 15px 10px 10px; font-family: 'Source Sans Pro',arial,sans-serif; border: 1px solid #cecece; color: black;box-sizing: border-box; width: 50%; max-width: 500px;">
            <option value="0" selected="selected">PLEASE CHOOSE CHECKER</option>
            <optgroup label="iPHONE SERVICES">
                <option value="0.01">Find My iPhone [ FMI ] (ON/OFF) &#x26A1;</option>
            </optgroup>
        </select>
        <br /><br />
        <button data-toggle="modal" data-target="#resultModal" type="submit" style="background-color: #2ABCA7; padding: 12px 45px; -ms-border-radius: 5px; -o-border-radius: 5px; border-radius: 5px; border: 1px solid #2ABCA7;-webkit-transition: .5s; transition: .5s; display: inline-block; cursor: pointer; width: 20%; max-width: 200px; color: #fff;">Submit</button>
    </form>

</center>


<div class="modal fade" id="resultModal" tabindex="-1" role="dialog" aria-labelledby="resultModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="resultModalLabel">Result</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form action method="post">
        @csrf
        <div class="modal-body">
          <div class="form-group">
            <textarea class="form-control" name="response">{{ old('$response') }}</textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">@lang('Close')</button>
        </div>
      </form>
    </div>
  </div>
</div>

screen : https://i.ibb.co/H2GyFQ8/stylex.png

so i want get result in same page without get white page like in screenshot

and

Thanks

CKEDITOR.replace() on appended textarea

On page load i can have between 0 and 10 textareas, on click I am appending new textarea:

container.innerHTML += content;

And now I need CKEDITOR on that textarea. If I trigger:

CKEDITOR.replace( selector );

Everything in existing textareas/ckeditors is lost.

My Code:

function addField( event ) {
  event.preventDefault();

  let container = document.getElementById('about_content');
  let childNumber = container.childElementCount;
  let content = about_html.replaceAll( '%nr%', childNumber )
  container.innerHTML += content;

  ckEditorTrigger( 'tiny_editor_' + childNumber );
}

function ckEditorTrigger( selector ) {
  CKEDITOR.replace( selector );
}

react-native sound not working after a while

I’m using 50 different sound files. it works normally but on my 14th or 15th try it no longer plays the audio files. (I am using android device)

  const animalSound = new Sound( selectedAnimals.soundUrl ||"snake.mp3", null, error => {
    if (error) console.log("Can't play sound. ", error);
  })

const handlePlaySound = () => {
    animalSound.setVolume(1);
    animalSound.play(() => {
        animalSound.release();
    });
  };

const handleStopSound = id => {
    animalSound.stop()
}