Map function stores the value of the last object in the array to all values

I am getting data from Firestore and using the map function to display all of that data. I am sending one of the arguments within a URL to get an image. I am sending a cryptocurrency pair in a URL to get an image in response. I am also displaying the pair in the table. However, when I send the same symbol in the map function, all of my pairs get the same pair sent in the url, the last pair of the data.
To simplify the issue:

Steps:

  1. Map function to display data
  2. Pair attribute is sent in the link to get image with every map function (click button to see image)
  3. Pair function also displayed in the table

Result:

  1. The pair in the table is unique and displaying correctly
  2. All urls in the map function get the same pair, the pair of the last object.

Code snippet

 {data.map((trade) => (
            <tr>
              <td>
                <div style={{ display: "flex" }}>
                  <img
                    src={trade.image}
                    style={{
                      width: "30px",
                      height: "30px",
                      marginTop: "13px",
                      marginRight: "5px",
                    }}
                    alt="btc"
                  />
                  <p className="coin-name">{trade.symbol.baseAsset}</p>
                </div>
              </td>
              <td>{trade.symbol.symbol}</td>
              <td>{trade.qty}</td>

              <td>{Math.round(trade.multiplier)}x avg volume</td>

              <td>{trade.price}</td>
              <td>{trade.exchangeDetails.name.toUpperCase()}</td>
              <td>{Math.round(trade.tradeValue * 1000) / 1000}</td>
              <td>
                <div>
                  <Button
                    onClick={handleOpen}
                    style={{ backgroundColor: "#142F37 ", color: "white" }}
                  >
                    View Graph
                  </Button>
                  <Modal
                    open={open}
                    onClose={handleClose}
                    aria-labelledby="modal-modal-title"
                    aria-describedby="modal-modal-description"
                  >
                    <Box sx={style}>
                      <img
                        src={`https://2zpbbz.chart-img.com/v1/tradingview/advanced-chart?symbol=${trade.symbol.symbol}`}
                        alt="No graph for this pair"
                        style={{ width: "500px" }}
                      />
                    </Box>
                  </Modal>
                </div>
              </td>
            </tr>
          ))}

UI

Get image as array buffer and display

I have written a file to an array buffer and stored on IPFS. At another point I wish to pull this buffer from IPFS and have the image displayed on the page. I am struggling with this as the blob does not seem to be located.

Adding photo as array buffer:

// Read photo
let photoFile = e.target.photo.files[0];
let reader = new window.FileReader();
let that = this;
reader.onloadend = function (e) {
  let res = reader.result;
  that.setState({photoString: res});
}

if (photoFile) {
  await reader.readAsArrayBuffer(photoFile);
}

// Add photo to IPFS
await ipfs.add(photoFile).then(async (result, error) => {
  let photoHash = result.path;
  if (error) {
    console.error(error)
  }
});

When trying to get from IPFS and display:

let holderPhoto = await $.get(`https://ipfs.infura.io/ipfs/${IPFSPhotoHash}`);
    const blob = new Blob( [ holderPhoto ] );
    const url = URL.createObjectURL( blob );
    const img = document.getElementById( 'photo' );
    img.image = require(url);
    img.onload = e => URL.revokeObjectURL( url );


<CardMedia id="photo" component="img" height="420" alt="Licence Photo"/>

Error:
components sync:2 Uncaught (in promise) Error: Cannot find module ‘blob:http://localhost:3000/ff4f9e6a-7fae-4cc2-93b3-a6234719c87f’

How to remove any text inside parentheses in a text node in a dynamically created iframe list called in a Bootstrap modal?

So I have a bootstrap modal that calls a .html file in an iframe (my .html file on the same domain) that always produces a different result which is what I need. However the contents generated in the list always creates a text node inside each li of the list containing text wrapped in parentheses. I want to keep all the text that is not inside the parentheses, but remove ANY text that appears inside parentheses ().

So my modal is called here:

<div class="modal-body"><iframe id="researchiframe" name="display-frame" style="width:100%;height:600px;"></iframe></div>

Then it loads my .html file into the iframe and displays the information I want in a list.

<div class="row">
<div class="col-lg-8 offset-lg-3" id="research_result">
<h4 id="research_result_title">Details</h4>

<center>
<ul id="research_result_details" style="padding:0px">
// text I want to remove appears in here //
</ul>
</center>

The list that it generates comes out like this…

