Getting Undefined using Props with Map function, how can it be resolved?

I’m trying to integrate Mapbox to a tutorial page I’m working on using following code ang calling API:https://www.jsonkeeper.com/b/5NPS, however instead of getting Object values I’m getting “undefined “

AirBnbMap.js (component)

import { useState } from "react";
import Map from "react-map-gl";
import { getCenter } from "geolib";

function AirBnbMap({ searchResults }) {
  //Transform the search results objects in to
  //{ latitude: 52.516272, longitude: 13.377722 },
  //object

  const coordinates = searchResults.map((result) => ({
    longitude: result.long,
    latitude: result.lat,
  }));

  console.log(coordinates);

  //The latitude and longitude of the center of locations coordinates

  const center = getCenter(coordinates);

  const [viewState, setViewState] = useState({
    longitude: center.longitude,
    latitude: center.latitude,
    zoom: 3.5,
  });

  return (
    <Map
      {...viewState}
      onMove={(evt) => setViewState(evt.viewState)}
      style={{ width: "100%", height: "100%" }}
      mapStyle="mapbox://styles/mapbox/streets-v9"
      mapboxAccessToken={process.env.mapbox_key}
    />
  );
}
export default AirBnbMap;

search.js (page)

import { useRouter } from "next/router";
import { format } from "date-fns";
import Header from "../components/Header";
import Footer from "../components/Footer";
import InfoCard from "../components/InfoCard";
import AirBnbMap from "../components/AirBnbMap";

function Search({ searchResults }) {
  const router = useRouter();

  //ES6 Destrucuring
  const { location, startDate, endDate, noOfGuests } = router.query;

  const formattedStartDate = format(new Date(startDate), "dd MMMM yy");
  const formattedEndDate = format(new Date(endDate), "dd MMMM yy");
  const range = `${formattedStartDate} - ${formattedEndDate}`;

  return (
    <div>
      <Header placeholder={`${location} | ${range} | ${noOfGuests} guests`} />
      <main className="flex ">
        <section className="flex-grow pt-14 px-6">
          <p className="text-xs">
            300+ Stays - {range} - for {noOfGuests} guests
          </p>
          <h1 className="text-3xl font-semibold mt-2 mb-6">
            Stays in {location}
          </h1>

          <div className="hidden lg:inline-flex mb-5 space-x-3 text-gray-800 whitespace-nowrap">
            <p className="button">Cancellation Flexibility</p>
            <p className="button">Type of Place</p>
            <p className="button">Price</p>
            <p className="button">Rooms and Beds</p>
            <p className="button">More filters</p>
          </div>

          <div className="flex flex-col">
            {searchResults?.map(
              ({ img, location, title, description, star, price, total }) => (
                <InfoCard
                  key={img}
                  img={img}
                  location={location}
                  title={title}
                  description={description}
                  star={star}
                  price={price}
                  total={total}
                />
              )
            )}
          </div>
        </section>

        <section className="hidden xl:inline-flex xl:min-w-[40%] sticky top-[76px] h-[calc(100vh-76px)]">
          <AirBnbMap />
        </section>
      </main>

      <Footer />
    </div>
  );
}

export default Search;

export async function getServerSideProps() {
  const searchResults = await fetch("https://www.jsonkeeper.com/b/5NPS").then(
    (res) => res.json()
  );

  return {
    props: {
      searchResults,
    },
  };
}

Getting error:
Server Error
TypeError: Cannot read properties of undefined (reading ‘map’)

enter image description here

However expecting Object value:
enter image description here

Html2Canvas save file to the server

I’m using html2canvas to create an image and put it into “#output’ element and that works as intended, but I would also like to save that image on my server but that I can’t get to work.

Here is how I’m trying to do that:

// HTML2Canvas script
function convert() {
  $("#output").empty();
  const original = document.querySelector('#input')
  const canvasContainer = document.querySelector('#output')

  html2canvas(original, {
    scale: 2,
    useCORS: true,
    onrendered: function(canvas) {        
      var imgData = canvas.toDataURL('image/jpeg');   


      var url = '/files/export.php';

      $.ajax({ 
        type: "POST", 
        url: url,
        dataType: 'text',
        data: {
          base64data : imgData
        }
      });     
    }
  }).then(canvas => {
    canvasContainer.appendChild(canvas)
  })
}

And here is my export.php

<?php

    $data = $_REQUEST['base64data']; 
    //echo $data;

    $image = explode('base64,',$data); 


    file_put_contents('here.png', base64_decode($image[1]));

?>

Any clues on what I’m missing here?

Parsing Childnode values in javascript

I have an XML

<root><example><examplevalue>exampletext</examplevalue><examplevalue>exampletext2</examplevalue</example></root>

and I have the following javscript code

            if (window.DOMParser){ // Standard browsers
                var parser = new DOMParser();
                xmlDoc = parser.parseFromString(xmlString, "text/xml");
            }
            else { // Internet Explorer
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.loadXML(xmlString); 
            }
            var coll=xmlDoc.getElementsByTagName("example");
            console.log(coll[0].childNodes[0].nodeValue);

The console output is

null

I would expect it to be

exampletext

Why are the childnodes not parsed correctly?
childNodes seems to be a method of class node. But the getElementByName return a HTMLCollection object. How does that work?
Thanks for any hints.

webpack devServer Hot reload / HMR reloading but not compiling VueJS components

Using webpack dev server on a vuejs project, when I edit a file the web page is reloaded but not updated.

When sniffing the websocket communication between the client and webpack server I can see this after editing LoginComponent.vue:

enter image description here

The “type”: “static-changed” makes me believe that webpack doesn’t know that it has to compile .vue files on change, and I have no idea how to fix that.

Here is my vue.config.js:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    optimization: {
      runtimeChunk: 'single',
    },
  },
  devServer: {
    client: {
      progress: true,
    },
    static: {
      directory:'/dontmanagestaticfiles'
    },
    port: 80,
    allowedHosts: 'all',
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    
    // hot: true,
    liveReload: true,

    watchFiles: {
      paths: ['src/**'],
      options: {
        // ignored: ['nodes_modules'],
        usePolling: true,
        aggregateTimeout: 300,
        interval: 500,
      }
    },
  },
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions = {
          isCustomElement: tag => tag.startsWith('ion-')
        };
        return options;
      });
  }
})

How to start deployed Angular application locally

I have deployed Angular frontend, on server it working fine, there are 3 script

/runtime.0fad6a04e0afb2fa.js    
/polyfills.24f3ec2108a8e0ab.js    
/main.a9b28b9970fe807a.js    

I want to start this application in Firefox, without IIS or Apache – by simple click to Html-page. Is it possible?

But Firefox said me

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///runtime.0fad6a04e0afb2fa.js. (Reason: CORS request not http). 

Is it possible to remove this restriction? Or Firefox never allow me loading and working this scripts?

Vue Slick Carousel

I have slider with VueSlickCarousel.

I want to be able to manually change the pagination during the scrolling, not after it.

  data() {
    return {
      sliderConfig: {
        arrows: false,
        dots: true,
        infinite: true,
        slidesToShow: 2,
        slidesToScroll: 1,
        responsive: [
          {
            breakpoint: 1023,
            settings: {
              slidesToShow: 1,
              slidesToScroll: 1,
            }
          },
        ],
        autoplay: true,
        autoplaySpeed: 2000,
        speed: 6000,
        cssEase: 'ease',
      }
    }
  }

e.stopPropagation() on click event

Please tell me why the e.stopPropagation() function does not work?

