Return Value Outside Function [duplicate]

I want to make a function which can be called anywhere to return the price of the entered URL as in this case, I am using API to fetch the price of Bitcoin. Can someone let me know how this thing will work?

function getPrice(url) {
    fetch(url)
    .then(response => response.json())
    .then(data => {
        var currentPrice = data[0]['current_price'];
        return currentPrice;
    });
}

console.log(getPrice('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin'))

Params without value in URLSearchParams?

I’d like to get an a=1&b=2&foo URL with URLSearchParams.

Here’s what I tried:

new URLSearchParams([['a', 1], ['b', 2], ['foo']]).toString();
// Uncaught TypeError: Failed to construct 'URLSearchParams':
// Failed to construct 'URLSearchParams': Sequence initializer must only contain pair elements

new URLSearchParams([['a', 1], ['b', 2], ['foo', '']]).toString();
// a=1&b=2&foo=

new URLSearchParams([['a', 1], ['b', 2], ['foo', null]]).toString();
// a=1&b=2&foo=null

new URLSearchParams([['a', 1], ['b', 2], ['foo', undefined]]).toString();
// a=1&b=2&foo=undefined

Can it be done?

Resetting the form fields and output of the function simultaneously

I am making a picture frame calculator. Therefore, I’m creating a reset button to clear the form fields of the calculator and the output of function calc() simultaneously.

However, I’m running into a problem where my reset button is only resetting the form fields, but not the output of the function.

Here’s the calculator excluding most CSS:

#height {
  text-align: left;
  margin-top: 250px;
  margin-left: 4px;
}
<section>

  <form id="frm1" action="/index.html" method="post">

    <fieldset>

      <legend>

        I Was Framed Calculator

      </legend>



      <label for="frameWidth">Frame Width:</label><input type="number" title="numbers should be in inches" onkeypress="return (event.which == 8 || event.which == 0 || event.which == 13) ? null : event.which >= 48 && event.which <= 57" step="any" min="0"
        name="frameWidth" id="frameWidth">
      <select name="frameWidthFraction" id="frameWidthFraction">
        <option value="0">0</option>
        <option value="0.0625">1/16</option>
        <option value="0.0125">1/8</option>
        <option value="0.1875">3/16</option>
        <option value="0.25">1/4</option>
        <option value="0.3125">5/16</option>
        <option value="0.375">3/8</option>
        <option value="0.4375">7/16</option>
        <option value="0.50">1/2</option>
        <option value="0.5625">9/16</option>
        <option value="0.625">5/8</option>
        <option value="0.6875">11/16</option>
        <option value="0.75">3/4</option>
        <option value="0.8125">3/16</option>
        <option value="0.875">7/8</option>
        <option value="0.9375">15/16</option>
      </select>

      <label for="frameHeight">Frame Height:</label><input type="number" title="numbers should be in inches" onkeypress="return (event.which == 8 || event.which == 0 || event.which == 13) ? null : event.which >= 48 && event.which <= 57" step="any" min="0"
        name="frameHeight" id="frameHeight">
      <select name="frameHeightFraction" id="frameHeightFraction">

        <option value="0">0</option>
        <option value="0.0625">1/16</option>
        <option value="0.0125">1/8</option>
        <option value="0.1875">3/16</option>
        <option value="0.25">1/4</option>
        <option value="0.3125">5/16</option>
        <option value="0.375">3/8</option>
        <option value="0.4375">7/16</option>
        <option value="0.50">1/2</option>
        <option value="0.5625">9/16</option>
        <option value="0.625">5/8</option>
        <option value="0.6875">11/16</option>
        <option value="0.75">3/4</option>
        <option value="0.8125">3/16</option>
        <option value="0.875">7/8</option>
        <option value="0.9375">15/16</option>
      </select>



      <label for="pictureWidth">Picture Width:</label><input type="number" title="numbers should be in inches" onkeypress="return (event.which == 8 || event.which == 0 || event.which == 13) ? null : event.which >= 48 && event.which <= 57" step="any" min="0"
        name="pictureWidth" id="pictureWidth">
      <select name="pictureWidthFraction" id="pictureWidthFraction">

        <option value="0">0</option>
        <option value="0.0625">1/16</option>
        <option value="0.0125">1/8</option>
        <option value="0.1875">3/16</option>
        <option value="0.25">1/4</option>
        <option value="0.3125">5/16</option>
        <option value="0.375">3/8</option>
        <option value="0.4375">7/16</option>
        <option value="0.50">1/2</option>
        <option value="0.5625">9/16</option>
        <option value="0.625">5/8</option>
        <option value="0.6875">11/16</option>
        <option value="0.75">3/4</option>
        <option value="0.8125">3/16</option>
        <option value="0.875">7/8</option>
        <option value="0.9375">15/16</option>
      </select>

      <label for="pictureHeight">Picture Height:</label><input type="number" title="numbers should be in inches" onkeypress="return (event.which == 8 || event.which == 0 || event.which == 13) ? null : event.which >= 48 && event.which <= 57" step="any"
        min="0" name="pictureHeight" id="pictureHeight">


      <select name="pictureHeightFraction" id="pictureHeightFraction">

        <option value="0">0</option>
        <option value="0.0625">1/16</option>
        <option value="0.0125">1/8</option>
        <option value="0.1875">3/16</option>
        <option value="0.25">1/4</option>
        <option value="0.3125">5/16</option>
        <option value="0.375">3/8</option>
        <option value="0.4375">7/16</option>
        <option value="0.50">1/2</option>
        <option value="0.5625">9/16</option>
        <option value="0.625">5/8</option>
        <option value="0.6875">11/16</option>
        <option value="0.75">3/4</option>
        <option value="0.8125">3/16</option>
        <option value="0.875">7/8</option>
        <option value="0.9375">15/16</option>
      </select><br>

      <label for="matOverlap">Mat Overlap:</label><input type="number" title="numbers should be in inches" onkeypress="(event.which == 8 || event.which == 0 || event.which == 13) ? null : event.which >= 48 && event.which <= 57" step="any" min="0" name="matOverlap"
        id="matOverlap">
      <select name="matOverlapFraction" id="matOverlapFraction">

        <option value="0">0</option>
        <option value="0.0625">1/16</option>
        <option value="0.0125">1/8</option>
        <option value="0.1875">3/16</option>
        <option value="0.25">1/4</option>
        <option value="0.3125">5/16</option>
        <option value="0.375">3/8</option>
        <option value="0.4375">7/16</option>
        <option value="0.50">1/2</option>
        <option value="0.5625">9/16</option>
        <option value="0.625">5/8</option>
        <option value="0.6875">11/16</option>
        <option value="0.75">3/4</option>
        <option value="0.8125">3/16</option>
        <option value="0.875">7/8</option>
        <option value="0.9375">15/16</option>
      </select>

      <br>


      <br>
      <br>
      <input type="reset" onreset="calc()" value="Reset">
      <input type="button" onclick="calc()" value="Calculate" name="cmdCalc" />

    </fieldset>

  </form>

</section>

