Why shouldn’t I use ‘var’ instead of ‘const’ with useState() in React

So I came across an issue with React when using setInterval, mainly when I use useState() within a setInterval() it doesn’t work, I did some reading and roughly found out why that’s the case and I also found some work arounds, however, when I make this declaration in my code:

var [timeLeft, setTime] = useState(5)

suddenly the setTime() works when called within a setrInterval() and changes the timeLeft

What are possible implications of doing it this way ?

Getting Cannot use import statement outside a module when I try executing jest test

I have this component which uses react-use-wizard

The component looks like this

import { useWizard } from "react-use-wizard";
import { collection, getDocs } from "firebase/firestore";
import {
  Box,
  Text,
  Flex,
  Stack,
  Radio,
  RadioGroup,
  Button,
  Center,
} from "@chakra-ui/react";
import { useEffect, useState } from "react";
import { db } from "../../utils/fireStore";
import Image from "next/image";

const StepOne = ({ setEmirateDetails, emirateDetails }) => {
  const [emirates, setEmirates] = useState([]);
  const [selectedEmirate, setSelectedEmirate] = useState("");

  const { previousStep, nextStep, isLastStep, isFirstStep } = useWizard();

  const handleChange = (e) => {
    return setSelectedEmirate(e.target.value);
  };

  const fetchEmirates = () => {
    getDocs(collection(db, "emirates")).then((querySnapshot) => {
      const newData = querySnapshot.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id,
      }));

      setEmirates(newData);
    });
  };

  const getSelectedEmirateDetails = () => {
    const _emirates = [...emirates];
    const result = _emirates.find(
      (_emirate) => _emirate?.name === selectedEmirate
    );

    return setEmirateDetails(result);
  };

  useEffect(() => {
    fetchEmirates();
  }, []);

  useEffect(() => {
    if (selectedEmirate) {
      getSelectedEmirateDetails();
    }
  }, [selectedEmirate]);

  return (
    <Box>
      <Flex alignItems="center">
        <Box p={4} rounded="md" ml={100} height={"50vh"}>
          <Text fontSize="3xl" fontWeight="bold">
            In which emirate would you like to live in?
          </Text>
          <Flex pl={4} justifyContent="space-between">
            <Box>
              <RadioGroup defaultValue="1" name="emirate">
                <Stack>
                  {emirates.map((_emirate) => (
                    <Radio
                      key={_emirate?.id}
                      size="lg"
                      name="emirate"
                      colorScheme="orange"
                      value={_emirate?.name}
                      onChange={handleChange}
                    >
                      {_emirate?.name}
                    </Radio>
                  ))}
                </Stack>
              </RadioGroup>
            </Box>

            {emirateDetails?.image && (
              <Box width="50%">
                <Image src={emirateDetails?.image} width={250} height={150} />
                <Text wordBreak="break-word">{emirateDetails?.overview}</Text>
              </Box>
            )}
          </Flex>
        </Box>
      </Flex>
      <Box>
        <Center>
          <Box>
            <Button
              mr={2}
              onClick={() => previousStep()}
              disabled={isFirstStep}
            >
              Previous
            </Button>

            <Button onClick={() => nextStep()} disabled={isLastStep}>
              Next
            </Button>
          </Box>
        </Center>
      </Box>
    </Box>
  );
};

export default StepOne;

I have a test case written with jest that looks like this

import { render, screen } from '@testing-library/react';
import StepOne from '../components/Steps/StepOne';

test('renders StepOne component', () => {
  render(<StepOne setEmirateDetails={() => {}} emirateDetails={{}} />);
  expect(screen.getByText('Emirates')).toBeInTheDocument();
});

And my jest config looks like this

module.exports = {
    testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
    transform: {
        "^.+\.m?jsx?$": "babel-jest",
        "\.(jpg|jpeg|png|gif)$": "jest-transform-stub",
        '\.[jt]sx?$': 'esbuild-jest'
    },
    testMatch: [ 
        '**/spec/**/*.js?(x)', '**/?(*.)(spec|test).js?(x)', 
        '**/spec/**/*.mjs', '**/?(*.)(spec|test).mjs' 
      ],
    testPathIgnorePatterns: [
        "/node_modules/",
        "/dist/"
      ],
    verbose: true,
    collectCoverageFrom: [
        "pages/**/*.js",
        "tests/**/*.js",
        "components/**/*.js"
    ],
    testEnvironment: 'jsdom'
  };

