useEffect not updating variables on function call

I have a component called Date with three variables. I also have a function called setCurrentTimes that is supposed to update the variables each time it is called with the current values.

I call the function inside react’s useEffect that has no dependencies to update the variables on the component mount.

Here is the date component.

const Date = () => {
  var currentDate;
  var currentTime;
  var amOrPm;

  const setCurrentTimes = () => {
    currentDate = moment().format("d MMMM YYYY");
    currentTime = moment().format(" h:mm:ss ");
    amOrPm = moment().format("a");
  };

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

  return (
    <div className="Date flex__container-v">
      {amOrPm === "pm" ? (
        <div className="Moon__icon flex__container">
          <img src={Assets.Moon} alt="Moon Icon" />
          <p className="p__poppins Date__greeting">Good Evening</p>
        </div>
      ) : (
        <div className="Sun__icon flex__container">
          <img src={Assets.Sun} alt="Sun Icon" />
          <p className="p__poppins Date__greeting">Good Morning</p>
        </div>
      )}
      <div className="Date__btm flex__container">
        <p className="p__poppins">{currentDate}</p>
        <p className="p__poppins">{currentTime}</p>
      </div>
    </div>
  );
};

The component returns different things depending on the variables. However, it is not working as expected. When I try to log out the variables inside the return statement I get undefined.

I don’t get what I am doing wrong.

Dynamically update value based on State in React

I have a react class based component where I have defined a state as follows:

class MyReactClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          selectedDataPoints: new Set()
        };
    }
    
    render () {
        return (
            <p>{this.state.selectedDataPoints}</p>
        );
    }
}

Note that initially, the state is an empty set, nothing is displayed.
But when the state gets populated eventually, I am facing trouble in spinning up the variable again. It is always taking as the original state which is an empty set.

How can I start using dwv (DICOM Web Viewer) on my website?

I’m new to JavaScript.

To view DICOM images I want to use this DICOM Web Viewer by ivmartel:

https://github.com/ivmartel/dwv

I have downloaded it and installed it using YARN. I can test run it using yarn run test.

But how can I implement it on my website?

I just wanted to use it here:

https://ivmartel.github.io/dwv/doc/stable/tutorial-examples.html

I just copied the codes existing here:

https://jsfiddle.net/ivmartel/kkp7ytk3/

But it looks like it can’t import dwv at all.

Code of my page looks like this:

<!DOCTYPE html>
<html>
 
<head>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script src="dwv-develop/src/app/application.js"></script>
    <title>
        JavaScript to check existence of variable
    </title>
</head>
         
<body>        
    <div id="dwv">
        <div id="layerGroup0"></div>
      </div>
      
    <script>
        var app = new dwv.App();
        // initialise with the id of the container div
        app.init({
        dataViewConfigs: {'*': [{divId: 'layerGroup0'}]},
        tools : {
            WindowLevel: {}
        } // or try "ZoomAndPan"
        });
        // activate tool once done loading
        app.addEventListener('load', function () {
        app.setTool('WindowLevel');
        });
        // load dicom data
        app.loadURLs(['https://raw.githubusercontent.com/ivmartel/dwv/master/tests/data/bbmri-53323851.dcm']);// create the dwv app
    </script>
</body>
 
</html>   

How can I import dwv to make it work on my website?

Prevent opening of new window (stay in current)

I need to force all links on a page to open in the same window. Is there a reliable userscript that does this?

It would be applied to a web app that handles links using JS. The code is complex (frameworks + proprietary) and I am not proficient enough to follow it and write a tailor-made script that achieves this.

Already searched for solutions in SO, script reposetories and Chrome plugins, but all I could find is popup blockers. However, I need to open the page and keep it in the same window (target="_self" if it was plain HTML)

Mapping items fetched from API javascript

I am trying to map some items returned to me from a API using a class and constructor with javascript.

My question is what I am doing wrong, since the log before the mapping “Result before Map” logs out my array of items. But after my map I get nothing and everything in my constructor is undefined.

Im probably missing something simple but I am just trying this to do it without a framework using pure javascript in order to learn more 🙂

class Test {
  constructor(obj) {
    this.testValue = obj.testValue
  }
}

async function getItems() {
  const promises = []

  const response = (await fetch(url)).json()
  promises.push(response)

  const result = await Promise.all(promises)
  console.log('Result before Map:', result)
  const tests = result.map(test => new Test(test))
  console.log('Result after Map:', tests)
}

