Passing data to Child Component ReactJS

Background

I am working on a website where I have parent components and child components. The snippet below is a Google Map wrapper and a map component.

Code

import React, { useEffect, useState, useRef } from "react";

// reactstrap components
import { Card, Container, Row } from "reactstrap";

// core components
import Header from "components/Headers/Header.js";
import LocationSearchInput from "../../components/Places";
import { useAuthenticator } from "@aws-amplify/ui-react";
import * as queries from "../../graphql/queries";
import { API, graphqlOperation } from "aws-amplify";
import { geocodeByAddress, getLatLng } from "react-places-autocomplete";
import * as _ from "lodash";
import { collapseTextChangeRangesAcrossMultipleVersions } from "typescript";

const MapWrapper = (data, loc) => {
  const mapRef = useRef(null);
  console.log("child props", data, loc);

  console.log("foo child", loc);
  // THIS WONT WORK BECAUSE WHEN IT FIRST LOADS ITS EMPTY
  // geocodeByAddress(loc[0].HomeLocation)
  //     .then(results => getLatLng(results[0]))
  //     .then(latLng => console.log('Success', latLng))
  //     .catch(error => console.error('Error', error))

  useEffect(() => {
console.log("child mount");
    let google = window.google;
    let map = mapRef.current;
    let lat = "40.748817";
    let lng = "-73.985428";
    const myLatlng = new google.maps.LatLng(lat, lng);
    const mapOptions = {
      zoom: 12,
      center: myLatlng,
      scrollwheel: false,
      zoomControl: true,
      styles: [
        {
          featureType: "administrative",
          elementType: "labels.text.fill",
          stylers: [{ color: "#444444" }],
        },
        {
          featureType: "landscape",
          elementType: "all",
          stylers: [{ color: "#f2f2f2" }],
        },
        {
          featureType: "poi",
          elementType: "all",
          stylers: [{ visibility: "off" }],
        },
        {
          featureType: "road",
          elementType: "all",
          stylers: [{ saturation: -100 }, { lightness: 45 }],
        },
        {
          featureType: "road.highway",
          elementType: "all",
          stylers: [{ visibility: "simplified" }],
        },
        {
          featureType: "road.arterial",
          elementType: "labels.icon",
          stylers: [{ visibility: "off" }],
        },
        {
          featureType: "transit",
          elementType: "all",
          stylers: [{ visibility: "off" }],
        },
        {
          featureType: "water",
          elementType: "all",
          stylers: [{ color: "#5e72e4" }, { visibility: "on" }],
        },
      ],
    };

    map = new google.maps.Map(map, mapOptions);

    const marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      animation: google.maps.Animation.DROP,
      title: "Light Bootstrap Dashboard PRO React!",
    });

    const contentString =
      '<div class="info-window-content"><h2>Light Bootstrap Dashboard PRO React</h2>' +
      "<p>A premium Admin for React-Bootstrap, Bootstrap, React, and React Hooks.</p></div>";

    const infowindow = new google.maps.InfoWindow({
      content: contentString,
    });

    google.maps.event.addListener(marker, "click", function () {
      infowindow.open(map, marker);
    });
  }, []);

  console.log("child render");
  return (
    <>
      <div
        style={{ height: `600px` }}
        className="map-canvas"
        id="map-canvas"
        ref={mapRef}
      ></div>
    </>
  );
};