$(document).on("click", ".el", function(e) {
  e.stopPropagation();
  alert(2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="el" onclick="alert(1)";>Click</div>

Close-On-Click-Away not working when MUI custom field is inside component

In my React component I have a sidebar menu, CustomizeComponentSidebar that in turn contains several other custom html tags. One of them is MUI’s Multiple Select. I made a close-on-click-outside functionality for using useRef. Everything is fine except if I click on MUI’s Multiple Select field, it traces the click as outside the component and closes it. I also tried using MUI’s ClickAwayListener instead, with the same result. Any help appreciated

    const handleClickOutside = (event) =>
    ref.current && !ref.current.contains(event.target) && resetSidebar();

useEffect(
    () => {
        document.addEventListener("click", handleClickOutside, true);

        return () => document
            .removeEventListener("click", handleClickOutside, true);
    },
    [customizeComponentMenu.open]
);

……..

                    <div ref={ ref } className="position-absolute">
                        <CustomizeComponentSidebar
                            props={ props }
                    />
                   </div>

///SelectField looks like this

    return (
    <div>
        <FormControl sx={ { m: 1, width: 300 } }>
            <InputLabel id="demo-multiple-name-label">Select</InputLabel>
            <Select
                labelId="demo-multiple-name-label"
                id="demo-multiple-name"
                multiple={ props.configuration.multipleOptions }
                value={ getValue() }
                onChange={ handleChange }
                input={ <OutlinedInput label="Option" /> }
                MenuProps={ MenuProps }
            >
                { options.map((option) => 
                    (
                        <MenuItem
                            key={ option }
                            value={ option }
                            style={ getStyles(option, optionName, theme) }
                        >
                            { option }
                        </MenuItem>
                    ))
                }
            </Select>
        </FormControl>
    </div>
);

};

export default SelectField;

Cannot read properties of undefined (reading ‘forEach’) when no Array

I got this error :

Cannot read properties of undefined (reading ‘forEach’)

if(response.Response) {
      $('#list').html('');
      response.Search.forEach(function(movie) {        
        var movieContent;
        if(movie.Poster === 'N/A') {
          movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year}</li>`;
        } else {
          movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year} <a href="${movie.Poster}" class="btn btn-xs btn-primary" id="poster-link">Poster</a></li>`;
        }
        $('#list').append(movieContent).hide().fadeIn(); 
      });
    }
  });

The error comes when I put less than 3 letters in my search input and the output is

{Response: ‘False’, Error: ‘Too many results.’}

otherwise, from 3 letters the response is correct

{Search: Array(2), totalResults: ‘2’, Response: ‘True’}

I understand that this is because there is no Array in the response but how can I prevent this error?

on function after load jquery

Please tell me, there are 2 pages: index.html, load.html.

There is a script that is included in index.html which contains the $('div').on() function for elements that are on the load.html page.
After calling the $('.el').load('load.html') function, the events stop working. How beautifully can you make the events fire even after updating the page with elements?

P.S. hanging a function on an element and loading a script in the load.html page is not suitable, the script is the same on the index.html page.

How to give TypeORM Datasource from middleware to Nestjs

I have a middleware that create a connection from TypeORM to the database wanted, at each request to the api.

I would like to link the created Datasource connexion to Nestjs and use the Datasource from the Nestjs injections like :

@InjectDatasource()

The only things I could have done was to pass the TypeORM Datasource has a part of request so the controllers could use it.

Is there a way to do it from the Nestjs injection directly ? It would be better and easier for the developpers.

Thanks in advance.

node.js Readable process?

i’m studying node.js stream module

and there’s one problem i can’t solve by myself.

const fs = require('fs')
const {Readable} = require('node:stream')

const rs = new Readable({
  read(size) {
    if(this.count < 3){
      console.log('read: ', this.count)
      this.push(`data${this.count + 1}t`)
      this.count++
    }else{
      console.log('read: null')
      this.push(null)
    }
  }
});
const ws = fs.createWriteStream('./big.txt')
rs.count = 0
rs.on('data', (c) => console.log('[data event]'))
rs.pipe(ws);

and big.txt is like this as i expected

data1 data2 data3

but the console.log is like this and this is not what i expected

read: 0
read: 1
[data event]
read: 2
[data event]
read: null
[data event]

i expected this

read: 0
[data event]
read: 1
[data event]
read: 2
[data event]
read: null

why is it different?
can anybody let me know? thanks