No “exports” main defined in node module’s package.json

I just installed the zx NPM package.

I installed it locally and imported it:

import { $ } from 'zx'

(async () => {
    await $`mkdir test`
})()

But I’m getting this error:

No “exports” main defined in
/home/alex/node/check-image-size/node_modules/zx/package.json

Note: I’m using Node 16.14

What do this kind of error mean, and how to fix it?

Not able to filter array in Jacascript [closed]

I have an array containing colour names and i want to filter out the colours containing the letter o, for example, if i have an array named colours

var colours = ["orange", "red", "yellow", "green", "violet"]

if i want to filter out the colours with the letter orange included, the result would be
“orange”, “yellow”, “violet”.
What is the code to replicate this filtering process?

The react-scripts package provided by Create React App requires a dependency?

The react-scripts package provided by Create React App requires a dependency:
[0]
[0]   "eslint": "^7.11.0"
[0]
[0] Don't try to install it manually: your package manager does it automatically.
[0] However, a different version of eslint was detected higher up in the tree:
[0]
[0]   C:UsersAsustodolistnode_moduleseslint (version: 5.6.0)
[0]
[0] Manually installing incompatible versions is known to cause hard-to-debug issues.
[0]
[0] If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
[0] That will permanently disable this message but you might encounter other issues.
[0]
[0] To fix the dependency tree, try following the steps below in the exact order:
[0]
[0]   1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder.
[0]   2. Delete node_modules in your project folder.
[0]   3. Remove "eslint" from dependencies and/or devDependencies in the package.json file in your project folder.
[0]   4. Run npm install or yarn, depending on the package manager you use.
[0]
[0] In most cases, this should be enough to fix the problem.
[0] If this has not helped, there are a few other things you can try:
[0]
[0]   5. If you used npm, install yarn (``http://yarnpkg.com/``) and repeat the above steps with it instead.
[0]      This may help because npm has known issues with package hoisting which may get resolved in future versions.
[0]
[0]   6. Check if C:UsersAsustodolistnode_moduleseslint is outside your project directory.
[0]      For example, you might have accidentally installed something in your home folder.
[0]
[0]   7. Try running npm ls eslint in your project folder.
[0]      This will tell you which other package (apart from the expected react-scripts) installed eslint.
[0]
[0] If nothing else helps, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
[0] That would permanently disable this preflight check in case you want to proceed anyway.
[0]
[0] P.S. We know this message is long but please read the steps above :-) We hope you find them helpful!
[0]
[0] npm run start exited with code 1

Please give me some suggestion.

React component rendering even when there is no change in the state value

From the React Docs, what I have learnt is that the component will re-render only if there is a change in the value of a state.

For instance

import React, { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  console.log("I am rendering");

  const handleButtonClick = () => {
    setCount(0);
  };
  return (
    <>
      <button onClick={handleButtonClick}>Increment</button>
      Count value is: {count}
    </>
  );
}

The message I am rendering is printed only once even if we click the button because the setCount function is setting the value to 0 which is the present value of count

Since there is no change in the present and future value therefore, the Component does not re-render.

Unexpected Behaviour

However, the similar behaviour is not observed when we add an extra line setCount(1) before setCount(0)

import React, { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  console.log("I am rendering");

  const handleButtonClick = () => {
    setCount(1); //this line has been added extra
    setCount(0);
  };
  return (
    <>
      <button onClick={handleButtonClick}>Increment</button>
      Count value is: {count}
    </>
  );
}

In principle, there is no change in the output of the final count value. However, if we click the button, the component re-renders and prints the message I am rendering


I could not find an explanation for this behaviour. Is this behaviour on expected lines?.

Shouldn’t the component re-render only when the final value of the state is different from the current value ?

Synchronize a general timer with functions to turn them off at the end of it

I am new here, also in Javascript. I would like to explain you my problem. I am currently making a JavaScript program consisting of a timer that, once it reaches 0, closes all the pages opened by the site. I managed to create the timer for the visual side, then the buttons to open the websites.

My problem is that I can’t manage to synchronize a timer with the setTimeout of the winYt() functions etc… Because when I put 10s before the page closes, it’s 10s from the moment the user click on the button. What I would like is that the pages close for example in 60s from the moment the global page opens, and therefore the timer starts, and that once the pages are opened with the buttons, they close only at the end of the timer.

I tried to link a timer function by putting it in a z variable to put it in the setTimeout, but it opens and closes the pages directly no matter what I try and what modification I try.

