React JS: Function isn’t returning anything

I have a JS function in my code that is supposed to return a React Component for Each element of my split string, but for some reason, when I call it on my main “return()”, the function isn’t returning anything. I tried to put the function directly inside of the return(), but the same happened. That never happened to me before and I have no idea of what it is.

Here is my code:

import React from 'react';

import DatabaseLiLine from './DatabaseLiLine';

const DatabaseLiSection = ({ className, children, classId }) => {
    const example = "Use,This,As,An,Example";
    const splitLiTitles = example.split(",");

    const returnLines = () => {
        splitLiTitles.forEach(element => {
            return(
                <DatabaseLiLine>
                    {element}
                </DatabaseLiLine>
            );
        })
    }
    return (
        <li className={className}>
            <a href="/">{children}</a>
            <div id={classId} className="consult_box">
                {returnLines()}
            </div>
        </li>
    );
}

export default DatabaseLiSection;

Google Apps Script add month to a date until specific date is reached

I have the following code using Google Apps Script, but when I log it out I get the following results. I want GAS to log the next month and stop once it gets to “lastDateofYear “. For whatever reason, the year doesn’t change in my results, it just keeps repeating the current year. Please help.

var thisDate = "Mon Dec 20 00:00:00 GMT-06:00 2021";
var nextYear = Number(currentYear)+1;
var lastDateofYear = new Date("12-31-"+nextYear);

  for(var i=thisDate; i <= lastDateofYear; ){  
    var currentiDate = new Date(i);     
    var month = currentiDate.getMonth()+1;
    i.setMonth((month) % 12);
    i.setDate(currentiDate.getDate());
    Logger.log(currentiDate);
  }

RESULTS:

Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021
Thu May 20 00:00:00 GMT-05:00 2021
Sun Jun 20 00:00:00 GMT-05:00 2021
Tue Jul 20 00:00:00 GMT-05:00 2021
Fri Aug 20 00:00:00 GMT-05:00 2021
Mon Sep 20 00:00:00 GMT-05:00 2021
Wed Oct 20 00:00:00 GMT-05:00 2021
Sat Nov 20 00:00:00 GMT-06:00 2021
Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021

My DragTarget only receives the image that is listed first. How do I change this?

Both Images are intended to be dragged into the leftbox div. when you drag the blue image, which is listed above the orange image. It successfully drops into the leftbox. When you drag the orange image to the droptarget the blue image replaces it once dropped. This is because it is listed above the orange image. I tested this out by swapping the code orders. Putting the orange image first. And the orange image was then the only recipient of the dropping. Any help is appreciated.

function allowdrag(e) {
  e.preventDefault();
}

function Drop(e) {
  e.preventDefault();
  var texts = e.dataTransfer.getData('image/png')
  var data = document.getElementById(texts);
  e.target.appendChild(data)
}

function drog(e) {
  e.dataTransfer.setData('image/png', e.target.id)
}
#leftbox {
  width: 20%;
  height: 175px;
  border: 5px solid grey;
  border-radius: 0px;
  padding: 0px;
  margin: 75px 15px 0px 100px;
  display: inline-block;
  background-color: white;
  position: relative;
}

#image1 {
  height: 175px;
  width: 138px;
  display: table;
  margin-bottom: 75px;
  display: inline-block
}

#reset {
  height: 0;
  width: 21%;
  padding-bottom: 18%;
  position: absolute;
  right: 0px;
  background-image: url(https://win-conditions.com/wp-content/uploads/2021/12/download-1.png);
  background-size: 100%;
  background-repeat: no-repeat;
}
<div id="leftbox" ondrop="Drop(event)" ondragover="allowdrag(event)">
  <button id="reset" type="button"></button>
</div>

<div id="image">
  <img id="image1" src="https://win-conditions.com/wp-content/uploads/2021/11/electrospirit.png" draggable="true" ondragstart="drog(event)">
  <img id="image1" src="https://win-conditions.com/wp-content/uploads/2021/11/fire_spirits-1.png" draggable="true" ondragstart="drog(event)">
</div>

JSFiddle: https://jsfiddle.net/0h7c45kj/1/

service-worker.js catch updatefound before running other custom functions

Is there a way to check if the service worker found an update before loading custom functions?

i have this function which is working, but it runs the custom functions twice, and seems very untidy..

I’m looking for a way to only run the custom functions once, and not when an update was found and installed. When an update is found, the user || the page will reload automatically and then the custom functions can run normally..

I added the reg.events in this function to determine where to place my custom functions. I hope this question is understandable..