const Maps = () => {
  const [foo, setFoo] = useState([]);

  const { user, signOut } = useAuthenticator((context) => [context.user]);
  // console.log("user map", user);

  const [pin, setPin] = useState([]);

  const fetchFoo = async () => {
    console.log(user.attributes.email);
    try {
      const todoData = API.graphql(
        graphqlOperation(queries.listEmployees, {
          filter: {
            Email: {
              eq: user.attributes.email,
            },
          },
        })
      ).then((response) => {
          console.log("fetch resp", response);
          setFoo(response.data.listEmployees.items);
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      console.log("error facing Todos:", err);
    }
  };
  console.log("parent render");

  useEffect(() => {
    console.log("parent mount")
    fetchFoo();
  }, []);

  var json = [{a: "a", b:"b"}]

  return (
    <>
      <Header />
      {/* Page content */}
      {/* {foo} */}
      <Container className="mt--7" fluid>
        <Row>
          <div className="col">
            {/* <LocationSearchInput /> */}
          </div>
        </Row>
        <Row>
          <div className="col">
            <Card className="shadow border-0">
              {/* <> */}
              <MapWrapper data={json} loc={{foo}}/>
              {/* </> */}
            </Card>
          </div>
        </Row>
      </Container>
    </>
  );
};

export default Maps;

Output

console output #1
console output #2

Problem

The child component when it first reads the data it is empty but it is populated the second time it is loaded. I have tried to tweak the useEffect to work but the only difference I get is it’ll perform an infinite loop if I remove the empty array.

I have an RESTFul API that renders HTML through a GET endpoint. How can I display this html in my wordpress website with custom header from the form?

I’m using a nocode API that returns some HTML based on some parameters in the URL when the user makes a GET request. I’d like to improve the user experience and have a form like a contact 7 form that can map user input for each form field in the call to API.

For example form would look like following:

Name: Todd
Email: [email protected]
Key: zjdHSDFHSDFHSDFS

My API is example https://api.com/endpoint/v1/

When the user enters name, email and key I need to make a call like this:

My API is example https://api.com/endpoint/v1?name={name}&email={email} with the Key field passed in as a header (X-BLOBR-KEY: {key})

I couldn’t figure out how to do this with javascript or with a wordpress plugin.

SWUP works on initial page load, fails on first request, and succeeds on every subsequent request?

I am using swup.js with a Laravel project that also uses Livewire. I almost have it working right, but I’m getting a bizarre error.

Here’s the situation:

  • The first page loads perfectly fine. Everything works as intended.
  • Once you click a swup link and “load” your next page, everything fails. No Javascript will be executed, Livewire can’t function, either.
  • But, once you make your second trip to that page by clicking the link, it’s as if everything has loaded correctly in cache and is working – Javascript, Livewire, everything seems fine.

I can’t figure out why this is happening. Here is my setup + code:

app.js:

import Swup from 'swup';
import SwupScriptsPlugin from '@swup/scripts-plugin';
import SwupLivewirePlugin from '@swup/livewire-plugin';

const swup = new Swup({
    cache: false,
    debugMode: true,
  plugins: [
      new SwupLivewirePlugin(),
      new SwupScriptsPlugin({
          head: true,
          body: true,
          optin: true
      }),
  ]
});

My master blade template, layouts.app.blade.php:

...
<livewire:scripts />

<main id="swup" class="">
    @yield('content')
    <script data-swup-ignore-script src="{{ asset('js/app.js') }}"></script>
    @yield('js')
</main>
...

My home.blade.php file:

@extends('layouts.app')

@section('content')
<section class="mt-24 mb-32 py-12 relative">
  <div class="max-w-7xl mx-auto px-4">
        <div class="flex flex-col space-y-3 lg:w-1/2 w-full ml-auto">
          <span class="block text-3xl xl:inline">I'm a...</span>
          <span id="role" class="block text-indigo-600 xl:inline text-7xl">Hymn Writer</span>
        </div>
      </div>
    </div>
  </div>
</section>
@endsection


...

@section('js')
<script data-swup-reload-script src="https://cdnjs.cloudflare.com/ajax/libs/TypewriterJS/2.17.0/core.min.js" integrity="sha512-o6alMAMTI5qAmVC1UvuRPgTl3UOOkP8NZ6212+rq1Oslsuy8Owt9r5Z0Wu0LNxpw/Q8N8ToGiyovHV+kyOulxg==" crossorigin="anonymous"></script>

<script data-swup-reload-script>
  function init() {
    var role = document.getElementById('role');

    var typewriter = new Typewriter(role, {
        loop: false,
    });

    typewriter.typeString('Hymn Writer')
        .pauseFor(2400)
        .deleteAll()
        .typeString('Father')
        .pauseFor(2400)
        // ...etc
        .start();
  }
  init();

  document.addEventListener('swup:contentReplaced', init);
</script>
@endsection

I can’t figure out why it’s working on initial page load and subsequent link clicks but not the very first time the link is clicked when starting from another page? What is going on here?

Functional Programming, JavaScript, chaining, and no external library to calculate average on array of objects

I want to use Functional Programming, JavaScript, chaining, and no external library to reduce an array of objects to the average of the grade of the element with the condition that enrolled >1.
So far I’m able to calculate the sum under the requested condition
But how can I calculate the average? ( Note that I want to use Functional Programming, JavaScript, chaining, and no external library)

Here is what I have come so far …

let enrollment= [
    {enrolled: 2, grade:100},
    {enrolled: 2, grade:80},
    {enrolled: 1, grade:89}
]

const sum = (accumulator, curr) => accumulator + curr.grade;
const average = (total,arr) =>  total/arr.length

enrollment
    .filter( elem => elem.enrolled >1)
    .reduce(sum,0)

Now how do I chain the average function to the above block of code?
Thanks in advance

getting the names of customers who id is more than 1500? From sorting this array…I.E homework question

Here is the problem: recieve an array produce an array with the persons name and number of products id above 1500 and if they are below 1500 (1436 – 1600 ) you cant include them.

 customers = [ { name :" stacy "  
        age : "45"
        products ordered id : "1500 - 1600"
       }
       name : "ashley"
       age : "87"
       products ordered id : "1455 - 1660"
      }
       name: " gabrielle"
       age : "67"
       products orderes id : "1568 -1600"

      }

I need to return there name of the customers who order is more than > 1500
This is a homework question.. the format may be off but this is exactly how they gave it to me.

Grab multiple properties of a JSON

I’m working with a large JSON file that looks like this:

{
    "name": "Superproduct",
    "description": "Enjoy this amazing product.",
    "brand": "ACME",
    "categories": [
      "Ball",
      "Soccer Ball",
      "Beach Ball"
    ],
    "type": "Online product",
    "price": 50,
    "price_range": "50 - 100",
    "image": "someImageURL",
    "url": "SomeProductURL",
    "free_shipping": true,
    "popularity": 10000,
    "rating": 2,
    "objectID": "1234"
  }

I am trying to access every object with the Ball category, so that I can add a discount to that specific item. I realized that every object can have multiple variations of the word Ball in the category array.

Is there a way I can target the word ball in the array, so that I can add that to an array and apply the discount to every product with said criteria?

This is what I have so far, but I’m not sure if this is the best way, or if there’s a better way to accomplish what I’m trying to do:

async function setDiscount() {

    let discountedRate = 0.5;
    
    fetch('products.json')
    .then(res => res.json())
    .then(data => {for (let i = 0; i < data.length; i++) {
        if (data[i].categories[i] == "Ball") {
            data[i].price -= (data[i].price * discountedRate);
        }
    }});

    
}

setDiscount();

P.S.: I’m a newbie.

Express/mongoose returns empty array when trying to get request

I am trying to get the list of books from the database. I inserted the data on mongoose compass. I only get an empty array back.

//Model File
import mongoose from "mongoose";

const bookSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
releasedDate: {
type: String,
required: true,
},
});

