How to list and record all network requests and response times in Cypress

I am looking to convert all requests from cy.intercept() into json objects that include: {'method':'____', 'url':'____', 'response_time':'____'} so that they can be written to a json file for performance analysis.

I am currently able to show all of the request methods and URL’s but not their response times.

Current code to get network requests:

cy.intercept({method:'GET', url:'**'}).as('gets');
cy.intercept({method:'POST', url:'**'}).as('posts');
cy.visit('url');

Is it possible to iterate through these individual requests with their response times and save them within an array?

I have tried saving the value returned from intercept() as a variable but it doesn’t show all of the requests or their response times.

var gets = cy.intercept({method:'GET', url:'**'}).as('gets');
var posts = cy.intercept({method:'POST', url:'**'}).as('posts');
cy.visit('url');

cy.writefile('file1.json', gets);
cy.writefile('file2.json', posts);

Thanks in advance.

Paperjs tool seems to be working, but does not display anything

I’m trying to get a multiple tool paperjs example going that is a bit of a vector based “paint program”.

I’m trying to do this with a toolStack class from a Stack Overflow suggestion. The original post has two placeholder tools and I added another. The two native tools work fine and display, my third tool “multiLine” (which runs fine as a stand along file) seems to be working, does not throw errors in the browser, and from inspecting the results seems to have data in the structures. However the third tool doesn’t display.

I realize the syntax is different in different section of the code. Both syntaxes seem to work fine. I’m new to Javascripting so don’t know if this is an issue. Thanks in advance for any eyes or suggestions about the code.

Paul

<!-- Multiple Tools Paper Example -->

<!DOCTYPE html>
<html>
<style>
    html,
    body,
    canvas {
      width: 100%;
      height: 100%;
      margin: 0;
    }
</style>
<script>
    window.onload = () => {
      // Setup Paper
    
      paper.setup(document.querySelector('canvas'))
    
      // Toolstack
    
      class ToolStack {
        constructor(tools) {
          this.tools = tools.map(tool => tool())
        }
    
        activateTool(name) {
          const tool = this.tools.find(tool => tool.name === name)
          tool.activate()
        }
        
        
    
        // add more methods here as you see fit ...
      } 


  // Tool Path, draws paths on mouse-drag
    
      const toolPath = () => {
        const tool = new paper.Tool()
        tool.name = 'toolPath'
    
        let path
        
    
        tool.onMouseDown = function(event) {
          path = new paper.Path()
          path.strokeColor = '#4242ff'
          path.strokeWidth = 15;
          path.add(event.point)
        }
    
        tool.onMouseDrag = function(event) {
          path.add(event.point)
          console.log(path);
        }
    
        return tool
      }
    
      // Tool Circle, draws a 30px circle on mousedown
    
      const toolCircle = () => {
        const tool = new paper.Tool()
        tool.name = 'toolCircle'
    
       
    
        let path
    
        tool.onMouseDown = function(event) {
          path = new paper.Path.Circle({
            center: event.point,
            radius: 30,
            fillColor: '#9C27B0'
          })
        }
    
        return tool
      }
      
      
      // This is the tool I added which does not display
      const multiLine = () => {
        const tool = new paper.Tool()
        tool.name = 'multiLine'
      
        var values = {
                        //lines: 5,
                        lines: 4,
                        //size: 40,
                        size: 10,
                        smooth: true
                    };        
            
        var paths;     
        
        
//          tool.onMouseDown = function(event) {   // this worked for debugging the tool
//        path = new paper.Path()               
//            path.strokeColor = '#ff4242'
//            path.strokeWidth = 10  
//        path.add(event.point)
//      }
//  
//     tool.onMouseDrag = function(event) {
//        path.add(event.point)
//          }
      
      
        tool.onMouseDown = function(event) {
                        paths = [];
                        for (var i = 0; i < values.lines; i++){
                            var path = new paper.Path();
                            path.strokeColor = '#FF2222';
                            path.strokeWidth = 25;
                            paths.push(path);
                            console.log(i);
                        }
                    }
                                                
       tool.onMouseDrag = function(event){
                      
                        var offset = event.delta;
                        offset.angle = offset.angle + 90;
                        
                        var lineSize = values.size / values.lines;
                        for (var i = 0; i < values.lines; i++) {
                            var path = paths[values.lines - 1 - i];
                            //offset.length = lineSize * i + lineSize / 2;
                            
                            offset.length = (-i * lineSize)  * (Math.max(event.delta.length /15, 1));
                            path.add(event.middlePoint + offset);
                           // path.smooth();
                            console.log(paths[1]);
                        }
                    }
            return tool
            }        
                    
      
    
    
      // Construct a Toolstack, passing your Tools
    
      const toolStack = new ToolStack([toolPath, toolCircle, multiLine])
    
      // Activate a certain Tool
    
      toolStack.activateTool('toolPath')
    
      // Attach click handlers for Tool activation on all
      // DOM buttons with class '.tool-button'
    
      document.querySelectorAll('.tool-button').forEach(toolBtn => {
        toolBtn.addEventListener('click', e => {
          toolStack.activateTool(e.target.getAttribute('data-tool-name'))
        })
      })
    }
    
    //       function onKeyDown(event) {