I also thought of making a timer that takes the exact time of when the site opens, then 5 minutes later, closes the pages (opened by the buttons only).

I come to ask you for help to find a function to make my pages close when the general timer reaches 0 only.

Thanks in advance,

Here’s the general code:

document.getElementById("timer").style.color = "rgb(72, 0, 130)";
document.getElementById("timer").style.fontFamily = " Comic sans MS";
let temps = 10
const timerElement = document.getElementById("timer")



var X = 11200
var win = window.open("https://waytolearnx.com", "_blank", "width=auto, height=auto");
win.opener = window;
win.focus();
opener=self;
setTimeout("win.close()",X) 


function diminuerTemps() {
    let minutes = parseInt(temps / 60,10)
    let secondes = parseInt(temps % 60,10)
            
    minutes = minutes < 10 ? "0" + minutes : minutes
    secondes = secondes < 10 ? "0" + secondes : secondes
            
    timerElement.innerText = minutes + ":" + secondes
    temps = temps <= 0 ? 0 : temps -1
    
}
setInterval(diminuerTemps, 1000);

function winYt() {
    const Yt = window.open("https://www.youtube.com/", "_blank");
    setTimeout(function() {Yt.close()}, z);
}

function winKr() {
    const Kr = window.open("https://krunker.io/", "_blank");
    setTimeout(function() {Kr.close()}, z);
}

function winBk() {
    const Bk = window.open("https://bonk.io/", "_blank");
    setTimeout(function() {Bk.close()}, z);
}

function winSv() {
    const Sv = window.open("https://surviv.io/", "_blank");
    setTimeout(function() {Sv.close()}, z);
}

If you want, I can send you my test functions that I made

Have a nice day.

Adding new line for image id to Crowd Elements Json output result

I’m creating an annotation-tool using the Crowd HTML Elements that let users annotate images with the bounding box format. The form looks like this:https://codepen.io/sagemaker_crowd_html_elements/pen/XWpJGad?editors=1111.

<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>

<crowd-form>
  <crowd-bounding-box
    name="annotatedResult"
    src="https://images.unsplash.com/photo-1533713692156-f70938dc0d54?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=2467&q=80"
    header="Draw bounding boxes around all the cats and dogs in this image"
    labels="['Fish', 'Coral', 'Turtle']"
  >


    <full-instructions header="Bounding Box Instructions" >
      <p>Use the bounding box tool to draw boxes around the requested target of interest:</p>
      <ol>
        <li>Draw a rectangle using your mouse over each instance of the target.</li>
        <li>Make sure the box does not cut into the target, leave a 2 - 3 pixel margin</li>
        <li>
          When targets are overlapping, draw a box around each object,
          include all contiguous parts of the target in the box.
          Do not include parts that are completely overlapped by another object.
        </li>
        <li>
          Do not include parts of the target that cannot be seen,
          even though you think you can interpolate the whole shape of the target.
        </li>
        <li>Avoid shadows, they're not considered as a part of the target.</li>
        <li>If the target goes off the screen, label up to the edge of the image.</li>
      </ol>
    </full-instructions>



    <short-instructions>
      Draw boxes around the requested target of interest.
    </short-instructions>
  </crowd-bounding-box>
</crowd-form>  

JSON OUTPUT:

TaskAnswers
[
  {
    "annotatedResult": {
      "boundingBoxes": [
        {
          "height": 456,
          "label": "Fish",
          "left": 1010,
          "top": 411,
          "width": 1028
        },
        {
          "height": 434,
          "label": "Fish",
          "left": 85,
          "top": 1313,
          "width": 1542
 }
      ],
      "inputImageProperties": {
        "height": 1850,
        "width": 2467
      }
    }
  }
]

But i new a line for image id because i need to save this result in database with image id and i have many images.

I want to take this output with image_id and write it to a database. But I don’t know how to add a new line to JSON and how to save it in a remote database. I tried adding some properties and javascript code but it didn’t help me. If anyone has a solution it would be great! Or where can i find to source code for crowd element?

{
    "image_id": 297992,// what i need
    "annotations": [
      {
    "annotatedResult": {


      "boundingBoxes": [
                {
          "height": 223,
          "label": "placeholder",
          "left": 168,
          "top": 173,
          "width": 238
        }
      ],


      "inputImageProperties": {
        "height": 800,
        "width": 800
      }
    }