const Book = mongoose.model("Book", bookSchema);
export default Book;


//Routes file
import express from "express";
import Book from "./bookModel.js";
const router = express.Router();

 router.get("/", async (req, res) => {
   const books = await Book.find({});

   res.status(200).json(books);
 });

Vue Router not scolling to correct hash location

When clicking a link on the app, the Router does not scroll to the correct hash location given. But it DOES scoll. The scroll is always about 1 element to high on the page. For example, if my page is this:

<template>
    <div id="div1">Div1</div>
    <div id="div2">Div2</div>
    <div id="div3">Div3</div>
    <div id="div4">Div4</div>
</template>

Then if i click a link that goes to hash “div3” it will scroll me so the top of the page is sitting at div2. Only a very few selec elements are scrolled to corrently. Is there a reason for this? Setting page margins?

Router code:

const router = new VueRouter({
  routes,
  mode: 'history',
  base: "/",
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
        return {
          selector: to.hash,
          behavior: 'smooth',
        }
    } else {
        return { x: 0, y: 0 }
    }
  }
})

Example of code that calls the hash routing:

if (item.title == "Mission") {
                            router.push({name: 'Explore', hash: '#mission-statement'});
                        } else if (item.title == "Our Story") {
                            router.push({name: 'Explore', hash: '#our-story-container'});
                        } else if (item.title == "Shared principles") {
                            router.push({name: 'Explore', hash: '#shared-principles-container'});
                        } else if (item.title == "Volunteer Opportunities") {
                            router.push({name: 'Explore', hash: '#volunteer-container'});
                        } else if (item.title == "Gallery") {
                            router.push({name: 'Explore', hash: '#galleries'});
                        } else if (item.title == "Living") {
                            router.push({name: 'Explore', hash: '#living-container'});
                        } else if (item.title == "Contact Us") {
                            router.push({name: 'Explore', hash: '#contact-us-container'});
                        } else {
                            router.push("/explore")
                        }

Angular this.useraccount.next(user) then Error An argument of type ‘HttpResponse’ is not allowed against a balance of ‘Useraccount’

I put this.useraccountsubject(user) to interpolate information on login, but I get an error.
ErrorType: this.useraccount.next(user) then Error An argument of type ‘HttpResponse’ is not
allowed against a balance of ‘Useraccount’

auth service.ts

export class AuthService {