<script>
  function calc()

  {

    var frameWidth = document.getElementById('frameWidth').value
    frameWidth = parseInt(frameWidth)

    var frameWidthFraction = document.getElementById('frameWidthFraction').value
    frameWidthFraction = parseFloat(frameWidthFraction)

    var frameHeight = document.getElementById('frameHeight').value
    frameHeight = parseInt(frameHeight)

    var frameHeightFraction = document.getElementById('frameHeightFraction').value
    frameHeightFraction = parseFloat(frameHeightFraction)

    var pictureWidth = document.getElementById('pictureWidth').value
    pictureWidth = parseInt(pictureWidth)

    var pictureWidthFraction = document.getElementById('pictureWidthFraction').value
    pictureWidthFraction = parseFloat(pictureWidthFraction)

    var pictureHeight = document.getElementById('pictureHeight').value
    pictureHeight = parseInt(pictureHeight)

    var pictureHeightFraction = document.getElementById('pictureHeightFraction').value
    pictureHeightFraction = parseFloat(pictureHeightFraction)

    var matOverlap = document.getElementById('matOverlap').value
    matOverlap = parseInt(matOverlap)

    var matOverlapFraction = document.getElementById('matOverlapFraction').value
    matOverlapFraction = parseFloat(matOverlapFraction)

    if (isNaN(frameWidth) || isNaN(frameHeight) || isNaN(pictureWidth) || isNaN(pictureHeight) || isNaN(matOverlap)) {
      alert('All fields are required!')
      return
    }

    var width = (1 / 2) * ((frameHeight + frameHeightFraction) - (pictureHeight + pictureHeightFraction) + (matOverlap + matOverlapFraction));
    var height = (1 / 2) * ((frameWidth + frameWidthFraction) - (pictureWidth + pictureWidthFraction) + (matOverlap + matOverlapFraction));

    document.getElementById('width').innerHTML = width
    document.getElementById('height').innerHTML = height

    document.getElementById('rectangle').scrollIntoView({
      behavior: 'smooth'
    })

  }
</script>


<div style="margin:0 auto;text-align:center;width:400px;height:50px;border:5px solid #000; margin-top: 20px; margin-bottom: 50px;padding-bottom:75%;background-color:gray" id="rectangle">
  <center>
    <div id="width"></div>
  </center>

  <div id="height"></div>
</div>

As you can see in the above code snippet the output is displayed on the rectangle. When the reset button is clicked – that output is not reset.

I’ve tried this:

<input type="reset" onreset="calc()" value="Reset">

And, onclick – but I just can’t seem to get it to work. I’m unsure if I’m even on the right track.

In other words, when reset is clicked it looks incorrectly like this: Incorrect Reset

But, it should look like this: Correct Reset

Can someone provide some guidance on how to reset both the form fields and the output of function calc() at the same time?

Javascript Parse JSON Array with Sub Array [duplicate]

I am looking to parse the JSON and access the Array within “keys”

{"keys":{"A00101":{"name":"Test Key 1","key":928625,"status":"ok"},"A00102":{"name":"Test Key 2","key":258748,"status":"ok"}},"status":"ok"}

In JavaScript I am looking retrieve all values:

  • name
  • key
  • status

I should get:

A00101
Test Key 1
928625
ok

A00102
Test Key 2
258748
ok

Create an event/function to show image loaded from AP

I am trying to get my images to load random cat pictures into the desired grid layout,
I am VERY new this concept of API’s, would you please explain to me:

  1. I have a dialog box that needs to fire off an event with a valid link to search for images[preferably for cats for this exercise]

2)The dialog box disappears and the cat images appear, i have tried to make the hard work done but i just can not think of how to find the answer i need

The content to display on the evnt is coming from the ImageGrid, so it must load that on the screen,

I know its a lot to really but i really need to know how to do this and hand this in tomorrow, if i get this i get a job:

Thanks for helping, my code below:

App.js

import React, { useState } from "react";

import Header from "./components/Header";

import Body from "./components/Body";
    
import Footer from "./components/Footer";

import ImageGrid from "./components/ImageGrid";


 function App() {
   


    return (
        <>
            <Header />

                <div className="container">
                    {/* Includes Dialog Box */}
                    <Body />      
                    <ImageGrid /> 
                </div>  
            <Footer />
        </>
         
    )
};

export default App

here is:

Body.jsx

import React, { useState } from 'react'

import DialogBox from './DialogBox';
function Body() {    

 return (
    <>    
        <div className="start-container">

            <DialogBox />  

        </div>
    </>
);}