//                          if (event.key == 'd'){
//                              project.activeLayer.removeChildren();
//                          }
//                          if (event.key == 'z'){
//                              project.activeLayer.removeChildren(project.activeLayer.lastChild.index);
//                          }
//  
//                      }
</script>
<head>
<title>
StackExchange Multiple Tools
</title>
<meta name="generator" content="BBEdit 14.1" /> 
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-core.js">
</script>
<button class="tool-button" data-tool-name="toolPath">
Draw Paths 
</button>
<button class="tool-button" data-tool-name="toolCircle">
Stamp Circles 
</button>
<button class="tool-button" data-tool-name="multiLine">
Multi Lines
</button>
<canvas resize>
</canvas>
</body>
</html>

positioning elements right property based on other dynamic values with CSS JS

I have a primary menu with two sub-menus nested inside. the sub menus are revealed on a hover, and have a dynamically changing width based on the content inside. I need the sub menus position relative to the main menu to be: the left border of the sub menu is touching the right border of the main menu and they are not overlapping. Common functionality of a sub menu on hover reveal I suppose.

So I believe the math for the css right positioning is something like:

right: -elements current width in px

I don’t believe theres a way in css to insert the elements current width value into the right position so I have tried with JS

    let subMenuBounds = subMenuOne.getBoundingClientRect()
    let subMenuTwoBounds = subMenuOne.getBoundingClientRect()

    subMenuOne.style.right = `-${subMenuBounds}px`
    subMenuTwo.style.right = `-${subMenuTwoBounds}px`

the problem with this is the subMenus have no bounds until I hover over the menu, because the display is set to: none.

any solution to this?

    let subMenuBounds = subMenuOne.getBoundingClientRect()
    let subMenuTwoBounds = subMenuOne.getBoundingClientRect()

    subMenuOne.style.right = `-${subMenuBounds}px`;
    subMenuTwo.style.right = `-${subMenuTwoBounds}px`;
.sub-menu-one,
.sub-menu-two {
  height: auto;
  width: auto;
  min-width: 12rem;
  position: absolute;
  top: 0;
  right: ??;
  border-radius: 5px;
  display: none;
  opacity: 0;
  transition: all 350ms;
  border: 1px solid #e4e4e4;
  background-color: #2e1a04;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  z-index: 3;
}

.menu-row:nth-child(2):hover > .sub-menu-one,
.menu-row:nth-child(3):hover > .sub-menu-two {
  opacity: 1;
  transition-delay: 350ms;
  display: block;
}
<div class="menu">
        <div class="menu-container">
            <div class="menu-row">
                <i class="fa-solid fa-book"></i>
                <h2>Syno &bull; Checker</h2>
                <span id="menu-close-btn">X</span>
            </div>
            <div class="menu-row">
                <p>Definition</p>
                <i class="fa-solid fa-caret-right"></i>
                <div class='sub-menu-one'>
                    <div>
                        <blockquote>
                            <p id="selected-word"></p>
                        </blockquote>
                    </div>
                    <div class="definition"></div>
                </div>
            </div>
            <div class="menu-row">
                <p>Synonyms</p>
                <i class="fa-solid fa-caret-right"></i>
                <div class='sub-menu-two'>
                    <div>
                        <blockquote>
                            <p id="selected-word-two"></p>
                        </blockquote>
                    </div>
                    <div class="options"></div>
                </div>
            </div>
        </div>
    </div>