<li><h5 class="title" style="display:inline-block;">My Title</h5>:These are the results I want to keep (Theses are the results I want to remove)</li>

So inside the li it creates text that I want to keep, and also text inside (parentheses) I want to remove.

Any help with this is greatly appreciated.

Shouldn’t await and then behave the same way?

Until today, I thought that await and then were 2 different ways to handle promises results.

I used nodemailer.createTestAccount to do some e2e testing and I stumbled in this counter-intuitive behaviour.

This is what the below code does:

  • I have 2 test functions: testA and testB (they should do the same exact thing)
  • I call the 2 functions and I get some output
  • testA seems to work properly returning different value every call
  • testB seems to return always the same value
const nodemailer = require("nodemailer");

const testA = async () => {
  nodemailer.createTestAccount().then(account => { console.log("testA:", account.user) })
  nodemailer.createTestAccount().then(account => { console.log("testA:", account.user) })
  nodemailer.createTestAccount().then(account => { console.log("testA:", account.user) })
}

const testB = async () => {
  const test1 = await nodemailer.createTestAccount()
  console.log("testB:", test1.user)

  const test2 = await nodemailer.createTestAccount()
  console.log("testB:", test2.user)

  const test3 = await nodemailer.createTestAccount()
  console.log("testB:", test3.user)
}

testA()
testB()

The result (hand sorted for readability):

testA: [email protected]
testA: [email protected]
testA: [email protected]

testB: [email protected]
testB: [email protected]
testB: [email protected]

Can someone explain me why is this happening?

CAPTCHA Error: POST does not match SESSION key

I am following a CAPTCHA tutorial on TutsPlus.com and I keep getting the ‘Incorrect Captcha message, meaning my $_POST user input does not match the stored $_SESSION string.

Upon further probing, I tried to echo $_SESSION[‘captcha_text’] and I got the error: ‘Undefined array key.’ As if I hadn’t stored the solution at all.

I have looked at my logs and used developer tools but the only other error is ‘Uncaught TypeError: Cannot set properties of null (setting ‘onclick’)’ which is probably why my javascript won’t run either.

Here is my captcha.php script:

// Store all characters we wish to use to generate CAPTCHA string. Only capital letters to avoid confusion.
$permitted_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

/**
 * Generate cryptographically secure random numbers using random_int() or non-secure random numbers using mt_rand()
 * @param string permitted chars used in CAPTCHA
 * @param int length of random string, default = 5
 * @param bool secure or not, default is secure
 * @return string random string
 */
function secure_generate_string($input, $strength = 5, $secure = TRUE) {
    $input_length = strlen($input);
    $random_string = '';
    for($i = 0; $i < $strength; $i++) {
        if($secure) {
            $random_character = $input[random_int(0, $input_length - 1)];
        } else {
            $random_character = $input[mt_rand(0, $input_length - 1)];
        }
        $random_string .= $random_character;
    }

    return $random_string;
}

// Render the CAPTCHA background. Image will be 200x50px in size and use five different colors for background.
$image = imagecreatetruecolor(200, 50);

imageantialias($image, true);

$colors = [];

// Generate random colors
$red = rand(125, 175);
$green = rand(125, 175);
$blue = rand(125, 175);

// Generate progressively darker shades of original colors. Store colors in array with darkest color as last element. 
for($i = 0; $i < 5; $i++) {
    $colors[] = imagecolorallocate($image, $red - 20*$i, $green - 20*$i, $blue - 20*$i);
}

// Lightest color used to fill whole background of image.
imagefill($image, 0, 0, $colors[0]);

// Draw rectangles at random locations on original image. Thickness of rectangles varies between 2 and 10, while color chosen randomly from last four values of $colors array
for($i = 0; $i < 10; $i++) {
    imagesetthickness($image, rand(2, 10));
    $rect_color = $colors[rand(1,4)];
    imagerectangle($image, rand(-10, 190), rand(-10, 10), rand(-10, 190), rand(40, 60), $rect_color);
}

// Letters are mix of black and white 
$black = imagecolorallocate($image, 0, 0, 0);
$white = imagecolorallocate($image, 255, 255, 255);
$textcolors = [$black, $white];

