React not firing useEffect consistently

This is my first React project. I usually am found hammering on the backend, but I have a personal project I am using to expose myself to frontend fun.

I have a function that sets up a table. While designing the component I used static data that gets pushed through useMemo and the memoized result is passed to useTable (react-table) with the result being a nicely formatted table with all expected data.

The next step is to pull in axios to make API calls to get real data and here is where things get strange. If I set up the code to call useTable with the memoized data the API call will fire, but if I use try to the API data the API is never called. The result is either a table that renders with test data or an error because the API was never called so there is no data to render.

I have a feeling this may have something to do with how and when React re-renders, but I haven’t been able to find any documentation to support that theory.

The code sample includes calling useTable with the memoized data.

import React, { useMemo, useEffect, useState } from 'react';
import { useTable } from 'react-table';
import Select from "react-select";
import MOCK_DATA from './constants/Mock_users.json';
import './css/table.css';
import axios from 'axios';

const options = [
  {value: "", label: ""},
  {value: "mon", label: "Monday"},
  {value: "tue", label: "Tuesday"},
  {value: "wed", label: "Wednesday"},
  {value: "thu", label: "Thursday"},
  {value: "fri", label: "Friday"},
]

  const columns = [
    {
      Header: 'Username',
      accessor: 'username',
      Cell: e =><a href={String(e.value)}> {String(e.value)} </a>
    },
    {
      Header: 'Name',
      accessor: 'name',

    },
    {
      Header: 'Route',
      accessor: 'route',
      Cell: ({row})=> {
              return <Select options={options} defaultValue={{ label: row.original.route, value: row.original.route}}/>
              },
    },
    {
      Header: 'Email',
      accessor: 'email',
    },
    {
      Header: 'Active',
      accessor: 'is_active',
      Cell: e =><a href={String(e.value)}> {String(e.value)} </a>
    },
  ];