Fix/modernize website log in that queries another site for authentication

First, please look at https://staging.upstatetoday.com/letmein

I have inherited a very old log in mechanism that has begun to not work lately – Firefox refuses to log users in, other browsers can be iffy, too. The site is wordpress, but the login is a different server (paywall).

Correct behavior is: insert username and password, click login button, page refreshes and sends user to the homepage if authentication is valid; alert drops that the username/password is incorrect if invalid.

This only seems to happen corectly in Chrome on the desktop, and sometimes in Edge. Firefox just refreshes the page. There are no js errors.

The login button is supposed to call a JS function that stores the current url (not needed in this implementation) then calls a function (in the wordpress functions.php file) that queries a separate site with the username and password and receives an XML response. That response is evaluated for a Yes and the user is allowed in or not, based on that xml response. If the user is allowed, the JS function returns the user to the page where they last were. If they are not allowed, the JS function alerts with bad user or pass msg.

Anyone can go to any post or page, but the single.php template is modified to check for authentication. If they are authenticated, they see the post. If not, they see a notice to subscribe or log in.

But, There’s more going on in the code that is not needed (?) and I think there is unnecessary duplication of the process.

You can see the dialog at the link on top. Please ignore the styling (coming later).

I have moved code, tried snippets, php sessions, but nothing is working in Firefox at all, and with no error messages, I do not know how to proceed.

This is the code for the login dialog:

<?php if(!isset($_SESSION['auth']) ) { ?>
    <a href="https://seneca.newzware.com/ss70v2/seneca/common/template.jsp?" target="new">Forgot user name/password? Click Here</a> 

    <form>
    <div class="form-group">
        <label for="pwd">User name:</label>
        <input type="text"  autocomplete="user-name" class="form-control" id="user-name" placeholder="Enter user name" style="width:200px; margin-bottom:5px;"/></div>
        
    <div class="form-group">
        <label for="pwd">Password:</label>
            <input type="password" autocomplete="current-password" class="form-control" id="pwd" placeholder="Enter password" style="width: 200px;margin-bottom:5px;"/> <button type="submit" class="btn btn-primary" id="sub-sign-in" style="color:blue;font-size:1.0em">Log in to Upstate Today</button>  </div>
    </form>
        <a href="https://seneca.newzware.com/ss70v2/seneca/common/template.jsp?#v3-registration-div" target="new"><button class="btn btn-default">Register or Renew Subscription </button> </a> 

<?php } else { ?>   
"<script type="text/javascript">   
    function Redirect() 
    {  
        window.location="https://staging.upstatetoday.com"; 
    } 
    document.write("You will be redirected to the homepage in 5 seconds"); 
    setTimeout('Redirect()', 5000);   
</script>"
<?php } ?>

This is the js that is called by “sub-sign-in” :

jQuery(document).ready(function( $ ){
  var pageURL = $(location).attr("href");
    localStorage.setItem("page_url", pageURL);
  console.log('ready');
  $('#sub-sign-in').click(function(){
    console.log('enter');
      var user_name=$('#user-name').val();
      var password=$('#pwd').val();
    $.ajax({
      type: "POST",
      url: '/wp-admin/admin-ajax.php',
      data: ({
        action: "check_address",
        name: user_name,
        pass:password
      }),
      success: function (response){
        console.log(response);
        var pg_url = localStorage.getItem("page_url");
        if(response == 'Yes0'){
         window.location.replace(pg_url);
        }
        else{
        alert('wrong username or password');
        }
      },
    error: function(error){
    console.log(error);
    }
    });
  });
});

This is the code from the child theme functions.php



function register_my_session()
{
  if( !session_id() )
  {
    session_start();
      }
}

add_action('init', 'register_my_session');

  /*     session_write_close(); */