// Fonts downloaded from Google to get variation in characters
$fonts = [FONT . 'Acme' . DS . 'Acme-Regular.ttf', FONT . 'Ubuntu' . DS . 'Ubuntu-Regular.ttf', FONT . 'Merriweather' . DS . 'Merriweather-Regular.ttf', FONT . 'Gideon_Roman' . DS . 'GideonRoman-Regular.ttf', FONT . 'Yeseva_One' . DS . 'YesevaOne-Regular.ttf'];

$string_length = 6;
$captcha_string = secure_generate_string($permitted_chars, $string_length);

$_SESSION['captcha_text'] = $captcha_string;

// Padding 15px on both sides of image. Leftover space (170px) is divided equally among all CAPTCHA letters
for($i = 0; $i < $string_length; $i++) {
    $letter_space = 170/$string_length;
    $initial = 15;

    imagettftext($image, 20, rand(-15, 15), $initial + $i*$letter_space, rand(20, 40), $textcolors[rand(0, 1)], $fonts[array_rand($fonts)], $captcha_string[$i]);
}

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

Here is my captcha.js script:

var refreshButton = document.querySelector('.refresh-captcha');

refreshButton.onclick = function() {
    document.querySelector('.captcha-image').src = 'captcha.php?' + Date.now();
}

My login.php where the captcha is displayed:


        <div class='captcha-container'>
            <label for='captcha'>Please Enter the Captcha Text</label>
            <br>
            <img src='<?php echo FUNCT_URL;?>captcha.php' class='captcha-image' alt='captcha'>
            
            <i class='fa-solid fa-arrow-rotate-right re
            fresh-captcha'></i>
            <br>
            <input class='input-field' type='text' id='captcha' name='captcha_challenge' pattern='[A-Z]{6}' required>
        </div>

        <button class='submit-btn' type='submit' name='loginSubmit'>Login</button>

        <!--this custom_captcha id is used in js file,you can change in js and html both-->
        <div id='custom_captcha'></div>

And finally, user_account where the login is processed:

if(isset($_POST['captcha_challenge']) && $_POST['captcha_challenge'] == $_SESSION['captcha_text']) {

Why does my table slowly recede in R Markdown when using the DT scrollResize plugin?

I ran the following code in R markdown. The table starts full size but then slowly recedes without me doing anything. Within a few seconds you can’t see any rows nor can you do anything to view them. I followed the format as shown here and there did not appear to be any additional information on the DT package website.

I’m using DT version 0.20, R version 4.1.2 and RStudio 2022.02.0+443.

    ---
    title: "scrollResize Not Working"
    output: html_document
    ---

    ```{r}

    library(DT)

    datatable(iris, plugins = "scrollResize",
          
          options = list(scrollResize = TRUE,
                         paging = FALSE,
                         scrollY = '300px',
                         scrollCollapse = TRUE))

    ```

How to use Cleanup in useEffect

I have the below code, where it pull all data from server as API

  export const apiExpenses = () => {

    //Get All Expenses, Realtime
    const { data: tableDataExpenses, error, mutate } = useSWR('/api/expenses/datatable', () =>
      axios
          .get('/api/expenses/datatable')
          .then(res => res.data),        
    )

    return {
        tableDataExpenses,
      }

  }

And using the output of that API in another component with useEffect

const { tableDataExpenses } = apiExpenses();
const [expenses, setExpenses] = useState([]);

useEffect(() => {
    setExpenses(tableDataExpenses.data);

    return () => {
      setExpenses([]);
    };
  }, [tableDataExpenses]);

But I am ending in below errors,

 Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

And because of this, I can’t get the value of tableDataExpenses

If I remove setExpenses from useEffect there are no errors and again if I write setExpenses it loads data.

But again in the next render, it fails with error.

So How can I prevent this error with the cleanup function?

I don’t understand why my code isn’t working [duplicate]

I have just started learning javascript and have made a small little program to create an alert when a button is clicked, yet it doesn’t work and I’m not sure why.

Here is my code:

<html>
<head>
    <style>
        body {
            background-color: grey;
            color: white;
        }
    </style>
    <script>
        const some_action = () => {
            window.alert("hi")
        }
        document.getElementById("btn").addEventListener("click", some_action)
    </script>
</head>
<body>
    <p>
        <button id="btn">click me</button>
    </p>
</body>

</html>

Writing image data to filesystem FS Electron Node.js

So I am trying to download an image. But everything I try it keeps giving me the same kind of error. Anyone got the same problem or solution why fs won’t work in fs.

Versions:
Node: 16.14.0
npm: 8.2.0
Electron: ^16.0.7

Current error:d.writeFile is not a function

My code:

// dependecies:
const axios = require('axios');
const fs = require('fs');


        image.promise = new Promise((resolve, reject) => {
          const formData = new FormData();
          formData.append('files', file);
          axios
            .post('http://api.resmush.it/', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
            .then(response => {
              const url = response.data.dest;
              function downloadFile() {
                axios
                  .get(url)
                  .then(response => {
                    console.log(response)
                    console.log(response.data)
                    fs.writeFile("/tmp/test", "Hey there!", function(err) {
                          if(err) {
                              return console.log(err);
                          }
                          console.log("The file was saved!");
                      });
                      fs.writeFileSync('/tmp/test-sync', 'Hey there!');

                    })
                  // .then(response => resolve(response))
                  // .catch(() => reject());
                  .catch(reject => {console.log(reject)})
              }
              downloadFile();
            })
            .catch(() => reject());
        })

Allow curly brackets in url validation

I’m working with Yup and would like it to match urls that use curly brackets in the query string in cases like these (currently it doesn’t match as a valid url):

https://blah.blahblah.net/register/{0}
https://blah.blahblah.net/provider/tool.php?id={0}

I know that I need to have a custom regex match for this.

It would be great if the solution could be “built” on top of current Yup url regex match case which is:
/^((https?|ftp):)?//(((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:)*@)?(((d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]))|((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).?)(:d*)?)(/((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)+(/(([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)*)*)?)?(?((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)|[uE000-uF8FF]|/|?)*)?(#((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)|/|?)*)?$/i;

Calculate hours and minutes between two values that contains 4 digits with Javascript [closed]

I have three fields in an eForm called Start, Stop and Total. In the field start and stop i want to enter four digits (ex 1100). I want to calculate the difference between the two values an that sum should show up in Total field as HH.mm .

So:

Start: 1030
Stop: 1200

Total 1.30

I have tried some diifrent scripts but i end up getting for example this problem:

If i a enter 1000 and 1100 it gets a total of 1.00 (CORRECT)
If i a enter 1000 and 1030 it gets a total of .30 (CORRECT but i would like 0.30)
If i a enter 0930 and 1000 it gets a total of .70 (WRONG, it should give .30 or as i wish 0.30)

Can it be that i need to convert the two first digits to hours and the last two to seconds?
How do i do that?

Best regards
Daniel

White screen on initial load when updating my progressive web app

I’m using create react app and recently added a service worker so as to make it a PWA. It was very easy and seemed to work great. However, now whenever I build a new version of my app I get the following error on the initial load of the website:

enter image description here

I believe the problem is that when I build my app the file names are randomly generated and don’t match the old ones. The PWA is using the old index.html trying to fetch the old files which don’t exist anymore.

What is the best way of fixing this?

Reuse react individual components in JSP

I have an existing application that’s written on core java, i mean no java framework has been used. I have another frontend application that’s built on react. Is it possible to import any react component for e.g menu. Instead of creating a new menu, can i reuse component that’s part of another application?

Any help would be appreciated!

Repeater doesn’t work how i wanted to work, react

I am working in wordpress and trying to create a custom gutenberg block with react. I am using the and that is working fine. I have the following fields that requires input like text or a image or a star rating:

Name:,
Workfunction:,
Image:,
Rating:,
Testimonial:

But the output in the editor field isn’t working properly as i wanted. So what is happening:

I put the info in the the info should be displayed in the editor and that is working. So if i add 1 block it’s working like a charm, so you get this:

Name: ben
Workfunction: DEV
Image: media
Rating: 5 stars (i choose 5 stars)
Testimonial: story

When i add a second the following is happening based on the fields i fill in.

Name: ben
Name: test
Workfunction: DEV
Workfunction: DEV
Image: media
Image: media
Rating: i choose 5 stars again, so the output is 10
Rating: i choose 5 stars again, so the output is 10
Testimonial: story
Testimonial: story

Name: ben
Name: test
Workfunction: DEV
Workfunction: DEV
Image: media
Image: media
Rating: i choose 5 stars again, so the output is 10
Rating: i choose 5 stars again, so the output is 10
Testimonial: story
Testimonial: story

It seems te duplicate and add to the same fields. What i am trying to get is the following:

Name: ben
Workfunction: DEV
Image: media
Rating: 5
Testimonial: story

Name: test
Workfunction: DEV
Image: media
Rating: 5
Testimonial: story

This is all happening in the return area and above i think. Could some on explain to me how to resolve this problem and what i have done wrong?

Here is mine code for a better understanding:

/**
 * BLOCK: project-drie
 *
 * Registering a basic block with Gutenberg.
 * Simple block, renders and saves the same content without any interactivity.
 */

//  Import CSS.
import './editor.scss';
import './style.scss';
import React from 'react';
import ReactDom from 'react-dom';
import { FaStar } from "react-icons/fa";
import {Helmet} from "react-helmet";



// import components
import { useBlockProps, RichText, InnerBlocks, MediaUpload, InspectorControls, MediaUploadCheck } from '@wordpress/block-editor';


const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
const { Button, IconButton, PanelBody, TextareaControl, TextControl, SelectControl, CustomSelectControl } = wp.components;
const { Fragment, useState } = wp.element;


/**
 * Register: aa Gutenberg Block.
 *
 * Registers a new block provided a unique name and an object defining its
 * behavior. Once registered, the block is made editor as an option to any
 * editor interface where blocks are implemented.
 *
 * @link https://wordpress.org/gutenberg/handbook/block-api/
 * @param  {string}   name     Block name.
 * @param  {Object}   settings Block settings.
 * @return {?WPBlock}          The block, if it has been successfully
 *                             registered; otherwise `undefined`.
 */


registerBlockType( 'cgb/block-project-drie-testimonials', {
    title: __( 'project-drie - Testimonials' ), // Block title.
    icon: 'shield',
    category: 'project drie',
  supports: {
        align: true,
    },
    keywords: [
        __( 'project-drie — CGB testimonials' ),
        __( 'testimonials' ),
    __( 'testimonial' ),
    ],
  attributes: {
    title: {
      type: 'string',
      source: 'text',
      selector: 'figcaption',
    },
    subtitle: {
      type: 'string',
      source: 'text',
      selector: 'figcaption',
    },
    testimonial: {
            type: 'array',
            default: [],
        },
  },

    /**
     * The edit function describes the structure of your block in the context of the editor.
     * This represents what the editor will render when the block is used.
     *
     * The "edit" property must be a valid function.
     *
     * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
     *
     * @param {Object} props Props.
     * @returns {Mixed} JSX Component.
     */


   edit: props => {
    const { attributes: {title, subtitle, testimonial, media, selectcontrol}, className, setAttributes } = props;
    const onChangeTitle = title => { setAttributes ( { title } ) };
    const onChangeSubtitle = subtitle => { setAttributes ( { subtitle } ) };
    const onSelectImage = ( media ) => { setAttributes( { media: media} );};
    const handleAddTestimonial = () => {
            const testimonial = [ ...props.attributes.testimonial ];
            testimonial.push( {
                author: '',
        position: '',
        testimonial: '',
        media: '',
        selectcontrol: '',
            } );
            props.setAttributes( { testimonial } );
        };

    const handleRemoveTestimonial = ( index ) => {
            const testimonial = [ ...props.attributes.testimonial ];
            testimonial.splice( index, 1 );
            props.setAttributes( { testimonial } );
        };

    const handleTestimonialChange = ( key, value, index  ) => {
            const testimonial = [ ...props.attributes.testimonial ];
            testimonial[ index ][key] = value;
            props.setAttributes( { testimonial } );
        };


    let testimonialFields,
            testimonialDisplay;

    let authorFields,
            authorDisplay;

    let positionFields,
            positionDisplay;

    let mediaFields,
            mediaDisplay;

    let selectcontrolFields,
            selectcontrolDisplay;


        if ( props.attributes.testimonial.length ) {
            testimonialFields = props.attributes.testimonial.map( ( testimonial, index ) => {

                return <Fragment key={ index }>
            <TextControl
                        className="author__react__testimonials"
                        placeholder="Add testimonial."
                        value={ testimonial.testimonial }
                        onChange={ ( value ) => handleTestimonialChange('testimonial', value, index ) }
                    />

            <TextControl
                        className="author__react__name"
                        placeholder="Add Author Name. Example: Ben"
                        value={ testimonial.author }
                        onChange={ ( value ) => handleTestimonialChange('author', value, index ) }
                    />

            <TextControl
                        className="author__react__name"
                        placeholder="Add Function. Example: CEO."
                        value={ testimonial.position }
                        onChange={ ( value ) => handleTestimonialChange('position', value, index ) }
                    />
            <MediaUpload
              onSelect={ (value) => handleTestimonialChange('media', value, index ) }
              allowedTypes="image"
              value={ testimonial.media.id }
              render={ ( { open } ) =>  (
                  <Button className={ testimonial.media.length > 0 ? 'image-button' : 'button button-large' } onClick={ open }>
                      { testimonial.media.length > 0 ? __( 'Upload Image', 'gutenberg-examples' ) : <img src={ testimonial.media.url } alt={ __( 'Upload Recipe Image', 'gutenberg-examples' ) } />  }
                  </Button>

              )   }
            />
            <SelectControl

              label={ __( 'Press ctrl to multiple stars:' ) }
              value={ testimonial.selectcontrol } // e.g: value = [ 'a', 'c' ]
              onChange={ (value) => handleTestimonialChange('selectcontrol', value, index ) }
              options={ [
                  { value: null, label: 'Select a Star', disabled: false },
                  { value: 'star' ,  label: 'Add 1 star' },
                  { value: 'star2', label: 'Add 2 stars' },
                  { value: 'star3', label: 'Add 3 stars' },
                  { value: 'star4', label: 'Add 4 stars' },
                  { value: 'star5', label: 'Add 5 stars' },
              ] }
            />

                    <IconButton
                        className="testimonials__remove__react__testimonial"
                        icon="no-alt"
                        label="Delete location"
                        onClick={ () => handleRemoveTestimonial( index ) }
                    />
                </Fragment>;
            } );

        testimonialDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
                return <p key={ index }>{ testimonial.testimonial  } </p>;
            } );

            authorDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
                return <p key={ index }>{ testimonial.author  } </p>;
            } );

        positionDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
                return <p key={ index }>{testimonial.position}</p>;
            } );

        mediaDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
          return <img key={index} src={testimonial.media.url} alt={testimonial.media.alt} />
            } );

        selectcontrolDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
          if (testimonial.selectcontrol == 'star') {
            return  (testimonial.selectcontrol == 'star') ? <span><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
          } else if (testimonial.selectcontrol == 'star2') {
            return  (testimonial.selectcontrol == 'star2') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
          } else if (testimonial.selectcontrol == 'star3') {
            return  (testimonial.selectcontrol == 'star3') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
          } else if (testimonial.selectcontrol == 'star4') {
            return  (testimonial.selectcontrol == 'star4') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span>: testimonial.selectcontrol;
          } else if (testimonial.selectcontrol == 'star5') {
            return  (testimonial.selectcontrol == 'star5') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
          }
        } );
        }

        return [
      <div className={ className }>
            <InspectorControls key="1">
                <PanelBody title={ __( 'Testimonial' ) }>
                    { testimonialFields }
                    <Button
                        isDefault
                        onClick={ handleAddTestimonial.bind( this ) }
                    >
                        { __( 'Add Testimonials' ) }
                    </Button>
                </PanelBody>
            </InspectorControls>
            <div key="2" className={ props.className }>
          <div className="wp-block-cgb-block-project-drie-testimonial-info">
            <div className="wp-block-cgb-block-project-drie-testimonial-title">
              <h2>{ __('Title', 'cgb')}</h2>
                <RichText
                  tagName="div"
                  className="wp-block-cgb-block-project-drie-testimonial-titles"
                  placeholder={ __('Add your title here', 'cgb')}
                  onChange={ onChangeTitle}
                  value={ title }
                />
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-subtext">
            <h2>{ __('Sub-Text', 'cgb')}</h2>
              <RichText
                tagName="p"
                className="wp-block-cgb-block-project-drie-testimonial-subtexts"
                value={ subtitle }
                onChange={ onChangeSubtitle }
                placeholder={ __('Add your sub-text here', 'cgb')}
              />
            </div>
          </div>
          <div className="wp-block-cgb-block-project-drie-testimonial-repeater">
            <div className="wp-block-cgb-block-project-drie-testimonial-repeater-title">
                    <h2>Employee</h2>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-skillname">
              <h3>Author Name:</h3>
              <span>{ authorDisplay }</span>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-percentage">
              <h3>workFunction:</h3>
              <span>{ positionDisplay }</span>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-bgimages">
              <div className="wp-block-cgb-block-project-drie-testimonial-bgimage">
                <h2>Author Image</h2>
                {mediaDisplay}
              </div>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-ratings">
              <div className="wp-block-cgb-block-project-drie-testimonial-rating">
                <h2>Rating</h2>
                {selectcontrolDisplay}
              </div>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-testimonials">
              <div className="wp-block-cgb-block-project-drie-testimonial-testimonial">
                <h2>Review</h2>
                {testimonialDisplay}
              </div>
            </div>
          </div>
        </div>
      </div>

        ];

    },

    /**
     * The save function defines the way in which the different attributes should be combined
     * into the final markup, which is then serialized by Gutenberg into post_content.
     *
     * The "save" property must be specified and must be a valid function.
     *
     * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
     *
     * @param {Object} props Props.
     * @returns {Mixed} JSX Frontend HTML.
     */
    save: ( props ) => {
    const {attributes: { title } } = props;
    const {attributes: { subtitle } } = props;
    const {attributes: { media} } = props;
    const {attributes: { testimonial } } = props;
    const {attributes: { selectcontrol } } = props;

    const selectcontrolDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
      if (testimonial.selectcontrol == 'star') {
        return  (testimonial.selectcontrol == 'star') ? <span><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
      } else if (testimonial.selectcontrol == 'star2') {
        return  (testimonial.selectcontrol == 'star2') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
      } else if (testimonial.selectcontrol == 'star3') {
        return  (testimonial.selectcontrol == 'star3') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
      } else if (testimonial.selectcontrol == 'star4') {
        return  (testimonial.selectcontrol == 'star4') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span>: testimonial.selectcontrol;
      } else if (testimonial.selectcontrol == 'star5') {
        return  (testimonial.selectcontrol == 'star5') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
      }
    } );






    // const skillnameFields = props.attributes.skillname.map( ( skillname, index ) => {
        //  return <p key={ index }>{ skillname.skill } { skillname.percentage }</p>;
        // } );

    return (
      <section className="testimonial">
        <Helmet>
          <script type="text/javascript" src="//cdn.jsdelivr.net/gh/kenwheeler/[email protected]/slick/slick.min.js"></script>
        </Helmet>
        <div className="container testimonial__container">
          <div className="row testimonial__row">
            <div className="testimonial__info">
              <div className="testimonial__subtext">
                <span>{ subtitle }</span>
              </div>
              <div className="testimonial__title">
                <h2>{ title }</h2>
              </div>
            </div>
            <div className="items testimonial__testimonials">
              {testimonial.map((field, i) => (
              <div className="testimonial__testimonial">
                <div className="testimonial__card" key={ i }>
                  <div className="testimonial__image">
                    <img src={field.media.url} />
                  </div>
                  <div className="testimonial__review">
                    <p>{field.testimonial}</p>
                  </div>
                  <div className="testimonial__stars">
                    <span>{selectcontrolDisplay}</span>
                  </div>
                  <div className="testimonial__author">
                    <div className="testimonial__name">
                      <span>{ field.author }</span>
                    </div>
                    <div className="testimonial__function">
                      <span>{ field.position }</span>
                    </div>
                  </div>
                </div>
              </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    );
    },
 } );

Draw line don’t work fine when local storage is used in js

I am storing user locations . when user has internet connection it goes directly to the server and store in database if user is not having internet it gets stored in localstorage and after having internet data uploaded on server.

It works fine with having internet but when i store in localstorage it draws weired lines on map.

enter image description here

code

 saveLocation(location){
      let data = {

          longitude: location?.longitude,
          latitude:location?.latitude,
          staff_id:TokenService.getUserInfo().id,
          work_order_id: TokenService.getWorkOrder(),
          deal_id: TokenService.getDealId()
        };
        let url = `api/save-location`;
     var offline_location = { url: url, method: "post", data: data };

       let options = {
        url: process.env.VUE_APP_ROOT_API+url,
        headers: {
            Authorization: `Bearer ${TokenService.getToken()}`
          },
        params: data,
      };
if(this.networkStatus){

   Http.post(options)
}else{
        var today = new Date();
        var time = today.getHours() + ":" + today.getMinutes()+ 
        ":"+today.getSeconds();
        this.$localStorage.set(`save_current_location_store_${time}`,JSON.stringify(offline_location));
      
     


    }
    },