function installApp(path, scope) {
if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register(path, {
            scope: scope
        }).then((reg) => {  
       // event listener to catch the prompt if any and store in
      // an instance for later use with add to homescreen() function.
       getPrompt(); 

       // this is a custom alert type notification      
       makeProgress('System','is ok'); 
                    
      /* THIS IS THE UPDATE FOUND FUNCTION */

        reg.onupdatefound = function() {
    var installingWorker = reg.installing;
    installingWorker.onstatechange = function() {
      switch (installingWorker.state) {
        case 'installed':
          if (navigator.serviceWorker.controller) {
     // the _clear() function removes items from the locaforage db to 
    // force the app to not auto login, but let the user
    // login again to refresh any data when the page reloads
                _clear('uuid');
                _clear('user');
                _clear('token');
                makeProgress('new version','reload app');
          } else {
           // removes any custom notifications
                    clearProgress(); 
            //just go into the app because everything is loaded.
            //We dont need to reinstall the 
            //homescreen or listen for the homescreen because this
           //is an update and the homescreen should already be installed?
               enterApp(); 
          }
          break;
        case 'redundant':
          // removes any custom notifications cause
          //the install is complete
            clearProgress();
               enterApp(); 
          console.log('The installing service worker became redundant.');
          break;
      }
    };
            return;
  };
                         


                  /** Here is the events that fire during the install
                 //  process and where i am currently stuck **/
  
    if (reg.installing) {
       makeProgress('updating','files');
    /* THE SERVICE WORKER IS DOWNLOADING THE CACHE FROM THE SERVER */
    } else if (reg.waiting) {

    /* what message here ?*/
    /* as far as i can tell, THE SERVICE WORKER IS WAITING FOR 
    *//*PREVIOUS SERVICE WORKER TO BEREFRESHED SO A RELOAD */
    /*UI SHOULD COME HERE??*/

    } else if (reg.active) {
    /* what message here ?*/
    /* IS THIS THE BEST PLACE TO RUN THE BELOW CUSTOM
    *//*FUNCTIONS?? WILL //THEY ALWAYS FIRE */
    }
                    


/** AT WHICH OF THE EVENTS ABOVE WILL I ADD THE FUNCTIONS FROM HERE **/

                requestWakeLock();  
       const browserFeatures = detectFeatures(reg);
               setCompatibilityArray(browserFeatures);
         
localforage.ready().then(function() {
                localforage.getItem('homescreen').then(function (value) {
               if(value != 1){           
    if (platform == 'iPhone' || platform == 'iPad') {
installHome();                                      
                                    } else {
     makeProgress('waiting', 'prompt');  
                         waitPrompt();
                         }
                         return;
               } else {
               enterApp();
                         return;        
               }
                         
    }).catch(function (err) {
    alertIt('something went wrong. Please refresh the page to try again.  If the problem persists, try another browser.</br>', 'warning', 0);
                    return;
    });
                
}).catch(function (err) {
  alertIt('Something went wrong.<br>Please refresh the page to restart the installation process.<br>'+err, 'danger', 0);
                return;
});
    
    
    /** TO HERE, WITHOUT RUNNING THESE FUNCTION DURING*/
   /*THE ONUPDATEFOUND EVENT AS THEN THEY WILL    RUN TWICE**/
    
    
    
        }, (err) => {
            alertIt('Something went wrong.<br>Please refresh the page to restart the   installation process.<br>', 'danger', 0);
        })
} else {
           alertIt('This browser is not compatible with this app.<br>Please try to use a   different browser to install this application.<br>', 'danger', 0);
   return;
}
}

I initialize this script like so:

  window.addEventListener("load", () => {
 makeProgress('Checking','system');     
  installApp(appsPath, appScope);
  })

How can mock class methods inside class be tested?

I have a mock class for a web service:

src/_mocks _/ExternalService.ts

export default class ExternalService {

  async queryService(skus: string): Promise<any> {
    try {
      return await this.mockResponse;
    } catch (error) {
      return error;
    }
  }

  mockResponse: any = {
    data: {
      recordSetCount: 6,
      isMock: true,
      items: [
       // Mock items
      ]
    }
  };

This method correctly calls the mock class in Jest:

src/Accesories.ts