function check_address()
{
$name = $_POST["name"];
$password = $_POST["pass"];
/*$edition = $_POST["edition"];
$subdate = $_POST["subscriptiondate"]*/
$response = wp_remote_get( 'https://seneca.newzware.com/authentication/auth70_xml.jsp?site=seneca&login_id='.$name.'&password='.$password);
$xml = simplexml_load_string($response['body']);
$isValid = (string) $xml->authenticated;
if(!session_id()) {
session_start();
}
if($isValid == 'Yes'){
$_SESSION['auth'] = '1';
}
echo $isValid;


}
add_action( 'wp_ajax_check_address', 'check_address' );
add_action( 'wp_ajax_nopriv_check_address', 'check_address' );
add_action( 'wp_enqueue_scripts', 'hello_elementor_child_enqueue_scripts', 20 );

function wpb_widgets_init() {
 
    register_sidebar( array(
        'name'          => 'Custom Header Widget Area',
        'id'            => 'newzware-widget',
        'before_widget' => '<div class="newzware-widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="newzware-title">',
        'after_title'   => '</h2>',
    ) );
 
}
add_action( 'widgets_init', 'wpb_widgets_init' );
 

This is the single post content that includes whether the user can read that post or not (ie, is authenticated):


<?php
/**
 * The template for displaying singular post-types: posts, pages and user-defined custom post types.
 *
 * @package HelloElementor
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}
?>


<?php
while ( have_posts() ) :
    the_post();
    ?>

<main id="content" <?php post_class( 'site-main' ); ?> role="main">
    <?php if ( apply_filters( 'hello_elementor_page_title', true ) ) : ?>
        <header class="page-header">
            <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
        </header>
    <?php endif; ?>
    <!-- Newzware Protection Code -->   
    
    <?php
        $key = 'Free Story';
        $themeta = get_post_meta($post->ID, $key, TRUE);
        if($themeta != '') {
        $free_story = 1; 
        }
    ?>

    <?php if($_SESSION['auth'] == '1' OR current_user_can( 'read_post' ) OR $free_story == '1' ) { ?>   
    
    <!-- end part 1Newzware Protection Code --> 
    
    <div class="page-content">
        <?php the_content(); ?>
        
    <!-- beginpart 2 Newzware Protection Code -->       
<?php } else { ?>

<div class='ifsub-panel'> <div class='ifsubpanel-heading' style='background:#2318A4; color:#fff; text-align:center;'><b>Subscribe To The Journal</b></div><div class='ifsubpanel-body'>  <p style='text-align:center'>
If you are already registered with <a href="https://upstatetoday.com">UpstateToday.com</a>, please click the LOGIN button in the upper left corner of this window to log in and continue reading.<br><br>
            
If you'd like to subscribe,<br>
<a href='https://seneca.newzware.com/ss70v2/seneca/common/template.jsp?nwmodule=nonsubscribers&nwpage=nonsubstart'><b class="text-danger"> Please click here for options. We'd love for you to join our family.</b></a></p>
</div></div>
        

    
    <?php } ?>
    
    
    <!-- End Newzware Protection Code -->       
        <div class="post-tags">
            <?php the_tags( '<span class="tag-links">' . __( 'Tagged ', 'hello-elementor' ), null, '</span>' ); ?>
        </div>
        <?php wp_link_pages(); ?>
    </div>

    <?php comments_template(); ?>
</main>

    <?php
endwhile;



I want to make this work reliably in desktop and mobile browsers. I’d love to have a user tap a login button, go to a page with the dialog, log in, then return to the home page.

Thanks for your time and pointers.

Getting warning from props passed in MUI styled components related to React not recognizing it

I have a styled component that needs to receive props to decide how it should be styled. Looks something like this:

const StyledTypography = styled(Typography)(
  ({ myColor = "black", isLarge = false }) => ({
    "&&": {
      fontSize: isLarge ? 30 : 16,
      border: `1px solid ${myColor}`,
      margin: 10,
      color: myColor
    }
  })
);

Unfortunately isLarge causes the following warning:

Warning: React does not recognize the isLarge prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase islarge instead. If you accidentally passed it from a parent component, remove it from the DOM element.

(Same with myColor)

In another thread, I was told that all that needs to be done is to use shouldForwardProp as a function returning a boolean in the second parameter to decide what props should be passed in tot the DOM DOM:

const StyledTypography = styled(Typography, { shouldForwardProp: () => false })(
 ...
);

Unfortunately this doesn’t work.

Is there anyway to do this?

Here is a working sample app with the warnings and everything: https://codesandbox.io/s/crimson-fast-qll47?file=/src/App.js

How is this search keyword turned into a “key”?

I am testing my web app to pull the API from target.com; here is the API request, (I got from their site.)

https://redsky.target.com/redsky_aggregations/v1/web_platform/product_summary_with_fulfillment_v1?key=9f36aeafbe60771e321a7cc95a78140772ab3e96&tcins=15013944%2C78438139%2C53318237%2C14599316%2C54541751%2C77632333%2C81415000%2C26396441%2C16951592%2C53140802%2C17316062%2C82095690%2C51964661%2C81471842%2C14394368%2C79314666%2C14779713%2C53140800%2C54557726%2C15346395%2C79276537%2C16185593%2C79314685%2C82439935%2C53318237&store_id=666&zip=43016&state=OH&latitude=40.060&longitude=-83.150&scheduled_delivery_store_id=1969&required_store_id=666&has_required_store_id=true

What it does is to search “banana”, but it was turned into the “key”. How is this done?

How to Setup send email function in html form using any programing language? [closed]

The html form code given as follow how to setup this contact form to get email to my account
using any language:

<form action="" method="post">
    <div class="fields">
        <div class="field name">
            <input type="text" placeholder="Name" name="name" required>
        </div>
        <div class="field email">
            <input type="email" placeholder="Email" name="email" required>
        </div>
    </div>
    <div class="field">
        <input type="text" placeholder="Subject" name="subject" required>
    </div>
    <div class="field textarea">
        <textarea cols="30" rows="10" placeholder="Message.." name="message" required> 
        </textarea>
    </div>
    <div class="button-area">
        <button type="submit">Send message</button>
    </div>
</form>
<!-- html form code  -->

leafletMap: is there any different between L.map and

I am following the leafletjs guide from here :
https://vue2-leaflet.netlify.app/components/LIcon.html#demo

and just adding stuffs into the component like this:

<l-map ref="myMapstats" :zoom="zoom" :center="center">
        <l-tile-layer
          url="https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png"
          attribution='&copy; <a target="_blank" 
           href="http://osm.org/copyright">OpenStreetMap</a>'
        ></l-tile-layer>
        <l-marker 
        :lat-lng="[47.413220, -1.209482]"
        :icon="icon" > 
        </l-marker>
          <l-icon 
           :icon-anchor="iconAnchor" 
           :icon-size="iconSize" 
            :popup- 
           : anchor="popupAnchor">
           icon-url="static/images/baseball-marker.png" >
          </l-icon>


          <l-popup>
           LOL
          </l-popup>
        </l-marker>
      </l-map>

And importing like this: import {LMap, LTileLayer, LMarker, LIcon} from ‘vue2-leaflet’;
So I am able to use LMAP and other components from ‘vue2-leaflet’;

But, I can see many people are using the same leafletmap in different way,
and the L.Marker in this way and then adding to the map, see below:

var map = L.map('map').setView([51.495, -0.09], 15);
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmLayer = new L.TileLayer(osmUrl, {
  maxZoom: 19,
  attribution: 'Map data © OpenStreetMap contributors'
});
map.addLayer(osmLayer);

var marker1 = L.marker([51.497, -0.09], {
  title: "marker_1"
}).addTo(map).bindPopup("Marker 1").on('click', clickZoom);



So for example I want to create a function ‘clickHandler(index)’, in my map ( the first Example ), and then calling the function from marker and in function I am using the LMap.setView()…., and when I run I am getting error, LMAP not define.

Just want to know id there any differennce between :
'<l-map> </l-map>' and 'var map = L.map('map')'

Thanks in advance!

 <l-marker
          v-for="(marker, index) in markers"
          :key="index"
          @click="clickHandler(index)"
  >

....... more code here ....

methods: {
   clickHandler(index) {
      LMap.setView(markers[index].location, 13);
      //this.$refs.myMapstats;
      markers[index].openPopUp();
    },
}

Access node crypto or webcrypto in the same file

In a TS package designed to run in both nodeJS and a browser, I want to access secure random generation from either crypto.getRandomValues(browser) or crypto.randomFillSync(node).

In package.json, I have "type": "module", my whole library uses ES6 imports (so require is not defined).

Unfortunately, the node crypto module must be imported to be usable. The import statement cannot “hide” inside if, so it will crash when run in the browser.

if(typeof crypto == "object"){ //we are in a browser
  fillRandom = crypto.getRandomValues
}
else{ //node
  import crypto from "crypto" //Err: Cannot use import outside a module (browser)
  fillRandom = crypto.randomFillSync
}

With commonJS I could simply use require("crypto"), but I have already fully commited to using ESM modules.

I imagine I could swap out this part of the code before compiling TS for browser/node, so both versions would have the code that makes sense in their enviroment, but I don’t know how, it seems a bit overkill.

Is there a way?

CSS modification not applying to the project at all?

I created a website to teach blind typing. However, while running it, i noticed that none of my CSS midifications happen… I tried debugging and searching the internet for similar problems but I cannot find the problem myself and so will appreciate a second pair of eyes to look it over and help me resolve this…
Thanks in advance <3

My HTML code:

    <head>

        <title>Blind Typing</title>
        <h2> Learn how to type blindly today! </h2>
        <h4> Follow these simple exercises and become a blind typer! </h4>
        <link rel="stylesheet" href="../blindTyping.css">
        <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
        <script src="../blindTyping.js"></script>

    </head>

    <body>
        
        <div>
        
            <div class="exp">
        
                Copy the following quote, without looking at the keyboard!, to the best of  you ability.
        
            </div>
            
            <div class="menu">
                
                Choose diffeculty level:
                <ul>
                    <li><button class="easy">Beginner</button></li>
                    <li><button class ="mid">Intermediate</button></li>
                    <li><button class="hard">Expert</button></li>
                </ul>
            </div>
        
            <div class="original" id="exc">
        
            </div>
            
            <div id="timer">
            
                <button class="start">start</button>
                <button class="stop">stop</button>
                <p class="timer"></p>
            
            </div>
        
            <div class="copy" id="exc">
        
                <input type="text">
                
                <p id="msg" class="oops" background-color="red"></p>
                <p  id="msg" class="success" background-color="green">Congratulation! You made it! Now go and try the next one! </p>
            
                <button class="under" id="next">Next Exercise</button>
                <button class="under" id="return">Return to Menu</button>
                
            </div>
        </div>

    </body>

</html>

My javascript code:

/*global $, document*/