  private useraccountSubject: BehaviorSubject<Useraccount>;
  public user: Observable<Useraccount>;
  isLoggedIn = new BehaviorSubject(false);

   constructor(private http:HttpClient, private router:Router){
   this.useraccountSubject = new BehaviorSubject<Useraccount>(null as any);
   this.user = this.useraccountSubject.asObservable();

  if(sessionStorage.getItem("USER")){ 
  const user =sessionStorage.getItem("USER");
  if(user){
    this.useraccountSubject.next(JSON.parse(user));
  }
 }
}
private handleError(err: HttpErrorResponse) {
if (err.status === 200) {
  console.error('Error:',err.error.data)
} else {
  console.error(`Backend error ${err.status}`)
}
return throwError(err);
}
private handleErrorsingup(err: HttpErrorResponse) {
if (err.status === 201) {
  console.error('Error:',err.error.data)
} else {
  alert('faild');
  console.error(`Backend error ${err.status}`)
}
return throwError(err);
}

login(username:string,password:string){ 
  const params = new FormData();
  params.append('username', username);
params.append('password', password);
return this.http.post<any>(`${baseUrl}/signin/`, params, {observe:'response', withCredentials: true})//withCredentials:true
.pipe(map(user=>{
 
  catchError(this.handleError)
//Here is the code section in question !!
 this.useraccountSubject.next(user);
  sessionStorage.setItem("USER", JSON.stringify(user));
  this.isLoggedIn.next(true);
  return user;
}))
}
 signup(email:string,password:string,name:string ){
const params = new FormData();
params.append('email', email);
params.append('password', password);
params.append('name', name);
return this.http.post<any>(`${baseUrl}/signup/`, params, {observe:'response', withCredentials: true})
.pipe(
  catchError(this.handleErrorsingup)
)
}
logout(){
 return this.http.post<any>(`${baseUrl}/signout/`, {}).subscribe(
  response=>{
    this.isLoggedIn.next(false);
    this.useraccountSubject.next(null as any)
    sessionStorage.clear(); 
    this.router.navigate(['login']) 
  }
)
}
public get useraccountValue(): Useraccount{
return this.useraccountSubject.value;
 }
}

The format ‘HttpResponse’ does not have id, username, name, password, email attributes in the format ‘Useraccount’.
Useraccount.ts

export class Useraccount{
id:string ='';
username: string='';
name:string='';
password:string='';
email:string='';
}

I have for that format Useracount.ts

Javascript setting image source in api call

Ive Read a couple Examples on how to set img src from js, but when i try to implement them it doesnt work. the ways I have tried are but neither of them seem to work.

document.getElementById("currentTemp").innerHTML = "Current Temp: " + currentData.list[1].main.temp + "°F";

const currentImg = document.getElementById("currentImg");

currentImg.src = "https://openweathermap.org/" +currentData.list[1].weather[0].icon + ".png";

//document.getElementById("currentImg").src =  currentData.list[1].weather[0].icon;

Reverse FileReader – Reassamble file from string

I get the file to a string:

const r = new FileReader()
r.readAsText(file, 'UTF-8')
r.onload = (evt) => {
     this.file = evt.target.result
};

After upload a Zip, Text or Image file my string looks like: data:text/plain;base64,VTJGc.....

How can i reverse the readAsText and get a downloadable file?

How to download video from this link using javascript and html

I want a button or link that can download or save the video from this type of link.

I am try this code but when i click on the link it Doesn’t save the video to device but open the HTML5 video play.

<a href="https://rr4---sn-gwpa-pmjz.googlevideo.com/videoplayback?expire=1645511732&ei=1C8UYom5FM_hhwaks43wAg&ip=44.201.92.140&id=o-ADrMmRDRPsO5co_3WapfdhpNmpy-aI0as8aimBEQjBQq&itag=22&source=youtube&requiressl=yes&vprv=1&mime=video%2Fmp4&ns=kLaa53VRRBZK3BdiZax7kSwG&cnr=14&ratebypass=yes&dur=2264.200&lmt=1611181733718538&fexp=24001373,24007246&c=WEB&txp=5535432&n=O38Bzkrt7cdpAQ&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cvprv%2Cmime%2Cns%2Ccnr%2Cratebypass%2Cdur%2Clmt&sig=AOq0QJ8wRAIgJ_Xr0KgAgeaggpUHe4w2PVpJW-JLpXvgIRR6xAQ0G8sCIGQt4ioUXn3fFc2vxcW_JvBjcgcib-4jUPIFVRPPThGa&redirect_counter=1&rm=sn-p5qeer7s&req_id=e8aad143a0eba3ee&cms_redirect=yes&ipbypass=yes&mh=Bb&mip=2409:4051:4e9b:59a7:9de2:5b9:ce83:ae30&mm=31&mn=sn-gwpa-pmjz&ms=au&mt=1645489725&mv=m&mvi=4&pl=48&lsparams=ipbypass,mh,mip,mm,mn,ms,mv,mvi,pl&lsig=AG3C_xAwRgIhAIgzEczDyvfbp0AiKfOuTbBJc6NiRoFMCOkb7MaXSwRUAiEA4jiQLlLTaHMYV4NdBqw8BgXpBjNx8qxfUM3CY8KA07Q%3D" download="myvideo.mp4"