export default Body

then:

    DialogBox.jsx
    import React, { useState } from 'react';
    
    import PropTypes from 'prop-types'
    
    // Material UI 
    import DialogActions from '@material-ui/core/DialogActions';
    import DialogContent from '@material-ui/core/DialogContent';
    import DialogTitle from '@material-ui/core/DialogTitle';
    import Input from '@material-ui/core/Input'
    import Dialog from '@material-ui/core/Dialog';
    import Button from '@material-ui/core/Button';
    import Grid from '@material-ui/core/Grid';
    
    
    
    
    
    const DialogBox = ({ ariaLabel }) => {
      const [open, setOpen] = React.useState(false);
      
      const handleClickOpen = () => {
        setOpen(true);
      };
      
      const handleClose = () => {
        setOpen(false);
      };
    
      // const handleGrid = () => {
      //   React.useState(true)
      // }
      
      return (
        <div className='modal'> 
          <Grid container justifyContent='center'>
            {/* Button To Open Dialog Box */}
            <Button 
            style={{border: '1px solid #ebc340', color: '#ebc340'}}
            variant="outlined" 
            color="secondary" 
            onClick={handleClickOpen}>
              Welcome to my Case Study, Click to begin
            </Button>
          </Grid>
            {/* Dialog Box Content */}
            <Dialog
            className='dialog-btn'
            open={open} 
            onClose={handleClose}>
              <DialogTitle>
                To begin the application, please insert your URL below:
              </DialogTitle>
              <DialogContent>
              <Input 
              placeholder="Enter Your Link Here" 
              inputProps={ariaLabel} 
              fullWidth/>
              </DialogContent>
    
              {/* Dialog Box Actions */}
              <DialogActions>
                <Button 
                onClick={handleClose} 
                color="secondary">
                  Cancel 
                </Button>
                <Button 
                onClick={handleClose} 
                color='primary' 
                autoFocus
                type='submit'
                // onSubmit={handleGrid}
                >
                  Submit
                </Button>
              </DialogActions>
            </Dialog>
        </div>
      );
    }
    
    Input.inputProps = {
      ariaLabel: 'Please insert your URL below',
      tertiaryColor: 'tertiary'
    }
    
    Input.inputTypes = {
      ariaLabel: PropTypes.string.isRequired,
      tertiaryColor: PropTypes.string.isRequired,
    };
    export default DialogBox

Lastly:

ImageGrid.jsx

import React from 'react';

// Style Images
import '../index.css';


// Fetch data from
const url = 'https://api.thecatapi.com/v1/images/search?limit=12';

function ImageGrid() {

    // catUrl is the original state
    // setCatUrl is the value of the updated vale
    const [ catUrl, setCatUrl ] = useState('');

    const getCat = () => {
        console.log('Gathering Your Images');

        fetch(url)
            .then((res) => res.json()) //gets the data in json
            .then((cats) => {
                console.log('Cats: ', cats);
                const catUrl = cats[0, 11].url;

                setCatUrl(catUrl);
            })
            .catch((error) => {
                console.log('Error: ', error)
            });
    }

    
    return (

    <>
        <div className="container">
            {/* First Row */}
            <div className="-image-container">
                <div className="image-row">
                    <img src={catUrl} alt="" />
                    <img src={catUrl} alt="" />
                    <img src={catUrl} alt="" />
                </div>

                {/* {Second Row} */}
                <div className="image-row">
                    <img src={catUrl} alt="" />
                    <img src={catUrl} alt="" />
                    <img src={catUrl} alt="" />
                </div>

                {/* Third Row */}
                <div className="image-row">
                    <img src={catUrl} alt="" />
                    <img src={catUrl} alt="" />
                    <img src={catUrl} alt="" />
                </div>

                {/* Fourth Row */}
                <div className="image-row">
                    <img src={catUrl} alt="" />
                    <img src={catUrl} alt="" />
                    <img src={catUrl} alt="" />
                </div>
            </div> 
        </div> 
    </>
  )
}