var easy = ["This is a test", "This is another test"];
var med = ["This is a medium quote"];
var hard = ["This is a hard quote"];

var cntq, currIndex = 0, mistakes = 0;

$(document).ready(function () {
    "use strict";
   
    $("#exc").hide();
    $(".oops").hide();
    $(".success").hide();
    $(".stop").hide();
    
        
$(".easy").on("click", function () {
    cntq = easy;
    $("#exc").show();
    $(".menu").hide();
    $(".original").html("<p>"+easy[currIndex]+"</p>");
});
    
$(".mid").on("click", function () {
    cntq = med;
    $("#exc").show();
    $(".menu").hide();
    $(".original").html("<p>"+med[currIndex]+"</p>");
});
    
$(".hard").on("click", function () {
    cntq = hard;
    $("#exc").show();
    $(".menu").hide();
    $(".original").html("<p>"+hard[currIndex]+"</p>");
});
    
$("#next").on("click", function () {
    currIndex++;
    mistakes = 0;
});
    
$("#return").on("click", function () {
    $("#exc").hide();
    currIndex = 0;
});
    
$("input").on("input propertychange", function () {
    $(".oops").hide();
    $(".success").hide();
    var chk = $("input").val();
    var org = cntq[currIndex];
    var errorFound = false;
    var newHTML = "";
        
    // Check letter by letter if the input matches the original sentence
    for(var i=0; i<chk.length&&!errorFound;i++){
        if(chk[i]===org[i]){
            // Add mark tag to the current letter in the original text to show user progress
            newHTML = newHTML +"<mark>"+org[i]+"</mark>";            }
        else{
            // If there's a mistake, alert user and delete the input so user can try again
            newHTML = cntq[currIndex];
            mistakes++;
            errorFound = true;
        }
    }
        
    // Check if there was a mistake
    if(errorFound){
        $(".oops").text("Oops! You made " + mistakes+ " mistakes.");
    }
        
    // complete the original sentence if the input is still unfinished with the rest of the org sentence
    if(i != org.length){
        for(;i<org.length;i++){
            newHTML+=org[i];
        }
    }// Check whether the sentence matches the original completely
    else if (newHTML === org){
        $(".success").show();
    }
        
    $(".orginal").html(newHTML);
    $("mark").attr("background-color='yellow'");
});
   
function getdate(){
    var today = new Date();
    //var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    if(s<10){
        s = "0"+s;
    }
    if (m < 10) {
        m = "0" + m;
    }
    $(".timer").text(m+" : "+s);
    $(".start").hide();
    $(".stop").show();
    setTimeout(function(){getdate()}, 500);
}

$(".start").on("click", getdate);

$(".stop").on("click", function() {
    $(".start").show();
});
    
}); // End ready function