I also have my babel.rc that looks like this

{
    "presets": ["next/babel"],
    "plugins": []
}

but every time I run my test case I keep getting this error

● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/obafemiomotayo/Development/Personal/Personal/UEL-GRP-16/UELGroup16A-Property-search/node_modules/react-use-wizard/dist/react-use-wizard.mjs:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { createContext, useContext, memo, useState, useRef, Children, useCallback, useMemo, isValidElement, cloneElement, createElement } from 'react';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import { useWizard } from "react-use-wizard";
        | ^
      2 | import { collection, getDocs } from "firebase/firestore";
      3 | import {
      4 |   Box,

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
      at Object.require (components/Steps/StepOne.js:1:1)
      at Object.require (tests/step-one.test.js:5:1)

The react-use-wizard module is transpiled to a .mjs files and it seems it cannot execute this line import { createContext, useContext, memo, useState, useRef, Children, useCallback, useMemo, isValidElement, cloneElement, createElement } from 'react';
in the code

Any Ideas, I have been stuck with this for days now

I have tried so many jest config manipulations and gynamstics but none seem to work. I am not sure what I should do next`

property ‘background’ does not exist on type ‘() => void’

I am trying to make a variable a timer in Microsoft Makecode.

I tried putting the basic.pause function, resulted in either comma expected, or property ‘background’ does not exist on type ‘() => void’. The code i am trying is

function timer(basic.***(error here)***pause(100))
function play_song() {***the song goes here***}

does anyone know what to do?

Application logging multiple nodes and their corresponding neighbors, why?

There is a process in someone else’s code that I am pretty unaware of. Here’s the explanation to the problem.

We have a network that is composed of a bunch of nodes. Firstly, we have a class called Node where it initially has an empty object property called state. Now, we have another class called Network where it has a method that executes a particular function on every node instance.

class Node {
      constructor(name, neighbors, network, storage) {
        this.name = name
        this.neighbors = neighbors
        this[$network] = network // irrelvent to quesstion
        this.state = Object.create(null)
        this[$storage] = storage // irrelevant to question
      }
      // other irrelevent methods

  class Network {
      constructor() {
        // reachable and storageFor are irrelevant 
        this.nodes = Object.create(null)
        for (let name of Object.keys(reachable)) {
          this.nodes[name] = new Node(name, reachable[name], this, storageFor(name))
        }
} 

      everywhere(f) {
        for (let node of Object.values(this.nodes)) f(node)
      }
    }

Now in the index.js file, we call the everywhere function, which will execute on every node. This is what we call

index.js

everywhere(nest => {
  nest.state.connections = new Map();
  nest.state.connections.set(nest.name, nest.neighbors);
  broadcastConnections(nest, nest.name);
});

Now, every nest has a Map() with 1 key-value pair right? Now take a look at this function that’s called after everywhere is called.


function findInStorage(nest, name) {
    return storage(nest, name).then(found => {
      if (found != null) return found;
      else {
        return findInRemoteStorage(nest, name); // this is called
      }
    });
  }
function network(nest) {
  console.log(nest.state.connections)
  return Array.from(nest.state.connections.keys());
}

// IMPORTANT
function findInRemoteStorage(nest, name) {
  console.log(nest.name)
  let sources = network(nest).filter(n => {
    return n != nest.name
  } );
  function next() {
    if (sources.length == 0) {
      return Promise.reject(new Error("Not found"));
    } else { // the "else" never runs
      let source = sources[Math.floor(Math.random() *
                                      sources.length)];
      sources = sources.filter(n => n != source);
      return routeRequest(nest, source, "storage", name)
        .then(value => value != null ? value : next(),
              next);
    }
  }
  return next();
}
// IMPORTANT

findInStorage(bigOak, "Big Oak")

It gives me a map with 4 key-value pairs. The pattern I noticed was that the 4 key-value pairs where the actual node and its neighbors, and the other 3 were the neighbors and each of their corresponding neighbors.

Now the question is:

Shouldn’t nest.state.connections be just a Map with the key as the nest (basically the node) and the value as an array of the neighbors? Why is it that nest.state.connections displays a Map with 4 key value pairs instead of just one?

I don’t know if the question is confusing and needs more details or if it’s something simple, but I will provide the repo to the 2 modules on github in case you would like to investigate the code more, and I will frequently check stackoverflow for questions or comments regarding my code.

Thanks in advance!!

The project

Prevent user from navigating the previous page

I have 2 web pages Account.php and Pet_Visit_Hisitory.php
On my Account.php I have a button that has a function

window.location.href = 'Pet_Visit_History.php';

My Pet_Visit_Hisitory.php has a button function

window.location.replace('Account.php');

So it went like this:
Homepage.php (Buttonclick)-> Account.php (Buttonclick)-> Pet_Visit_Hisitory.php (Buttonclick)-> Account.php (GoBack) -> Pet_Visit_Hisitory.php

My goal is to prevent the user from going back to Pet_Visit_Hisitory.php
So it goes like this
Homepage.php (Buttonclick)-> Account.php (Buttonclick)-> Pet_Visit_Hisitory.php (Buttonclick)-> Account.php (GoBack) -> Account.php

Convert value to javascript array

I am passing a value into a javascript function from an html button. The value looks like the following.

enter image description here

As you can see it is an array of key value pairs. How do I convert it so that it looks like the following:

enter image description here

I want to do this so I can access the array in javascript. Here is the HTML and JS code:

<button value="{{data}}" id="generate-btn" name="generate-btn">Generate</button>
document.getElementById("generate-btn").addEventListener("click", function() {
  console.log("generate button clicked");
  let message = document.getElementById("generate-btn").value;
});

Flickity js | Images keep overlapping one above another until resize screen

So i am trying to make dynamic flickity slider so when you click on template image, it opens up a slider

I am having an issue with the images that are overlapping one over another so the slider wont work. i cant force display flex on the viewport.

It is important to note that if i resize the window size, sliders starts working propperly.

Here is my fiddle

carousel-cell’s keep getting style="position: absolute; left: 0px; transform: translateX(0%);"
instead of style="position: absolute; left: 0px; transform: translateX(100%);"

I have tried setting up new flickity after adding new cells but nothing helps

Is HEC-RAS could be Solved with python or javascript?

Floodplain Mapping is done by River Analysis with HEC-RAS software and the changes in River due to Flood are seen.

Can this work be done with the help of any Python or JavaScript library/framework / anything else????
If so, it will be very helpful if you tell me the source of that library / framework/documentation. Thanks in advance.enter image description here

I cannot find any solution to do this as I am beginning in javascript and python.

Vite with react baseUrl Problem, tries to load files from prefix path

I am using Vite with React and encountering a strange problem.

I have set the baseUrl in my tsconfig to be “src”
I have set the base in the defineConfig in vite.config.ts file to be ‘/’

But for some reason if I go to a path after the first prefix it tries to get the files from the relative path instead of the base path.

for example if I go to
HTTP://127.0.0.1:8080/home/hi

I get the error:

GET HTTP://127.0.0.1:8080/hi/src/main.tsx net::ERR_ABORTED 404

I am running the dev server using this command in the scripts:

"dev": "vite"

Any idea why this is happening?

Agora livestream video or complete guide [closed]

I am new to Agora and frankly speaking the web SDK documentation is almost non-existent. Also cant seem to find good tutorials on YouTube. Does anyone know any link to a video or text tutorial on how to setup a Livestream webapp with Agora web SDK. Please its urgent

I have gone through the Agora documentation and Youtube. Agora documentation describes how to clone the git repo and run the template(not how to write it on your own). Youtube videos are mostly 5x time-lapse or glossing over already completed code. I just wan a tutorial for absolute beginner. showing how to setup and stream, while others join the stream. Thank you

My data array from my Google Ads API script request sometimes has duplicate data rows how do I merge?

Newbie question: My data array (from google ads scripts) has ~20% duplicate rows in it. How do i combine those duplicates, and their data together?

Hello,

I am a new javascript programmer using Google Ads Scripts to fetch data from our client’s Google Merchant Center (product shopping ads data), process that data, then use in optimizing their campaign(s). I am using their Shopping Performance Report api to report on impressions, clicks, revenue, etc. The data is pulled into a google sheet and then i wrote some javascript to process that data row by row, looking at the values and making decisions, labeling product performance into one of 8 different performance categories (‘top performer’, ‘worst performer’ etc.). At the end of that row loop, i store that row’s data into a temporary array (‘tempArray’). I do that for all the rows in the api report object.

My problem is the data sometimes returns two rows for the product ID. Not sure why, will ask Google. However, I need to do the following just don’t know how yet:

Once the data is finished processing, I need to loop through it and combine any elements that have the same product Id AND combine their values (clicks total = duplicate 1 clicks + duplicate 2 clicks, impressions total = duplicate 1 impressions + duplicate 2 impressions).

The tempArray data looks like this (example duplicate elements):

[
    [shopify_US_8059591393525_43884977225973, null, Chasing Joy Hat in Khaki, 8, 0,     0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, low impressions],  
    [shopify_US_8059591393525_43884977225973, null, Chasing Joy Hat in Khaki, 12094, 115, 0.009508847362328427, 36.93, 1.165053, 87.08227563, 31.698128754657517, 2.3580361665312752, 0.010130895652173913, under-index]]

Do I need to change the data structure to an array of objects, then use a JS array function like map or reduce? I found this article on merging duplicates but it was too complex at first glance: https://www.tutorialspoint.com/merge-and-remove-duplicates-in-javascript-array

Thanks in advance!

I’ve considered trying the map() function but wanted to reach out first on what some options might be.

How difficult to convert single-tenant web app into multi-tenant web app?

StackOverflow community!!

I’m a non-profit organization providing software service to rural medical clinics. I have a single-tenant web app with single SQL database. Is it difficult to convert the web app into a multi-tenant webapp that provides a separate database to each clinic?

I’m using a cloud provider to host the app. I’m not charging clinics to use the webapp, so I want to minimize my cost on cloud. That’s why I would like to convert the single-tenant webapp into multi-tenant to serve multiple clinics with one codebase. The webapp was developed with .NET and the backend was written in C#. Database server is Microsoft SQL. A developer is charging me $15k to convert the webapp into multi-tenancy! Is that too much?

I appreciate any help. Thank you for taking time to read my question!

I can’t send separate data for each sale_velue with different ids

{changeData.active_id_fk.map((cod, index) => ( <React.Fragment key={active_id_fk${index}`}>
{list.active.map(({ active_id, model }, index) => {

                                            if (cod == active_id) {
                                                return (
                                                    <tr key={`model_${index}`}>
                                                        <th>{cod}</th>
                                                        <td>{model}</td>
                                                        <td>{changeData.internal == 0 && 
                                                            <Input
                                                                type="string"
                                                                required
                                                                name="sale_value"
                                                                placeholder="R$ 0,00"
                                                                onInput={(e) => maskMoneyBRL(e)}
                                                                value={changeData.sale_value}
                                                                onChange={handleChangeMoney} 
                                                            />}
                                                        </td>
                                                    </tr>
                                                )
                                            }
                                        })}
                                    </React.Fragment>
                                ))}

`

I need to send different amounts to the sale_value

I tried to create an array to capture the values of each input as it didn’t work out very well.

Want to learn Full stack development [closed]

Hello people I have a biggest doubt in my life I am 21 years old guy doing bca i actually wanted to become full stack developer from the beginning of my degree but due to family and financial problem I can’t learn coding properly I am at my last year I have only basic knowledge in theoretical so can give me some guidance how to start my journey

Become a good and experienced developer

Why useState is not changing in event listener

When I change state in my school event listener is not changing inside, like I have constantly setting isScrollable to true, but it should set only one time , when scroll is happens

  const [isScrollable, setIsScrollable] = useState(false);
  const scrollableDiv = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const current = scrollableDiv.current;

    const handleScroll = debounce(() => {
      if (!isScrollable) {
        console.log("setting");
        setIsScrollable(true);
      }
      //code...
    }, 16);

    if (current) {
      current.addEventListener("scroll", handleScroll);
    }

    return () => {
      if (current) {
        current.removeEventListener("scroll", handleScroll);
      }
    };
  }, []);```