export default ImageGrid

RegEx for detecting a string and a path in one go

Here is an example of what regex I need regex

I have many of these lines in a file

build test/testfoo/CMakeFiles/testfoo2.dir/testfoo2.cpp.o: CXX_COMPILER__testfoo2_Debug /home/juxeii/projects/gtest-cmake-example/test/testfoo/testfoo2.cpp || cmake_object_order_depends_target_testfoo2

I need to detect the string between CXX_COMPILER__ and _Debug, wich is here testfoo2.

At the same time, I need to also detect the entire file path /home/juxeii/projects/gtest-cmake-example/test/testfoo/testfoo2.cpp, which comes always after the first match.

I could not figure out a regex for this. So far I have .*CXX_COMPILER__(.w+)_w+|(/[a-zA-Z_0-9-]+)+.w+ and I am using it in typescript like so:

const fileAndTargetRegExp = new RegExp('.*CXX_COMPILER__(.w+)_w+|(/[a-zA-Z_0-9-]+)+.w+', 'gm');
let match;
while (match = fileAndTargetRegExp.exec(fileContents)) {
          //do something
}

But I get no matches. Is there an easy way for this?

How can I modify react build to give me multiple javascript files?

I have a multi page application that doesn’t use node. It has a bunch of html files and javascript files. I want to render react components in the application, which I found I am able to do with ReactDOM.render.

However, I am building out the react components separately in a react project made with npx create-react-app. I can use npm run build which gives me a main.js javascript file that contains a production ready version of all my components.

I can add this main.js file into my html files with a script tag to have my components render in my multi page application.

However, the problem is that I notice when I run npm build, I get one main.js file that contains everything. This is not good because the app will run too slow if I have to load all of my react components in main.js file every time I go to a new page.

Instead, I am looking to only load the specific components I need for a page.

Example:

Lets say I had a test1 component and a test2 component.
Page1 has a script to use test1, so I only want to load test1 on Page1.
Page2 has a script to use test2, so I only want to load test2 on Page2.
Therefore, I need a test1.js file and a test2.js file after npm run build

How would I do this?

Thanks,

RxJS how to grab first values that is not null from two promises

I’m trying to wrap my head around how RxJS concat works, and how it works with Promises in general.

I have two observables:

currentConfirmation$ emits null

newConfirmation$ emits a new confirmation

Could someone explain why this works:

const finalConfirmation$ = currentConfirmation$.pipe(
    switchMap((conf) => {
      if (!conf) {
        return newConfirmation$
      }

      return of(conf)
    })
  )

But this does not

const finalConfirmation$ = concat(currentConfirmation$, newConfirmation$).pipe(find((conf) => !!conf))

By not works I mean this test passes with the switchMap version and times out with the concat version

  test("updateConfirmation should create the confirmation if it doesn't exist", (done) => {
    updateConfirmation({ value: true, symbol: 'LTCUSD', name: 'BTC_TEST_CONFIRMATION_999' }).subscribe((conf) => {
      done()
      expect(conf.entityData).toEqual({ value: true, symbol: 'LTCUSD', name: 'BTC_TEST_CONFIRMATION_999' })
    })
  })

I would also love to know if there is a better approach to accomplishing the above than what I have come up with.

Smooth scrolling when a link is clicked on mobile