My CSS code:

title h2 h4 {
    left: 50%;
    transform: translate(-50%,0);
    text-align: center;
    position: absolute;
    border-radius: 5px;
    box-shadow: 0px 8px 16px 0px;
}

body {
    left: 50%;
    transform: translate(-50%,0);
    text-align: center;
    position: absolute;
    border-radius: 5px;
}

ul .menu {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

li button {
    display: block;
    width: 60px;
}

mark {
  background-color: yellow;
  color: black;
}

input 
{
    display: block;
    width: 500px;
    height: 200px;
}

.under {
    display:inline-block;
}

#next {
    float: right;
    position: absolute;
}

#return {
    float: left;
    position: absolute;
}

p #msg {
    border-radius: 10px;
    padding: 20px;
    width: 500px;
    height: 50px;
}

.oops {
    border: 2px red
}

.success {
    border: 2px green;
}

#timer {
    right: 5%;
    text-align: center;
    position: absolute;
    border-radius: 5px;
    box-shadow: 0px 8px 16px 0px;
}

Reactjs/Redux – Objects are not valid as a React child

I am making a shopping cart – onClick I have redux adding items to cartItems array.

In the code below (increment reducer its the last one after add/remove) I am trying to get rid of duplicate values from the cartItems array, and display a total number of unique items in the cart with cartIcon: {value: 0} – which is by default 0 (before adding any items).