Can someone tell me the the correct way to do that?

FIle.WriteAllText not adding text

I have html/javascript code that I am trying to write in c sharp on a windows forms application. It looks like this

<html>
<body>
<button onclick = "Clicker()">Click Me </button>
<script src = "clicker.js"></script>
</body>
</html>

here is what clicker.js looks like


function Clicker(){
    document.body.innerHtml += "adding to document";
}

I was able to setup the onclick event in c sharp, but when I click the button, the file that I am writing to is not continuing to add “adding to document” to the document. It only does it once. Here is what the event looks like

void ButtonClick(object k, EventArgs e){
   File.WriteAllText(location,"adding to document");
}

Why is this not working?

why are my if/else statements not outputting the equations being used, not sure what I am doing wrong?

in my introductory coding class, we are currently working on if/else statements. We do scripting within our html document, and I have provided the code I have been working on down below. I am very confused about why my information is not being outputted when I run my code. Essentially, we have to use if/else statements for if a customer purchases more than 150 clubs, and in our code we need to show an equation for if they input a number greater than 18 for cost per club. My if/else statements reflect this, and I have also checked my code for grammar mistakes but I am not finding any. Any help with this issue would be extremely appreciated! Thank you!

This part is what I have in my html:

<form id="userInformationEntry">
    <p><label for="txtPutterQuantity">How many golf clubs would you like to 
    order:</label>
        <input type="text"  id="txtPutterQuantity"  maxlength="100"  
        size="50"></p>
    <p><label for="txtPutterCost">How much is the cost to be paid per golf 
    club:</label>
        <input type="text"  id="txtPutterCost"  maxlength="100"  size="50"> 
    </p>
    <p><label>Would you like to be added to the mailing list?</label></p>
    <p><label for="radFirstChoice">Yes</label>
        <input type="radio"  id="chkYes"  name="optionChoice1" 
        checked="checked"></p>  
    <p><label for="radSecondChoice">No</label>
        <input type="radio"  id="radSecondChoice"  name="optionChoice2"></p>
    <p><input type="button"  value="Submit Order Information"  
    onclick="submitOrderFunction"></p>
    <br>
    <br>
</form>

<div id="orderInformationResults">
</div> <!--end of orderInformation div-->

This part is what I have in my script:

function submitOrderFunction()  {
    var golfClubAmount, golfClubCost;
    var deductionAmount;
    var totalAmount;
    var truePrice;
    var resultsString;

    golfClubAmount = document.getElementById("txtPutterQuantity").value;
    golfClubCost = document.getElementById("txtPutterCost").value;
    golfClubAmount = parseInt(golfClubAmount);
    //Only whole numbers would be enetered because you can't give half or a 
    quarter of a club
    golfClubCost = parseFloat(golfClubCost);
    //Decimals may be used if someone will be paying some change as well (ex: 
    $21.50)
    totalAmount = (golfClubCost - 18) * golfClubAmount;
    totalAmount = totalAmount.toFixed(2);
    totalAmount = parseFloat(totalAmount);

    //the 10% off deduction exclusively for orders of 150 clubs or more
    if (golfClubAmount > 150 )
    {
        deductionAmount = totalAmount * .90;
    }
    else
    {
        deductionAmount = 0;
    }

    truePrice = totalAmount + deductionAmount;
    truePrice = truePrice.toFixed(2);
    //We need to limit to two decimal places
    truePrice = parseFloat(truePrice);
    //We will be working with decimals, so parseFloat seems like the better 
    function to use

    resultsString = "For an order of " + golfClubAmount + " clubs, at $" + 
    golfClubCost + " per club, you will earn $" + truePrice + "."
    document.getElementById("orderInformationResults").innerHTML = 
    resultsString;
}

If anyone can lead to what I am doing wrong, I would greatly appreciate it, or if anyone has any insights, thank you!