I have created a site and have anchor links at the top of the site. On a computer, when I press a link, it scrolls to the given section in a smooth manor, but on a phone it just jumps straight to the section. I originally used scroll-behavior: smooth, but implemented JavaScript code instead because I thought that may fix the problem; it didn’t. Below I have attached my html code and JavaScript code I am currently using:

    <nav class="nav">
        <h6 id="site">website.net</h6>
        <ul class="nav__links">
            <li class="nav__item">
                <a href="#about" class="link">About</a>
            </li>
            <li class="nav__item">
                <a href="#experience" class="link">Link2</a>
            </li>
            <li class="nav__item">
                <a href="#skills" class="link">Link3</a>
            </li>
            <li class="nav__item">
              <a href="#projects" class="link">Link4</a>
            </li>
        </ul>
        <div class="hidden--btn menu--btn">
          <div class="menu-btn__burger"></div>
        </div>
    </nav>

Java:

const nav = document.querySelector('.nav');
/*scroll animation */
const scrollTo = function (e) {
    e.preventDefault();
    const target = e.target;
    if (target.classList.contains('link')) {
        const id = target.getAttribute('href').slice(1);
        document.getElementById(id).scrollIntoView({behavior: "smooth"});
    }

    if (target.classList.contains('hamburger--link')) {
        const id = target.getAttribute('href').slice(1);
        document.getElementById(id).scrollIntoView({behavior: "smooth"});
        hamburgerBin.classList.toggle('hidden--two');
    }
}

nav.addEventListener('click', scrollTo);

React Native: Opening a Modal from inside another Modal doesn’t work in iOS

I have a Dropdown component which is just a React Native Modal positioned next to a toggle – the Modal allows me to make the whole background a Pressable so I can close the dropdown when any area outside it is pressed.

The items inside the dropdown menu each have an onPress prop which performs a given function while also closing the dropdown itself. This works great, except when I want to use the onPress event to open another react-native Modal.

Here’s a (simplified) example:

<>
  // Custom component that renders a react-native Modal
  <Dropdown
    items={[
      { label: "Press to open a Modal", onPress: () => setIsModalOpen(true) }
    ]}
  />

  // Another react-native Modal
  <Modal visible={isModalOpen}>
    ...
  </Modal>
</>

This works as expected on the web – the Dropdown’s Modal closes and the other Modal opens at the same time. However, on iOS, the second Modal never opens, and the app actually becomes completely unresponsive until I restart it from the Metro builder.

I’ve seen other questions on Stack Overflow that mention “opening a modal from inside another modal”, but the existing questions all seem to concern nested modals. In my case, we aren’t actually trying to nest modals – the second modal should open as the first one closes. The iOS app seems to just not render the second modal, even though I can verify through the console that the isModalOpen boolean is getting set to true.

I’m beginning to think this is actually a bug with React Native itself, but figured I’d check here in case it’s a known issue, maybe with event bubbling or something?

How to deploy Nuxt SSR in Firebase with Cloud functions

I’m playing with Nuxt in mode SSR and Firebase + Cloud functions, after deploy, everything working fine, no errors in the console from nuxt project, no errors in the functions log, but I got a page with this message: Page Not Found.

I’ve followed this tutorial: https://www.youtube.com/watch?v=_aTvdnqY3ek

This is my firebase.json


    {
      "functions": {
        "source": "functions",
        "predeploy": [
          "npm run build && rm -rf functions/nuxt && cp -r .nuxt/ functions/nuxt/ && cp nuxt.config.js functions/"
        ]
      },
      "hosting": {
        "predeploy": [
          "rm -rf public/* && mkdir -p public/_nuxt && cp -r .nuxt/dist/client/ public/_nuxt && cp -a static/. public/"
        ],
        "public": "public",
        "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
        "rewrites": [
          {
            "source": "**",
            "functions": "ssrapp"
          }
        ]
      }
    }

My functions/index.js


    const functions = require('firebase-functions')
    
    const { Nuxt } = require('nuxt-start')
    
    const nuxtConfig = require('./nuxt.config.js')
    
    const config = {
      ...nuxtConfig,
      dev: false,
      debug: false,
      buildDir: 'nuxt'
    }
    
    const nuxt = new Nuxt(config)
    
    exports.ssrapp = functions.https.onRequest(async (req, res) => {
      await nuxt.ready()
      nuxt.render(req, res)
    })
    