const initialState = {
    cartItems: [],
    cartQuantity: 0,
    cartIcon: {value: 0},
}


export const addToCartSlice = createSlice({
    name: 'cart',
    initialState,
    reducers: {
        
        add(state, action ) {

            const itemIndex = state.cartItems.findIndex(
                (props) => props.id === action.payload.id
                );
                if(itemIndex >= 0){
                    state.cartItems[itemIndex].cartQuantity += 1;
                } else {
                    const tempProduct = {...action.payload, cartQuantity: 1}
                    state.cartItems.push(tempProduct);

                }

            
        },
        remove(state, action) {
            const removeItem = state.cartItems.filter(
                (cartItem) => cartItem.id !== action.payload.id 
            
            );
            state.cartItems = removeItem;
        },


        increment: (state) => {
            const Items = state.cartItems.filter(
                (element, index) => state.cartItems.indexOf(element) === index);
                state.value = Items.length;
        }      // if i just do state.value += 1
               // then the value goes up by 1
               // but I want to display the amount of unique entries

    },

});

Here onClick I am pulling data from the item that was “added” to the cart and additionally trying to increment the cartIcon number by 1 (if the item hasn’t been yet added to the array cartItems). The problem could be here? Because the error mentions all the props and data I’m pulling to be rendered into the cart.

const dispatch = useDispatch()
const handleAddToCart = (props) => {
  dispatch(add(props));
};

  return (<>
                <div id={props.id} className='shopitem'>
                    <img src={props.url} />
                    <h2>{props.title}</h2>
                    <p className='boldprice'>${props.price}</p>
                    <button onClick={() => {
                    handleAddToCart(props);
                    dispatch(increment())
                  }}> ADD TO CART </button>
                </div>
        </>
  )
}

And here I am trying to display the amount of unique items to the shopping cart icon.

const count = useSelector((state) => state.cart.cartIcon.value)
{count}

For some reason I am getting this error. If I just do state.value += 1 it will add +1 to the shopping cart icon, however I only want to display +1 for each unique item.

“Uncaught Error: Objects are not valid as a React child (found: object with keys {id, title, price, url, cartQuantity}). If you meant to render a collection of children, use an array instead.”