function Users() {
  const [grinchUsers, setGrinchUsers] = useState(null)
  useEffect(() => {
    console.log('Calling to API')
    axios.get('http://localhost:8000/api/users/').then((response => {
      setGrinchUsers(response.data)
    }))
  }, []);

  const data = useMemo(() => MOCK_DATA, []);
  const tableInstance = useTable({ columns, data });

  console.log('data: ' + JSON.stringify(data))
  console.log('grinchUsers: ' + JSON.stringify(grinchUsers))

  return( <h1>Tadaaa</h1>);
  const {getTableProps, getTableBodyProps, headerGroups, rows, prepareRow} = tableInstance;

  return(
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map ((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>
                {column.render('Header')}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map(row =>{
          prepareRow(row)
            return(
              <tr {...row.getRowProps()}>
                {row.cells.map((cell)  => {
                  return <td {...cell.getCellProps()}>
                    {cell.render('Cell')}</td>
                })}
              </tr>
            )
          })
        }
      </tbody>
    </table>
  );
}

export default Users;

JavaScript errors after multiple onmouseover calls

function langPicker(buttonid){
    animationForwarder('sectionlang1', 'sectionlang2', 'anim-switchByFadeIn-lang', 100)
    setTimeout(langTextChange, 625, buttonid);
}
function langTextChange(buttonid){
    const subject1 = document.getElementById('sectionlang1');
    const subject2 = document.getElementById('sectionlang2');
    if(buttonid == 'cpp'){
        subject1.textContent = 'C++';
        subject2.textContent = 'C++ is one of the most renowned programming languages in the world';
    }
}
function anFrwdDoubleExec(identifier, identifier2, identifier3, identifier4 ,anim_id, wait_time, anim_id2, wait_time2, secondExecutionWaitTime){
    animationForwarder(identifier, identifier2, anim_id, wait_time);
    setTimeout(() => {animationForwarder(identifier3, identifier4, anim_id2, wait_time2)}, secondExecutionWaitTime);
}
function animationForwarder(identifier, identifier2, anim_id, wait_time){
    document.getElementById(identifier).classList.add(anim_id);
    if(identifier2 != 'skip'){
        setTimeout(() => {document.getElementById(identifier2).classList.add(anim_id)}, wait_time);
    }
}
.nonstandard-draft{
    max-width: 15vw;
    position: fixed;
    bottom: 1.7vw;
    right: 1.7vw;
}
.nonstandard-draft-head{
    font-size: 1.7vw;
    display: inline-block;
    font-family: Belanosima;
    margin: 0 0 1.2vw 0;
}
.nonstandard-draft-data{
    font-family: Belanosima;
    font-size: 1vw;
    white-space: pre-line;
    color: #0d8569;
    filter: drop-shadow(0.1vw 0.1vw 0.2vw black);
}
.grd-draft1{
    background-image: linear-gradient(to right bottom, #f269e0, #ff5d9a, #ff864b, #ffbd00, #a8eb12);
    filter: drop-shadow(0vw 0vw 0.1vw #ff864b);
}
.grd-draft2{
    background-image: linear-gradient(to right bottom, #8f00ff, #007aff, #0091ef, #009994, #009950);
    filter: drop-shadow(0vw 0vw 0.1vw #0091ef);
}

.w-100p{
    width: 100%;
}
.w-97p{
    width: 97%;
}
.w-14p75{
    width: 14.75vw;
}
.w-9p5{
    width: 9.5vw;
}
.h-100p{
    height: 100%;
}
.header{
    background-image: url('../RESOURCES/bgs/bg12.gif');
    height: 100vh;
}
.fx{
    display: flex;
}
.fx-jc-spb{
    justify-content: space-between;
}
.fx-ai-c{
    align-items: center;
}
.fx-jc-c{
    justify-content: center;
}
.fx-dir-c{
    flex-direction: column;
}
.mg-none{
    margin: 0;
}
#headertext{
    width: 0vw;
    overflow: hidden;
}
.headertexttransformed{
    width: 48.5709375vw !important;
    transition: all 0.5s ease-in;
}  
.b-sh-def{
    box-shadow: 0vw 0vw 0.3vw grey;
}
.bgs-full{
    background-size: 100% 100%, 100% 100%;
}
.headerimage{
    width: 12vw;
    margin-right: 3.25vw;
    image-rendering: pixelated;
}
.headergradienttext{
    white-space: nowrap;
    font-size: 3vw;
}
.ff-raleway{
    font-family: Raleway;
}
.grd-firsth1{
    background-image: linear-gradient(to right bottom, #000000, #202020, #3a3a3a, #565656, #747474);
    filter: drop-shadow(0.1vw 0.1vw 0.01vw #3a3a3a);
}
.grd-sech1{
    background-image: linear-gradient(to right bottom, #00e377, #00e395, #00e2af, #00e1c3, #00ded3);
    filter: drop-shadow(0.1vw 0.1vw 0.01vw #00e377);
}
.gradient-text{
    background-clip: text;

    -webkit-background-clip: text;
    -o-background-clip: text;
    -moz-background-clip: text;

    -webkit-text-fill-color: transparent;
    -o-text-fill-color: transparent;
    -moz-text-fill-color: transparent;
}
.fc-violet{
    color: blueviolet;
}
.nav{
    position: fixed;
    background-color: white;
    top: 1vw;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 10vw;
    z-index: 1;
}
.dp-none{
    display: none;
}
.wh-animelem-1{
    width: 1.5vw;
    height: 1.5vw;
}
.wh-animelem-1-addr-1{
    top: -2vw;
    left: -2vw;
}
.wh-animelem-1-addr-2{
    bottom: -2vw;
    right: -2vw;
    transform: rotate(180deg);
}
.headercontainer{
    margin: 3.25vw;
}

.fsz-1{
    font-size: 1vw;
}

@keyframes anim1{
    0%{
        opacity: 0;
    }
    33.3%{
        opacity: 1;
    }
    66.6%{
        opacity: 0;
    }
    99.9%{
        opacity: 1;
    }
}

.abm-section{
    height: 74vh;
    padding: 10vh 0;
}
.bs-bb{
    box-sizing: border-box;
}

.anim-1{
    animation: anim1 0.25s ease-in-out;
}
.nest-subsection{
    width: 80vw;
    max-width: 1250px;
}
.general-subsection{
    max-height: calc(70vh - 80px);
}
.add-text-subsection{
    font-family: Belanosima;
}
.t-ss-heading{
    font-size: 48px;
    margin-bottom: 32px;
}
.t-ss-paragraph{
    font-size: 34px;
    filter: drop-shadow(0.2vw 0.2vw 0.1vw #a6a6a6);
}
.t-ss-paragraph-modabm{
    max-width: 671.438px;
}
@keyframes blink{
    0%{
        opacity: 0;
    }
    50%{
        opacity: 1;
    }
    100%{
        opacity: 0;
    }
}
.anim-blink{
    animation: blink 1.25s infinite;
}
.pfp{
    height: 340px;
    width: auto;
    border-radius: 15%;
    margin-left: 70px;
}
@keyframes fadeInTR{
    from{
        transform: translateX(-75px);
    }
    to{
        opacity: 1;
    }
}
.anim-fadeintr{
    animation: fadeInTR 0.75s ease-out forwards;
}
.scroll-alternative{
    overflow-y: scroll;
}
.scroll-alternative::-webkit-scrollbar{
    display: none;
}
.op-0{
    opacity: 0;
}
.border{
    height: 40px;
    background: url('../RESOURCES/SHWHP_RES/greeceborder.png'), white;
    background-size: contain;
}
.abm-bgp{
    background: url('../RESOURCES/SHWHP_RES/bg-content/bg-master.png'), white;
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: bottom left;
}
.longsec-child-preset{
    height: 70vh;
    color: #f3f3f3;
}
.general-heading{
    font-size: 54px;
}
.add-lang-paragraph{
    text-align: left;
    font-size: 24px;
    margin-top: 30px;
}
@keyframes fadeInTB{
    from{
        transform: translateY(-30px);
    }
    to{
        opacity: 1;
    }
}
.anim-fadeintb{
    animation: fadeInTB 0.75s cubic-bezier(.2,1,1,1) forwards;
}
.bg-long{
    background-image: url('../RESOURCES/bgs/bg14.jpg');
}
.longer-subsection{
    max-height: 100%;
}
.lang-pick{
    width: 225px;
    height: 225px;
    padding:20px;
    flex-wrap: wrap;
    transform: rotate(45deg);
}
.lang-pick-opt{
    width: 94px;
    height: 94px;
    margin: 9.25px;
    border-radius: 12px;
    flex-shrink: 0;
}
.cpp{
    background-image: radial-gradient(circle, #5ffbf1, #64fcec, #69fde7, #6ffde1, #76fedc, #83fed7, #8fffd3, #9affcf, #abffcd, #baffcc, #c7ffcc, #d3ffce);
}
.cpp::before{
    content: '';
    width: 71.27659574468085%;
    height: 6px;
    transform: scaleX(0);
    transform-origin: left;
    position: absolute;
    top: -20px;
    left: -20px;
    background-color: #08fcbc;
    transition: transform 0.1s ease-in;
}
.lang-pick:hover .cpp::before{
    transform: scaleX(1);
    transform-origin: left;
    transition: transform 0.1s ease-out;
}
.cpp::after{
    content: '';
    width: 6px;
    height: 71.27659574468085%;
    transform: scaleY(0);
    transform-origin: top;
    position: absolute;
    top: -20px;
    left: -20px;
    background-color: #08fcbc;
    transition: transform 0.1s ease-in;
}
.lang-pick:hover .cpp::after{
    transform: scaleY(1);
    transform-origin: top;
    transition: transform 0.1s ease-out;
}
.html{
    background-image: radial-gradient(circle, #e28ef6, #d884f4, #ce7af2, #c470f0, #b867ef, #af66ef, #a564f0, #9b63f0, #9168f2, #876df4, #7d72f5, #7376f5);
}
.html::before{
    content: '';
    width: 71.27659574468085%;
    height: 6px;
    transform: scaleX(0);
    transform-origin: right;
    position: absolute;
    top: -20px;
    right: -20px;
    background-color: #08fcbc;
    transition: transform 0.1s ease-in;
}
.lang-pick:hover .html::before{
    transform: scaleX(1);
    transform-origin: right;
    transition: transform 0.1s ease-out;
}
.html::after{
    content: '';
    width: 6px;
    height: 71.27659574468085%;
    transform: scaleY(0);
    transform-origin: top;
    position: absolute;
    top: -20px;
    right: -20px;
    background-color: #08fcbc;
    transition: transform 0.1s ease-in;
}
.lang-pick:hover .html::after{
    transform: scaleY(1);
    transform-origin: top;
    transition: transform 0.1s ease-out;
}
.css{
    background-image: radial-gradient(circle, #5ffbf1, #46eefa, #41dfff, #52cffe, #69bff8, #79b3f4, #8aa7ec, #9a9ae1, #aa8fd8, #ba83ca, #c777b9, #d16ba5);
}
.css::before{
    content: '';
    width: 71.27659574468085%;
    height: 6px;
    transform: scaleX(0);
    transform-origin: left;
    position: absolute;
    bottom: -20px;
    left: -20px;
    background-color: #08fcbc;
    transition: transform 0.1s ease-in;
}
.lang-pick:hover .css::before{
    transform: scaleX(1);
    transform-origin: left;
    transition: transform 0.1s ease-out;
}
.css::after{
    content: '';
    width: 6px;
    height: 71.27659574468085%;
    transform: scaleY(0);
    transform-origin: bottom;
    position: absolute;
    bottom: -20px;
    left: -20px;
    background-color: #08fcbc;
    transition: transform 0.1s ease-in;
}
.lang-pick:hover .css::after{
    transform: scaleY(1);
    transform-origin: bottom;
    transition: transform 0.1s ease-out;
}
.js{
    background-image: radial-gradient(circle, #b1ff00, #90ff4e, #6eff76, #4dff97, #2affb4, #4bf6a6, #5eee98, #6ce58c, #8fcf5b, #a9b72f, #be9c05, #ce7e00);
}
.js::before{
    content: '';
    width: 71.27659574468085%;
    height: 6px;
    transform: scaleX(0);
    transform-origin: right;
    position: absolute;
    bottom: -20px;
    right: -20px;
    background-color: #08fcbc;
    transition: transform 0.1s ease-out;
}
.lang-pick:hover .js::before{
    transform: scaleX(1);
    transform-origin: right;
    transition: transform 0.1s ease-out;
}
.js::after{
    content: '';
    width: 6px;
    height: 71.27659574468085%;
    transform: scaleY(0);
    transform-origin: bottom;
    position: absolute;
    bottom: -20px;
    right: -20px;
    background-color: #08fcbc;
    transition: transform 0.1s ease-out;
}
.lang-pick:hover .js::after{
    transform: scaleY(1);
    transform-origin: bottom;
    transition: transform 0.1s ease-out;
}
.cur-sel{
    cursor: pointer;
}
.whp-icon{
    width: 74%;
    height: 74%;
    transition: all 0.15s;
}
.whp-icon:hover{
    width: 80%;
    height: 80%;
    transition: all 0.15s;
}
.pos-abs{
    position: absolute;
}
.p-ab-center{
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.pos-rel{
    position: relative;
}
.anim-switchByFadeIn-lang{
    animation: switchByFadeIn-lang 1.25s ease-in forwards;
}
@keyframes switchByFadeIn-lang{
    50%{
        transform: translateX(75px);
        opacity: 0;
    }
    50.001%{
        transform: translateX(-150px);
    }
    100.001%{
        transform: translateX(75px);
        opacity: 1;
    }
}
<section onmouseover="anFrwdDoubleExec('sectionlang1', 'sectionlang2', 'slash1-lang', 'slash2-lang', 'anim-fadeintb', 250, 'anim-blink', 100, 0)" class="longsec-child-preset w-100p fx fx-jc-c fx-ai-c fx-dir-c">
                <div class="nest-subsection fx fx-jc-spb fx-ai-c">
                    <div class="longer-subsection add-text-subsection fx-dir-c bs-bb">
                        <h1 id="sectionlang1" class="mg-none general-heading underline-marker op-0"><span id="slash1-lang">/</span><span id="slash2-lang">/</span> Languages: the keys</h1>
                        <p id="sectionlang2"class="t-ss-paragraph t-ss-paragraph-modabm add-lang-paragraph ff-raleway mg-none op-0">Languages serve as my trump cards: they are like limbs for every programmer. And I am no exception! Here you can review the aforementioned.</p>
                    </div>
                    
                    <div class="lang-pick fx">
                        <div onclick="langPicker('cpp')" class="lang-pick-opt bgs-full cpp pos-rel cur-sel">
                            <img src="RESOURCES/SHWHP_RES/cpp_b&w.png" class="whp-icon pos-abs p-ab-center" alt="C++">
                        </div>
                        <div class="lang-pick-opt bgs-full html pos-rel cur-sel">
                            <img src="RESOURCES/SHWHP_RES/html_b&w.png" class="whp-icon pos-abs p-ab-center" alt="HTML">
                        </div>
                        <div class="lang-pick-opt bgs-full css pos-rel cur-sel">
                            <img src="RESOURCES/SHWHP_RES/css_b&w.png" class="whp-icon pos-abs p-ab-center" alt="CSS">
                        </div>
                        <div class="lang-pick-opt bgs-full js pos-rel cur-sel">
                            <img src="RESOURCES/SHWHP_RES/js_b&w.png" class="whp-icon pos-abs p-ab-center" alt="JS">
                        </div>
                    </div>
                </div>
            </section>

Basically, I wanted to share with you a question: why the js breaks after multiple onmouseover calls over an element? The code snippet’s below to ease the error’s identification (log also below).

Uncaught TypeError: Cannot read properties of null (reading ‘classList’)

What I had tried before posting this:

  1. Checking for any mistakes in the values;
  2. Analyzing the function body;
  3. Asking GPT.

No results for me.

get html attribute value by name react native render html

I am trying to get the src value from the html string <video src="url"></video>. I need the source value so I can custom render the component using the renderers prop for the default export. The package is react-native-render-html

video: (src: any) => {
  console.error(src);
  return(
    <Video
      source={{uri: "https://url"}}
      style={{ width: 100, height: 100, alignSelf: 'center', backgroundColor: 'blue' }}
      resizeMode={ResizeMode.CONTAIN}
      shouldPlay={false}
      isLooping
      isMuted
      useNativeControls
    />
  )
},

the source object does not contain the attribute value of src thanks

Problem with react-native-ble-plx library when receiving data

I have a problem with my react native app when receiving data, since I cannot see the complete message that is sent to me, I can only see a part of the message, this is not a problem of where the message is sent since I can see in another app and if the complete message is sent.

I want to know if there is any type of additional configuration to be able to receive the complete message

I put the part of the code where I receive the data

  //Connect the device and start monitoring characteristics
  async function connectDevice(device) {
    
    device
      .connect()
      .then(device => {
        setConnectedDevice(device);
        setIsConnected(true);
        return device.discoverAllServicesAndCharacteristics();
      })
      .then(device => {
        //  Set what to do when DC is detected
        BLTManager.onDeviceDisconnected(device.id, (error, device) => {
          
          setIsConnected(false);
        });

        //Read inital values
        //Message
        device
          .readCharacteristicForService(SERVICE_UUID, MESSAGE_UUID)
          .then(valenc => {
            setMessage(base64.decode(valenc?.value));
          });

          //monitor values and tell what to do when receiving an update
          const MAX_MESSAGES = 11; // Número máximo de mensajes a almacenar
          const messages = {}; // Diccionario para almacenar los mensajes recibidos
          let currentIndex = 0; // Índice actual en el diccionario
          //Message
          device.monitorCharacteristicForService(
            SERVICE_UUID,
            MESSAGE_UUID,
            (error, characteristic) => {
              if (characteristic?.value != null) {
                const decodedMessage = base64.decode(characteristic?.value);

                messages[currentIndex] = decodedMessage; // Almacenar el mensaje en el diccionario
                currentIndex = (currentIndex + 1) % MAX_MESSAGES; // Actualizar el índice circularmente
                
                setVolt(messages[0]);
                setFre(messages[1]);
                setFac(messages[2]);
                setRLC1(messages[3]);
                setCor(messages[4]);
                setPot(messages[5]);
                setPRea(messages[6]);
                setPApa(messages[7]);
                setEAct(messages[8]);
                setERea(messages[9]);
                setT(messages[10]);
  
              }
            },
            'messagetransaction',
          );
      });
  }

Since I can’t see the whole message, the solution of my code is to send it divided into 11 parts and in code to separate the data and put it in the corresponding place, but I want to know if there is any way to receive a single long message with all content

cache.match returns undefined in my react js pwa

caches.match returns undefined and delete my stored cache or my cache is being deleted for any reasons and cache.match can’t match anything

i’m trying to make a working pwa, i register the service worker directly on my index.html and it succeeds, and my service worker for the moment have only this

const CACHE_NAME = 'version-1'

const urlsToCache = [
    'index.html',
    'static/js/main.a1ae2d16.js',
    'service-worker.js',
    '/manifest.json',
    '/logo192.png',
    '/favicon.ico',
]

const self = this;

self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then((cache) => {
                console.log('Opened cache')
                return cache.addAll(urlsToCache)
            })
    )
})

self.addEventListener('fetch', async (event) => {
    event.respondWith(
        caches.open(CACHE_NAME)
            .then(cache => {
                console.log(cache)
                cache.match(event.request.url, {ignoreVary: true})
                    .then(response => {
                        console.log(response)
                        if (response) {
                            return response
                        }
                    })
            })
    )
})

the install event is working as expected, on my first time in the page it store in cache the listed requests, but when i refresh the page, in the fetch event occurs an error because the respondWith gets a undefined, because my cache.match returns as resposne in my callback an undefined (always) even if in the previous load of the page i saw the request stored in cache, also when i log cache it’s an empty object and when i look into my stored cache again it’s now empty, i don’t know if it’s being cleaned for any reason when i reload the page or if the cache.match don’t match anything and respondWith broke the page and the cache because it receive an undefined

sorry for my grammar, if i forget to explain something useful please let me know

How to replace component by another component in svelte with undo and redo action?

I want to design front-end system where,

  • Frame A -> can be replaced with Frame B (user action on frame, leads to transition – e.g. click)
  • Frame A‘s transition to Frame B mutates some global state vars
  • All transitions are recorded (can perform undo/redo)

My initial thinking is that, I can achieve this via:

  • buffer (stack), in which each element is (stateVars, frame)

Now, doing this with svelte my store looks like this:

// stores.ts
import { writable } from "svelte/store";

type BufferItem = {
    frame: string // this is component name,
    vars: Record<string, string | number | null>,
}

export const buffer = writable<BufferItem[]>([{
   frame: 'initComponent',
   vars: {},
}]);
// App.svelte
<script>
    import { buffer } from './stores.js';
        // import Undo from 'undo.svelte';
        // import Redo from 'redo.svelte';

    let currentFrame;
    buffer.subscribe((value) => {
        // TODO: handle, empty or non-array buffer
        currentFrame = value[value.length - 1].frame;   
    });

    // How do I dynamically import and assign component
    // based on the currentFrame (type string)?
    let component = ""; // need to be component type
</script>

<svelte:component this={component} />

I’m thinking I can do following, but it seems like hacky, I don’t know if there is a better way to achieve this using bind and svelte-esq approach.

let registry = { 'componentStringName': Component; }

let currentFrame;
buffer.subscribe((value) => { currentFrame = value[value.length - 1].frame; });

let component = registry[currentFrame];

Tests of component Vue 3 and Quasar with jest

I have to test a component in the application Vue 3 and Quasar with Webpack. This is an example of my test:

import MyComponent from "./MyComponent.vue";
import { mount } from '@vue/test-utils';
import { installQuasarPlugin } from '@quasar/quasar-app-extention-testing-unit-jest'

installQuasarPlugin();

describe('Deployment of MyComponent', () => {
    const wrapper = mount(MyComponent)
    const toolbar = wrapper.findComponent({name: 'QToolbar'}) 

    it('MyComponent renders correctly', () => {
        
        expect(toolbar.exist()).toBe(true)

    })

});

When I run the test I have the error: “Cannot read property ‘value’ of undefined”
and error is shown in const wrapper when I mount the component.
I’ve written other tests in the same way, which works well.

How to print only selected checkbox list in HTML/CSS/JS?

I have to print the PDF page only of the items that are selected with the checkbox.

    <td>Prima riga</td>
    <td><input type="checkbox"></td>
    <td><textarea class="form-control autosize" style="resize: none; overflow: hidden;"></textarea></td>
    </tr>
    <tr>
    <td>Seconda riga</td>
    <td><input type="checkbox"></td>
    <td><textarea class="form-control autosize" style="resize: none; overflow: hidden;"></textarea></td>
    </tr>
    <tr>
    <td>Terza riga</td>
    <td><input type="checkbox"></td>
    <td><textarea class="form-control autosize" style="resize: none; overflow: hidden;"></textarea></td>
    </tr>

Blocked by CORS policy because of a 302 Moved Temporarily

I’m using the Bullhorn REST API from my website.
In my javascript code, I have the following:

var myHeaders = new Headers();
var requestOptions = {
  method: "GET",
  redirect: "follow",
  headers: myHeaders,
};
const url_part1 = "https://auth.bullhornstaffing.com/oauth/authorize?client_id=";
const url_part2 = "&response_type=code&username=";
const url_part3 = "&password=";
const url_part4 = "&action=Login";
const full_url =
  url_part1 +
  client_id +
  url_part2 +
  username +
  url_part3 +
  password +
  url_part4;
response = await fetch(full_url, requestOptions);

If the client_id, the username or the password are wrong, I get a 200 OK response and I don’t have any problem, even if I don’t allow CORS (which I’m not too sure I understand why).

However, if they are correct, I get redirected with a 302 Moved Temporarily response. And I have the standard:

Access to fetch at 'https://welcome.bullhornstaffing.com/?code=*************' (redirected from 'https://auth.bullhornstaffing.com/oauth/authorize?client_id=*******&response_type=code&username=*****&password=******&action=Login') from origin '*****' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So I tried various answers I found online, for example, adding:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "http://localhost:3000"
    Header set Access-Control-Allow-Credentials "true"
    Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
    Header set Access-Control-Allow-Headers "Origin, Content-Type, Accept"
</IfModule>

to .htmaccess.

I do now see in the response headers of the request:

Access-Control-Allow-Credentials: true

Access-Control-Allow-Headers: Accept, Authorization, Content-Type, Origin, highLevelCallStack, uniqueCallId, x-requested-with
Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin: https://cappuccino-consulting.com
Access-Control-Max-Age: 86400

But I’m still redirected, and on the second response header of the second page to which I’m redirected, these headers disappear. Which I assume is the reason why it’s raising the error I shared above.

What should I do? I feel like I’ve tried so many things (functions.php, etc …) and I couldn’t make any work.

Single Postal Code has more results but Google Place Autocomplete API returns one result

I am using Google Places Autocomplete API to get all the related postal codes based on user’s input (Only for Australia). For example, user types 5000. Postal code 5000 has more than one result.

Postcode    Suburb
5000        ADELAIDE, SA
5000        ADELAIDE BC
5000        CITY WEST CAMPUS, SA
5000        HALIFAX STREET, SA

But Google Places Auto Complete returns only one result.

Postcode    Suburb
5000        ADELAIDE, SA

My code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=myKey"></script>
    <script type="text/javascript">
var options = {
    types: ['postal_code'],
    componentRestrictions: {
      country: "au"
    }
  }
        google.maps.event.addDomListener(window, 'load', function () {
            var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'), options);
            google.maps.event.addListener(places, 'place_changed', function () {
for (var i = 0; i < place.address_components.length; i++) {
                    for (var j = 0; j < place.address_components[i].types.length; j++) {
                        if (place.address_components[i].types[j] == "postal_code") {
                            alert(place.address_components[i].long_name);
                        }
                    }
                }
                
            });
        });
    </script>
</head>
<body>
    <span>Location:</span>
    <input type="text" id="txtPlaces" style="width: 250px" placeholder="Enter a location" />
</body>
</html>

My expected output.

  1. User should enter only postal codes in the text box. Not city or regions name (No Alphabets)
  2. Input 5000 should returns all the possible results.

Why does getAttribute not exist on type “Node”?

I’m converting some Javascript I wrote into a Deno TypeScript module. The script uses deno-dom to get all the “a[href]” links off of a page, and returns a list of links. The script is working correctly, however, when I test the code using deno test, it complains

"TS2339 [ERROR]: Property 'getAttribute' does not exist on type 'Node'"

My understanding is that the Element type is a “type” of the Node type – but my attempts at intelligently declaring this has failed. What am I misunderstanding here?

Here’s the code chunk in question:

const document = new DOMParser().parseFromString(content, "text/html");

    if (document === null) throw new Error("Failed to parse HTML");
    const baseUrl = response.url;

    // Find all links on the page
    const linkSelector = document.querySelectorAll(
      'a[href^="http:"], a[href^="https:"]',
    );
    const links = Array.from(linkSelector, (link) => link.getAttribute("href"))
    // This is the line it complains about !!!
      .map((link: string) => {
        // Convert relative links to absolute URLs
        const absoluteURL = new URL(link, baseUrl);
        return absoluteURL.href;
      })
      .filter((link: string) => {
        // Filter out links that are on the same domain as the URL
        const parsedUrl = new URL(url);
        const parsedLink = new URL(link);
        return parsedUrl.hostname !== parsedLink.hostname;
      });

    return {
      source: url,
      links: links.slice(0, slice),
    };

Thanks.

strange behaviour of let vs const in knoghts tour problem javascript

I have been driving myself crazy trying to understand why one little tweak that i wouldve thought made no difference was the cause of me not being able to implememt this knightsTour solution on my own. There is a function that sets varables and calls the recursive solve function and another function that validates the x and y inputs. The recursive solve function below is the source of the problem.

function solvefg(x,y,xMove,yMove,m,board){
  
  const p=Math.pow(board.length,2)
  if(m===p)return true
  
 
  for(k=0;k<Math.sqrt(p);k++){
    const nextX=x + xMove[k]
    const nextY=y + yMove[k]
     
     
       if(isValid(nextX,nextY,board)){
       board[nextX][nextY] = m;
       console.log(board)
       if(solvefg(nextX,nextY,xMove,yMove,m+1,board)){
         return true
       }
       
       else{
         board[nextX][nextY]=-1
       }
     }
  }

}

The correct answer declares 3 variables using let like this

const p= Math.pow(board.length,2)
  if(m===p)return true
  let k,nextX,nextY
 
  for(k=0;k<Math.sqrt(p);k++){
       nextX=x + xMove[k]
       nextY=y + yMove[k]

Can anyone tell me whats happening here?

I was expecting that decaring const variables within the scope of the for loop i would get the correct values. I dont understand why the answer becomes correct when i use declare let variables outside the for loop

Web Audio API – Sound in Chrome/Safari but not Firefox

I can play audio just fine in Chrome/Safari, but in Firefox I just get silence with no errors so I don’t know what is going on.

This is my code:

const lowpassFilterNode = audioContext.createBiquadFilter()
lowpassFilterNode.type = "lowpass"
lowpassFilterNode.frequency.value = lowpassCutoff
lowpassFilterNode.Q.value = 5
const gainNode = audioContext.createGain()
gainNode.gain.value = volume
await audioContext.audioWorklet.addModule("./soundtouch.js")
const source = createScheduledSoundTouchNode(audioContext, audioBuffer)
source.parameters.get("rate").value = audioSpeed
source.parameters.get("pitch").value = pitchCorrect
source.loop = true
await functions.timeout(200)
source.connect(gainNode)
gainNode.connect(audioContext.destination)
source.start(0, offset)

I think the problem is with soundtouch. I am using the library here:
https://github.com/DanceCuts/soundtouchjs-scheduled-audio-worklet/blob/master/src/createScheduledSoundTouchNode.js

But I didn’t find anything that is obviously wrong in this code. Do you have any ideas?