My nuxt.config.js


    module.exports = {
    
        ssr: true,
        server: {
          port: 3400
        },
      
        /*
         ** Headers of the page
         */
        head: {
          htmlAttrs: {
            lang: 'es-ES'
          },
          meta: [
            { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge' },
            { charset: 'utf-8' },
            { name: 'viewport', content: 'width=device-width, initial-scale=1' }
          ],
          link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
          link: [
            {
              rel: 'stylesheet',
              href: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css'
            }
          ]
        },
      
        /*
         ** Customize the progress-bar color
         */
        loading: { color: '#fff' },
      
        /*
         ** Global CSS
         */
        css: ['~/assets/css/style.css', 'assets/css/bootstrap.min.css', 'assets/css/custom.css'],
        script: [
          {
            src: '~/assets/js/bootstrap.bundle.min.js',
            type: 'text/javascript'
          }
        ],
      
        router: {
          // customize nuxt.js router (vue-router).
          middleware: 'i18n' // middleware all pages of the application
        },
        /*
         ** Plugins to load before mounting the App
         */
        plugins: [
          '~/plugins/i18n.js',
          '~/plugins/fontawesome.js',
          { src: '~/plugins/vue-carousel.js', mode: 'client' }
        ],
      
        /*
         ** Google Fonts
         */
        googleFonts: {
          families: {
            Acme: true,
            'Acme+Sans': true,
            Lato: [100, 300],
            Raleway: {
              wght: [100, 400],
              ital: [100]
            }
          }
        },
      
        /*
         ** Nuxt.js modules
         */
        modules: [
          '@nuxtjs/device',
          '@neneos/nuxt-animate.css',
          '@nuxtjs/moment',
          ['@nuxtjs/google-fonts'],
          [
            '@nuxtjs/google-analytics',
            {
              id: 'UA-00000-0000000'
            }
          ],
          [
            'nuxt-validate',
            {
              lang: 'es',
              nuxti18n: {
                locale: {
                  'es-ES': 'es_ES'
                }
              }
            }
          ]
        ],
      
        webfontloader: {
          google: {
            families: ['Open+Sans:400,700']
          }
        },
        /*
         ** Build configuration
         */
        build: {
          // publicPath: 'nxt',
          /*
           ** You can extend webpack config here
           */
          vendor: [
            'vue-i18n' // webpack vue-i18n.bundle.js
          ],
      
          extend(config, ctx) {}
        }
        // serverMiddleware: ['~/sendgridApi/src/index.js']
      }

Any idea what’s wrong?

Thanks in advance!

How to re-render layout upon user interaction in Cytoscape.js?

In my Next.js application, I’m using Cytoscape.js to produce data visualizations. I’ve enabled functionality using the Cytoscape Context Menus library to allow users to change the displayed label for a node using a dynamically generated list of options based on the respective node’s properties. However, there are some instances when after modifying a node’s label, it may overlap with another nearby node’s label since it became a lot larger. I think I need to trigger a re-rendering of the layout whenever a user interacts with the visualization, so that the node with the modified label would be moved so that it wouldn’t overlap with another node’s label it would have otherwise.

I’ve tried the solution (i.e., setting infinite: true within the layout config object) from a similarly titled post on Stack Overflow, but unfortunately that didn’t work for me. Is anyone aware of any other values I may need to add in the layout config object to make sure that the layout is re-rendered after each user interaction? Or is there something else I need to do? For context, we are using two layouts in our application: dagre & concentric. We use the dagre layout for general hierarchical left-right layout in our visualization and concentric layout to arrange placeholder nodes around their parent nodes. I’d really appreciate any help with this! I’ve included my code below:

Code:

const layoutConfig = {
    name: 'dagre',
    avoidOverlap: true,
    nodeDimensionsIncludeLabels: true,
    infinite: true,
    rankDir: 'LR',
    spacingFactor: 2,
    fit: false,
};

const circleLayoutConfig = {
    name: 'concentric',
    minNodeSpacing: 100,
    avoidOverlap: true,
    nodeDimensionsIncludeLabels: true,
    infinite: true,
    fit: false,
    padding: 100,
    boundingBox: {
        x1: x,
        y1: y,
        w: 10,
        h: 10,
    },
}

FWIW, I am using Cytoscape.js v3.21.1 & Cytoscape Context Menus v4.1.0.

Can the Key value for DynamoDB be a variable or does it have to be hardcoded?

This is my code:

let client_id = "a3bdso310";
var params = { TableName: tableName, Key: { 'client_id': {S: client_id}}};

I am getting an error when I try to perform a GetItem using DynamoDB SDK: “The provided key element does not match the schema”. Whenever I replace {S: client_id} with the actual value like this {S: "a3bdso310"} it works just find. Can the “Key” value not be a variable? What is even weirder is that when I test this locally it works just fine, the issue is only occurring when I deploy my local project to an EC2. So basically when I run this project on my local machine, everything is the same, the only difference I can think of when running it in an EC2 instance is maybe the fact that the EC2 instance has to have permissions to perform operations on my DynamoDB table. But I already gave it permissions, and other operations work fine that don’t require a key (e.g. scan). Is there a solution around this?

Appending Object to array in node module using POST method

I am currently working on an assignment where I have to get transactions array from my transaction-manager module, use the POST method to append a new object to the array using req.body, and then delete one of the items from the array using DELETE method. When I try running the POST method using postman software, it returns saying undefined. Theres clearly an error when requesting the body but I am unsure why this is occurring, any help would be appreciated.Postman Error Output

Transactions.js file

//Variables
const port = 3000;
const express = require('express');
const app = express();
app.use(express.json());
const transaction = require('transaction-manager');

//get /transactions
app.get("/transactions", (req, res) => {
     res.status(200).json(transaction.getTransactions());
});

//post /transactions/
app.post("/transactions", (req, res) => { 
     const json_body = req.body;

     const new_transaction = new transaction.Transaction(json_body.id, json_body.date, json_body.description, json_body.type, json_body.amount);
     transaction.TransactionList.push(new_transaction);

     
     res.json({ message: `Transaction ID ${id} added.` });
});

//delete /products/
app.delete("/products", (req, res) => {

     if (req.params) {
          const transactionID = req.params['transaction_id']
          transaction.TransactionList = transaction.TransactionList.filter(v => v.id !== transactionID)

          res.json({ message: `Transaction ID ${transactionID} removed.`})
     }
     else { res.json({ message: 'No transaction ID passed.'}) }


     res.json({
          message: `Transaction ID ${transaction_id} removed.`
     });
})

//Listen
app.listen(port, () => {
     console.log(`Listening on port ${port}`);
})

TransactionManager.js

//Transaction Class
class Transaction {
     constructor (id, date, description, type, amount) {
          this.id = id;
          this.date = date;
          this.description = description;
          this.type = type;
          this.amount = amount;
     }

     get json () {
          return {
               id: this.id,
               date: this.date,
               description: this.description,
               type: this.type,
               amount: this.amount
          }
     }
}

//Transaction List
let TransactionList = [
     new Transaction(Math.floor(Math.random() * 100) + 1, "Apr 5 2002", "Couch for living room", "Credit", 200),
     new Transaction(Math.floor(Math.random() * 100) + 1, "Aug 9 2003", "TV for bedroom", "Debit", 350),
     new Transaction(Math.floor(Math.random() * 100) + 1, "May 5 2004", "Tire replacement", "Credit", 150)
];


//Export getTransactions
exports.getTransactions = () => {
     return TransactionList;
}
exports.Transaction = Transaction;
exports.TransactionList = TransactionList;