Please help – I am relatively new to Javascript and programming overall.. I may be making a stupid mistake, so if something is clearly wrong.. then please let me know 🙂

Angular hot observables with RxJS: Changes on array are not emitted to subscribers

I have a small task board like trello with tasks to be done, doing and done. All the tasks are stored on 3 separate arrays in one service called TaskService. To show the task and change task state I have implemented angular’s cdk drag n drop.

My goal now is to subscribe to the the task arrays so when the array changes send the changes to an api. For now I’m just trying to console.log the events but I’m not understanding what’s happening it seemly to work but I can’t get the arrays updates.

This is my component controller:

doing: any[];

  constructor(private taskService: TaskService) {}

  ngOnInit(): void {
    this.getTodoTasks();
    // this.getDoingTasks();
    this.getDoneTasks();

    const obs$ = this.taskService.getDoing();

    obs$.subscribe({
      next: (data: any[]) => {
        this.doing = data;
        console.log(data);
      },
    });
  }

  todo: any[];
  // doing: Subscriber<any[]>;
  done: any[];
  newTaskText: string = '';

  isModalShown: boolean = false;

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer == event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

  newTask() {
    console.log(`Click Modal!`);
    this.isModalShown
      ? (this.isModalShown = false)
      : (this.isModalShown = true);
  }

  getTodoTasks() {
    this.taskService.getTodos().subscribe((data) => {
      this.todo = data;
      console.log(`Se ha añadido Tak a : Todo`);
    });
  }

This is my view:

<app-modal *ngIf="isModalShown" (close)="newTask()">
  <div class="modalContent">
    <textarea
      name=""
      id=""
      cols="30"
      rows="10"
      class="newTask"
      [(ngModel)]="newTaskText"
    ></textarea>
    <div class="modalButtons">
      <input
        type="button"
        value="Cancel"
        class="btn btn-secondary"
        (click)="cancelTask()"
      />
      <input type="button" value="Save" class="btn btn-primary" (click)="saveTask()" />
    </div>
  </div>
</app-modal>

<div class="container">
  <div class="list">
    <h2>TO DO</h2>
    <input type="button" value="Modal" (click)="newTask()" />
    <div
      class="tasks"
      cdkDropList
      #todoList="cdkDropList"
      [cdkDropListData]="todo"
      [cdkDropListConnectedTo]="[doingList, doneList]"
      (cdkDropListDropped)="drop($event)"
    >
      <div class="task" *ngFor="let item of todo" cdkDrag>{{ item }}</div>
    </div>
  </div>
  <div
    class="list"
    cdkDropList
    #doingList="cdkDropList"
    [cdkDropListData]="doing"
    [cdkDropListConnectedTo]="[doneList, todoList]"
    (cdkDropListDropped)="drop($event)"
  >
    <h2>DOING</h2>
    <div class="tasks">
      <div class="task" *ngFor="let item of doing" cdkDrag>{{ item }}</div>
    </div>
  </div>
  <div
    class="list"
    cdkDropList
    #doneList="cdkDropList"
    [cdkDropListData]="done"
    [cdkDropListConnectedTo]="[doingList, todoList]"
    (cdkDropListDropped)="drop($event)"
  >
    <h2>DONE</h2>
    <div class="tasks">
      <div class="task" *ngFor="let item of done" cdkDrag>{{ item }}</div>
    </div>
  </div>
</div>

And my service:

constructor() {}

  todo = ['task 1', 'task 2', 'task 3'];
  doing = [];
  done = [];

  getTodos(): Observable<any[]> {
    return of(this.todo);
  }

  getDoing(): Observable<any[]> {
    return new Observable((subscriber) => {
      subscriber.next();
    })
  }

  getDone(): Observable<any[]> {
    return of(this.done);
  }

How to create a element and then make that element draggable across the page?

I need to create a element with documet.createelement and make it draggable. Here is the code

    var files= document.getElementById('texttouse').value;
    let textadder=document.createElement("p");
 let t= document.createTextNode(files);
 textadder.appendChild(t);
   document.getElementById('gallery').appendChild(textadder);
     for (i = 0 ; i < textadder.length; i++) {
    textaddder[i].onclick = function() {
      var div = this.parentElement;
     
    }
  }             
  
}

But I can’t figure out how to make it draggable.Please help me.