  async getAccesoriesFromService(skus: string): Promise<any> {
    const externalService = new ExternalService();
    const productsData = [];
    
    try {
      const products = await externalService.queryService(skus);

      if (!products.data?.items?.length) {
        return { errorCode: -4 };
      }

      ... 

      return { errorCode: 0, products: productsData };
    } catch (error) {
      return { errorCode: -1, error };
    }
  }

In this test I want to override the mock with another mock:

_ tests__/main.spec.ts

const accesories = new Accesories();
const externalService = new ExternalService();

jest.mock('../src/ExternalService');

it('get no accesories from service', async () => {
  const mockResponseNoRecords: any = {
    data: {
      recordSetCount: 0,
      items: [] // empty array
    }
  };
  jest.spyOn(externalService, 'queryService').mockImplementation((): any => {
    return mockResponseNoRecords;
  });

  try {
    await accesories.getAccesoriesFromService('string with skus');
  } catch (error) {
    expect(error.errorCode).toBe(-4);
  }
}

But when I run the test, I get these results from console.log:

  console.log
    products in test code:  {
      mockResponseNoRecords: {
        data: {
        recordSetCount: 0,
        items: []
      }
    }

      at __tests__/main.spec.ts:96:11

  console.log
    products in actual code:  {
      data: {
        recordSetCount: 6,
        isMock: true,
        items: [
          // Items from the mock class
        ]
      }
    }

And the test passes because the original mock was called, it was not successfully spied

What I want to achieve is to override the method in the mock class in order to make it fail, but the original mock is being called.

How to make a POST request from Flutter to Amplify REST API

Following the getting started documentation for Amplify Flutter REST API, the auto-generated POST request below for ExpressJS results in the following error:

SyntaxError: Unexpected token ‘ in JSON at position 1
at JSON.parse

The GET request returns fine, but when changing to POST and adding the body field below from the documentation the error is returned. How can a POST request be successfully called from Flutter using the Amplify REST API?

Flutter GET Request – (no error)

Future<void> callAPI() async {
    try {
      RestOptions options = RestOptions(
          path: '/example',
          apiName: 'ExpressJSRESTAPI'
      );
      RestOperation restOperation = Amplify.API.get(
          restOptions: options
      );
      RestResponse response = await restOperation.response;
      print('GET call succeeded');
      print(new String.fromCharCodes(response.data));
    } on ApiException catch (e) {
      print('GET call failed: $e');
    }
  }

Flutter POST Request (throws error)

Future<void> callAPI() async {
    try {
      RestOptions options = RestOptions(
          path: '/example',
          body: Uint8List.fromList("{'name':'Mow the lawn'}".codeUnits),
          apiName: 'ExpressJSRESTAPI'
      );
      RestOperation restOperation = Amplify.API.post(
          restOptions: options
      );
      RestResponse response = await restOperation.response;
      print('POST call succeeded');
      print(new String.fromCharCodes(response.data));
    } on ApiException catch (e) {
      print('POST call failed: $e');
    }
  }

ExpressJS GET request path

app.get('/example', function(req, res) {
  // Add your code here
  res.json({success: 'get call succeed!', url: req.url});
});

ExpressJS POST request path

app.post('/example', function(req, res) {
  // Add your code here
  res.json({success: 'post call succeed!', url: req.url, body: req.body})
});

How do I find the exact total of the cart(Javascript)

I have made an online food ordering website all is done but I don’t know I am getting sum BUG in finding the total
The javascript updatecartTotal() method which finds total goes like this

   
    var cartItemContainer = document.getElementsByClassName('cart-items')[0]
    var rowvar = cartItemContainer.getElementsByClassName('cart-row')
    var total = 0
    

    
    for (var i = 0; i < rowvar.length; i++) {
        var rowvar = rowvar[i]
        var priceElement = rowvar.getElementsByClassName('cart-price')[0]
        var quantityElement = rowvar.getElementsByClassName('cart-quantity-input')[0]
        var price = parseFloat(priceElement.innerText.replace('₹', ''))
        var quantity = parseInt(quantityElement.value)
        z = (price * quantity)
        console.log(price)
        console.log(z)
        console.log(quantity)
        total = (Math.round(z*5/100))  + (quantity*total) + (z)
        
        console.log(total)
    }
}

I want a gst of 5 percent NOT ON ULTIMATE FINAL PRICE
I want it on final price of each food item then add all final prices to get ULTIMATE FINAL PRICE which is our total.It is quite confusing bug for me hope you can solve it.

Here price is just the price per piece of item

Thank You

dotted background with pure html/css

I need to style element background with dots like in the picture. Tried a lot of from the web but I need exactly like in the pictre

enter image description here

I don’t understand all things connected to the linear-gradient found smth like “background-blend”, “radial-gradinet” but I can’t get exactly what I want.

background:
            linear-gradient( /* background color fading left to right , to blend with every others gradient bg */
                    to left,
                    #fff,
                    #fff),
            repeating-linear-gradient( /* horizontal white lines hidding a row of dots */
                    to bottom,
                    transparent 0,
                    transparent 32px,
                    white 32px,
                    white 40px,
                    transparent 40px
            ),
            repeating-linear-gradient( /* vertical lines hidding a col of dots */
                    to right,
                    transparent 0,
                    transparent 32px,
                    white 32px,
                    white 40px,
                    transparent 40px
            ),
            radial-gradient( /* dot repeated via background-size */
                    circle at 5px 5px,
                    #2f4e79 1px,
                    transparent 2px,
                    transparent 8px
            )
            0 0 / 8px 8px;

    background-blend-mode:
            multiply, /* only blend the first layer to keep dots hidden */
            normal,
            normal,
            normal;

jQuery Dialog Overlay Only Works at the Top of the Page

I am giving a link to open a dialog approximately in the middle of a web page. After clicking the link, a dialog opens. So far, no problem. But the weird thing is the overlay doesn’t work correctly. The top of the page turns black. So it’s not behind the dialog. I slide the scroll bar up when the dialog window is open. At the top the background is black. But the place where the dialog opens is the same. I’m looking for how to fix this problem.
A new class definition has been proposed for a similar problem. However, that didn’t work for me.

jQuery(document).ready(function($){
    jQuery( "#custom-dialog" ).dialog({
      autoOpen: false,
      width: "50%",
      height: 400,
      modal: true,
      responsive: true,
      show: {
        effect: "clip",
        duration: 1000
      },
      hide: {
        effect: "clip",
        duration: 1000
      },
      open: function(event, ui) {

        jQuery(this).closest(".ui-dialog")
        .find(".ui-dialog-titlebar-close")
        .removeClass("ui-dialog-titlebar-close")
        .html("<span class='ui-button-icon-primary ui-icon ui-icon-closethick'></span>");
       jQuery('.ui-widget-overlay').addClass('new-override');
    }
    });
    jQuery( "#custom-btn" ).on( "click", function() {
      jQuery( "#custom-dialog" ).dialog( "open" );
    });
  });
.ui-widget-overlay.ui-front.new-override{background:#000;}
  <link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<div id="custom-dialog" title="Custom">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem, nobis expedita fuga repudiandae porro velit vitae? Obcaecati quia ipsa repellat tempora aspernatur quisquam, illo amet corporis nisi quis, itaque aperiam.
</div>
<button id="custom-btn">Open Dialog</button>

How to stop running async function on node.js from react application?

React app can run node.js function which preparing data and sending information to the database in batches.
It takes a lot of time and I would like to add the ability to stop this function right from react app.

I tried a lot of things to include in this function including:

  • while loop: added the variable outside the function – if ‘true’ – run code, if not – return – it just doesn’t work (variable was changed from react using socket.IO)

  • setTimeout (also setInterval), triger clearTimeout function from react: this doesn’t work as setTimeout and setInterval doesn’t work in async function

after that:

  • made (actually fond here on stackoverflow) new function to promisify setTimeout to be able to use in async function:
const setTimeout2 = (callback, ms) => {
  return new Promise(
    resolve =>
      (to = setTimeout(() => {
        callback();
        resolve();
      }, ms))
  );
};
async function addOrdersToDB(limit) {
  do {
    await setTimeout2(async () => {
      try {
        // some code here
      } catch (err) {
        console.log(err);
      }
    }, 400);
  } while (latestOrderExist);
}
function clearTO() {
  setTimeout(() => {
    console.log('clearTO');
    clearTimeout(to);
  }, 3000);
}

This for some reason doesn’t iterate.

Is there solution for this?
Thanks!

How to compare 2 nested json objects arrays Javascript

I am trying to compare 2 nested json objects arrays using lodash. Following example will return true even obj1 and obj2 have different number of objects inside the array.
Basically what I need to do is compare these 2 nested json objects arrays and if the arrays are identical then needs to return true else false

note : obj1 has price element and obj2 has countInStock which should not use to compare

Can anyone help me to solve this?

import _ from "lodash"

var obj1 = [{
    "colour": {
        "value": "Black",
        "label": "Black"
    },
    "size": {
        "value": "M",
        "label": "M"
    },
    "price": "70"
},
{
    "colour": {
        "value": "Black",
        "label": "Black"
    },
    "size": {
        "value": "M",
        "label": "M"
    },
    "price": "70"
},
{
    "colour": {
        "value": "Silver",
        "label": "Silver"
    },
    "size": {
        "value": "S",
        "label": "S"
    },
    "price": "50"
},
{
    "colour": {
        "value": "Black",
        "label": "Black"
    },
    "size": {
        "value": "L",
        "label": "L"
    },
    "price": "130"
}]

var obj2 = [{
    "colour": {
        "value": "Silver",
        "label": "Silver"
    },
    "size": {
        "value": "S",
        "label": "S"
    },
    "countInStock": "3"
},
{
    "colour": {
        "value": "Black",
        "label": "Black"
    },
    "size": {
        "value": "M",
        "label": "M"
    },
    "countInStock": "10"
},
{
    "colour": {
        "value": "Black",
        "label": "Black"
    },
    "size": {
        "value": "L",
        "label": "L"
    },
    "countInStock": "3"
}]

var result = _.isEqual(
  _.omit(obj1.sort, ['countInStock']),
  _.omit(obj2.sort, ['price'])
);

console.log(result); // true

Axios Get Request Not Working on Host in Next.js

I have an API which gets records from Mongodb. When I call records from db, records are coming, there is no problem. But it’s not working on the host. There is an error on console like Failed to load resource: the server responded with a status of 404 () api/improve-language?cat=general:1.

My codes where I’m trying to get datas:

useEffect(() => {
    getAllData(category)
  }, [])

  async function getAllData(cat){

    if(cat){
      cat = `?cat=${cat}`
    } else{
      cat = ``
    }
    
    axios
    .get(`/api/improve-language${cat}`)
    .then(res => {
      setAllWords(res.data)
      setNeverAskedWords(res.data)
      newQuestionAndAnswers(res.data)
    })
    .catch(err =>{
      console.log(err)
    })

  }

the close-btn close the video but the sound still run in background?

how I can make the close-btn close the video and stop it in same time??
the close-btn close the video but the sound still run in background??
do I have any probleme in the code?

<HTMl>
  <head>
      <link rel="stylesheet" href="style.css">
  </head>
<body>
  
<div class="video-player" id="video-player">
<video width="100%" controls autoplay id="myVideo">
  <source src="media/vid1.mp4" type="video/mp4">
</video>
   <img src="media/close.png" class="close-btn"
    onclick="stopVideo()">
</div>


<script>

var Videoplayer = document.getElementById("videoPlayer");
var Videoplayer = document.getElementById("myVideo");

function stopVideo(){

  videoPlayer.style.display = "none";
}

</script>

How should I use the SCSS variables correctly with the VUE3 stack?

In the global file VUE3 of the project I write the SCSS variable.

введите сюда описание изображения

Further, in one of the modules I try to use it:

введите сюда описание изображения

I get an error.

введите сюда описание изображения

98% after emitting CopyPlugin

 ERROR  Failed to compile with 1 error                                                                                                                                                  17:57:46

 error  in ./src/components/headerNav.vue?vue&type=style&index=0&id=14455714&lang=scss&scoped=true

Syntax Error: SassError: Undefined variable.
  ╷
6 │   background-color: $--color-second;
  │                     ^^^^^^^^^^^^^^^
  ╵
  E:Progi3vue3-perfect-goodssrccomponentsheaderNav.vue 6:21  root stylesheet


 @ ./node_modules/vue-style-loader??ref--9-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--9-oneOf-1-1!./node_modules/vue-loader-v16/dist/stylePostLoader.js!./node_modules/postcss-loader
/src??ref--9-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--9-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader-v16/dist??ref--1-1!./src/components/
headerNav.vue?vue&type=style&index=0&id=14455714&lang=scss&scoped=true 4:14-455 15:3-20:5 16:22-463
 @ ./src/components/headerNav.vue?vue&type=style&index=0&id=14455714&lang=scss&scoped=true
 @ ./src/components/headerNav.vue
 @ ./node_modules/cache-loader/dist/cjs.js??ref--15-0!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--15-2!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-l
oader-v16/dist??ref--1-1!./src/views/Home.vue?vue&type=script&lang=ts
 @ ./src/views/Home.vue?vue&type=script&lang=ts
 @ ./src/views/Home.vue
 @ ./src/router/index.ts
 @ ./src/main.ts
 @ multi (webpack)-dev-server/client?http://192.168.0.102:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.ts

Question:
Why is this happening and how is it necessary to implement the task in the context of this technology stack?

P.S. The editor itself picks up the color of the variable correctly:

введите сюда описание изображения