React: infinite render on useEffect only when using an internal component

I have this following code Parent and DataFilter.

Parent.js

const Parent = () => {
  const [filteredData, setFilteredData] = useState()

  ...

  const Filter = () => {
    return (
      <div>
        <h2>Filter your data</h2>
        <DataFilter data={filteredData} updateFilter={setFilteredData} />
        <Result data={filteredData} />
      </div>
    )
  }


  return (
    <div>
      <h1>Header</h1>
      <Filter />
    </div>
  )
}

DataFilter.js

const DataFilter = ({ data, updateFilter }) => {
  const [name, setName] = useState(defaultFilters.name)
  const [age, setAge] = useState(defaultFilters.age)
  
    ...(filter logic using data)
  
  useEffect(() => {
    updateFilter({ name, age })
  }, [name, age])
}

Here, I receive Maximum update depth exceeded aka infinite rendering, which I kind of know why.

  1. Parent and DataFilter get rendered
  2. DataFilter triggers Parent‘s setFilteredData in useEffect
  3. Parent gets rerendered because of setFilteredData
  4. Parent being rerendered triggers child component DataFilterrerender
  5. Repeat from No.2

But, this only started happening only after I extracted Filter in ‘Parent’ as an inner component… I know it’s weird but it was working fine when Parent was like this


const Parent = () => {
  const [filteredData, setFilteredData] = useState()

  ...

  return (
    <div>
      <h1>Header</h1>
        <div>
          <h2>Filter your data</h2>
          <DataFilter data={filteredData} updateFilter={setFilteredData} />
          <Result data={filteredData} />
        </div>
    </div>
  )
}  

Does anyone know why the infinite rendering happens only when it’s as an inner component?

I tried using useCallback for setFilteredData but it didn’t work.

Also what should I do to prevent the infinite render if I want to keep it as a component rather than directly writing everything in a return()?

Server Side Rendering Every Page in Gatsby

We’re using Gatsby as a decoupled WordPress frontend, and according to a client’s ad network, their API requires the entire DOM to refresh on page load. I’m experimenting with whether it would be worthwhile to use server side rendering to achieve this or if it negates all the benefits of Gatsby anyway.

I’m not sure how to achieve this, however. All page data is being pulled from the GraphQL data layer. Gatsby’s docs indicate that runtime GraphQL queries are not supported, so it seems getServerData() won’t work here.

I’ve been looking at the SSR API, and I’m wondering if simply using wrapPageElement in gatsby-ssr.js will cause all pages to server side render. Or would I need to use wrapRootElement if I want the entire DOM to refresh on page load?

I just need a push in the right direction, as the docs are a little unclear to me about this.

arcgis js – disable transforming shape on select

I am trying to figure out how to disable manipulation of shapes/objects once they have been drawn using the sketch widget.

My current code is very simple:

const graphicsLayer = new GraphicsLayer();

    const webmap = new WebMap({
      portalItem: {
       // secret api key //
      },
      layers: [graphicsLayer]
    });

    const view = new MapView({
      container,
      map: webmap,
      zoom: 4
    });
    const sketch = new Sketch({
          layer: graphicsLayer,
          view: view,
          creationMode: "update",
          defaultUpdateOptions: {
            enableRotation: false,
            enableScaling: false,
            enableZ: false,
            toggleToolOnClick: false,
          }
        });
    
        view.ui.add(sketch, "top-right");

I essentially want to achieve the following:

  • Draw the object
  • prevent object on being transformed/scaled/rotated etc.
  • Bonus points: Have the object emit its data on select (e.g. .on(“click”, (e) => { dosomething })

I have managed to do first and part of second, but i am still able to move the drawn object around.

Dynamically manipulating arrays in Javascript/ React Native Calendars Agenda

I have data loaded from Firebase that loads reserved time slots by time and user ID like this

firebase
            .firestore()
            .collection(`Mayra`)
            .get()
            .then((querySnapshot) => {
              querySnapshot.forEach((doc) => {
                console.log("doc data loaded", doc.data());


doc data loaded Object {
"userDataJson": Object {
"15:00pm a 16:00pm": "oeXjttjPnPhkn6xIqhqsQhJvQM92",
},
}
doc data loaded Object {
  "userDataJson": Object {
    "11:00am a 12:00pm": "oeXjttjPnPhkn6xIqhqsQhJvQM92",
  },
}
doc data loaded Object {
  "userDataJson": Object {
    "10:00am a 11:00am": "oeXjttjPnPhkn6xIqhqsQhJvQM92",
    "17:00pm a 18:00pm": "oeXjttjPnPhkn6xIqhqsQhJvQM92",
  },
}
doc data loaded Object {
  "userDataJson": Object {
    "11:00am a 12:00pm": "oeXjttjPnPhkn6xIqhqsQhJvQM92",
    "19:00pm a 20:00pm": "oeXjttjPnPhkn6xIqhqsQhJvQM92",
  },
}

and the doc.id from firebase are the dates loaded like this

console.log("doc id loaded", doc.id);
doc id loaded 2021-12-22
doc id loaded 2021-12-23
doc id loaded 2021-12-24
doc id loaded 2021-12-28

I am also loading User data in a different collection like this

const list = [];
          await firebase
            .firestore()
            .collection("Members")
            .get()
            .then((querySnapshot) => {
              querySnapshot.forEach((doc) => {
                const { FirstName, LastName, Age, Cell, userId } = doc.data();
                list.push({
                  key: doc.id,
                  Name: FirstName,
                  Last: LastName,
                  Cell: Cell,
                  Age: Age,
                  userId: userId
                });
              });
            });

Using react-native-calendars {Agenda} my goal is to create the object array dynamically so that the userID is matched and so that the information can appear like this

const goalExample = {
    
    "2021-11-24": [
      { time: "9:00AM - 10:00AM", name: "Gabo"},
      { time: "10:00AM - 11:00AM", name: "Carlos"},
      { time: "11:00AM - 12:00AM", name: "Jeff" },
    ],
    "2021-11-25": [
      { time: "8:00AM - 9:00AM", name: "Kiki"},
    ],
    "2021-11-26": [],
    "2021-11-27": [
      { time: "10:00AM - 11:00AM", name: "Diego" },
    ],
  };

So far I’ve managed to make it to

list.push(doc.id);

                list.forEach((day) => {
                  mark[day] = [
                    {
                      time: "9:00AM - 10:00AM",
                      name: "carlos",
                    },
                  ];
                });

but cannot figure out how to load the data dynamically. Requesting help or other suggestions please.

How do I put the bordered text underneath the nav-menu text?

I did a round bordered text right next to the nav-menu. I having issues on how will I put the text underneath the texts. Refer to the image below.

enter image description here

I wanted to put the coming soon texts underneath the COMPANY and CONTACT menu (I don’t mean doing a sub-menu) Below are the code I did for doing this.

<el-menu-item index="4">{{ $t("Tabnav.nav_n") }}</el-menu-item>
<div class = csoon1>
  <span class = text>COMING SOON</span>
</div>
<el-menu-item index="4">{{ $t("Tabnav.nav_n") }}</el-menu-item>
<div class = csoon2>
  <span class = text>COMING SOON</span>
</div>

.text {
  border: 2px solid #00db99;
  border-radius: 10px;
  background-color: #00db99;
  font-size: 13px;
}

Is it possible to put the round bordered text underneath? If not I’ll try make it stick next to the menu text and get them compressed.

How to verify Google Earth Link within a form using Regex

I am trying to validate that the link that I am entering into a form is a valid Google Earth link however, its accepting all link apart from google earth link; here is the code for my js script that I am trying to do this with.

 validate: function() {
        var inputFields = $('input[type=text]');
        var notAvailable = $('#op_not_available');
        var GoogleEarthUrl = $('#op_gooogle_earth_link').val().trim();
        var twitterUrl = $('#op_twitter_url').val().trim();
        var urlRegex = /^(ht|f)tps?://[a-z0-9-.]+.[a-z]{2,4}/?([^s<>#%",{}\|\^[]`]+)?$/;
        var GoogleEarthRegex = /google.com/;
        var twitterRegex = /twitter.com/;
        if (!notAvailable.prop("checked")) {
          $("#not_available").val('off');
          for (var i = 0; i < inputFields.length; i++) {
            if (!$(inputFields[i]).val().trim().length) {
              return 'Please enter all fields';
            }
          }
          if ((GoogleEarthUrl !== '-') && !(urlRegex.test(GoogleEarthUrl) && GoogleEarthRegex.test(GoogleEarthUrl))) {
            return 'Please enter a valid Google Earth URL';
          }
          if ((twitterUrl !== '-') && !(urlRegex.test(twitterUrl) && twitterRegex.test(twitterUrl))) {
            return 'Please enter a valid Twitter Url';
          }
        }else{
          $("#not_available").val('on');
        }
        return;
      }
    };

JavaScript: Cannot read properties of undefined reading “size”, even though “size” is already defined

This returns the undefined error:

function spawnCreature() {
    var creature = {
        size: 10,
        x: (Math.random() * (land.width - (creature.size / 2)) + (creature.size / 2)),
        y: (Math.random() * (land.height - (creature.size / 2)) + (creature.size / 2)),
        dirX: 0,
        dirY: 0,
    }
    creatureArray.push(creature);
}

Despite that, I tried to fix it with this:

function spawnCreature() {
    var creatureSize = 10;
    var creature = {
        size: creatureSize,
        x: (Math.random() * (land.width - (creatureSize / 2)) + (creatureSize / 2)),
        y: (Math.random() * (land.height - (creatureSize / 2)) + (creatureSize / 2)),
        dirX: 0,
        dirY: 0,
    }
    creatureArray.push(creature);
}

But all that happened was the creature wasn’t anywhere in the land.

Trying to do a simple calculation with a button

For a project I’m trying to make a type of calculator. Where I’m having trouble with is changing my button value to what I want the calculation output to be

here is a small portion of my html because its a big table but I’m trying to make a button like this one for all of them… enter image description here

here is the function I made for the calculations enter image description here

lastly, this is my web page so far
enter image description here

again, my goal is to change the “press” to the calculated value. Thank you! I hope this makes sense

Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. ERROR HAPPENS SOMETIMES?

To preface, this is the error.

Promise { <pending> }
nodejsprojectnode_modulesfirebase-adminlibutilserror.js:44
        var _this = _super.call(this, errorInfo.message) || this;
                           ^
FirebaseAppError: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".
    
  errorInfo: {
    code: 'app/invalid-credential',
    message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".'
  },
  codePrefix: 'app'
}

From my understanding, this error is because my params are invalid or something causing an improper initialization of firebase.

Now I am initializing the app like this: initializeApp();.

So the initialization works. When I run a command such as const userInfo = await getAuth().verifyIdToken(authorization); the command works and I get userInfo but when I run a command such as const userInfo = await getAuth().getUser(uuid); it fails.

To my knowledge, the syntax is right and how I’m using the methods are right as well. I’m just unsure why I get an initializeApp error when using one method but not another.

Grouping a base64->buffer hex string by bytes in Javascript?

I’m trying to take a Base64 string, convert it to a hex string and group the output by bytes.

I’d like the output of console.log(bufferString) to be:

03 67 00 cf 04 68 61 00 ff 01 2d

But I’m stuck with this output:

036700cf04686100ff012d

What I’ve got so far…

let request = {
    "PayloadData": "A2cAzwRoYQD/AS0=",
    "FPort": 10
  }

let buffer = Buffer.from(request.PayloadData, 'base64');
let bufferString = buffer.toString('hex');

console.log(bufferString)

Upload pdf file to Firebase Storage, save link to firestore, and can download the pdf file after refresh with Nuxt & Vuetify

How can I upload a file (pdf) to Firebase Storage after a button is clicked and then get the URL (using getDownloadURL() I guess?). After that, whenever a user is logged in the next time, they can download the file on the same page that they upload it.

Currently I managed to upload the file to firebase storage. But I still cannot save the file URL into firestore user’s document. and how can I get the file from firebase so that I can download it later?

I’m using Nuxt.js and Vuetify to do it.

template

                        <v-card>                      
                            <v-file-input
                                outlined
                                show-size
                                counter
                                prepend-icon="mdi-file-upload-outline"
                                :rules="fileRules"
                                accept=".pdf"
                                v-model="ssm" 
                                style="margin: 1rem;">
                            </v-file-input>
                            <v-btn
                                @click="uploadFile">
                                Upload</v-btn>
                        </v-card>

script

    data: () => ({
        fileRules: [
            value => !value || value.size < 2000000 || 'File size should not exceeded 1MB!',
        ],
        ssm: '',
    }),

    methods: {
        saveToFirestore() {
            var data = {
                ssm: this.ssm,
            };
            firestore
                .collection('SubcontractorRegistration')
                .doc(firebase.auth().currentUser.uid)
                .update(data)
                .then(() => {
                    console.log('hello world!')
                })

        },

        uploadFile(file) {
            var uidRef = firebase.auth().currentUser.uid
            const filePath = `SubcontractorRegistration/${uidRef}/${file.name}`;
            const metadata = { contentType: this.ssm.type };
            FirebaseStorage.ref()
                .child(filePath)
                .put(this.ssm, metadata)
                .then(() => {
                    FirebaseStorage
                        .ref()
                        .child(filePath)
                        .getDownloadURL()
                        .then((url) => {
                            this.ssm = url;
                        })
                    this.saveToFirestore();
                    alert("success!")
                })
        }
    },

Just to add, it gives me these 2 error:

  1. Before and after the file is uploaded.
    => [Vue warn]: Invalid prop: custom validator check failed for prop “value”.

  2. after file is upload
    => Uncaught (in promise) FirebaseError: Function DocumentReference.update() called with invalid data. Unsupported field value: a custom File object (found in field ssm in document Subcontractor/9e0b2xsNqrhVn0Coukko3BTHlj93)

Thank you!

Mobile page’s hamburger menu and onClick issue

I hope the title properly described the situation I have.

I am a self-taught learner. Forgive me if the title is incorrect. I would appreciate hearing all your comments.

Symptom:
When I click the hamburger menu on the mobile page’s Navigation bar, it disappears and the menu popup function does not work either.

Here is the code or github

Navbar.js

import React, { Component } from "react";
import { MenuItems } from "./MenuItems";

import "./Navbar.css";

class Navbar extends Component {
    state = { clicked: false };

    handleClick = () => {
        this.setState({ clicked: !this.state.clicked });
    };

    render() {
        return(
            <nav className="NavbarItems">
                
                <h1 className="navbar__logo">
                    <a href="/" style={{ textDecoration: "none"}}>JW</a>
                </h1>

                <div className="menu__icon" onClick={this.handleClick}>
                    {/* for the hamburger (bar) menu animation */}
                    <i className={this.state.clicked ? "fas fa-times" : "fas fa-bars"}></i>
                </div>

                <ul className={this.state.clicked ? "nav__menu active" : "nav__menu"}>
                    {MenuItems.map((item, index) => {
                        return (
                            <li key={index}>
                                <a 
                                    className={item.cName} 
                                    href={item.url}>
                                    {item.title}
                                </a>
                            </li>
                        )
                    })}
                </ul>

            </nav>
        )
    }
}

export default Navbar;

MenuItems.js

export const MenuItems = [
    {
        title: 'Skills',
        url: '#skills',
        cName: 'nav__links'
    },
    {
        title: 'Projects',
        url: '#work',
        cName: 'nav__links'
    },
    {
        title: 'Contact',
        url: '#contact',
        cName: 'nav__links'
    },
]

Navbar.css

    .NavbarItems {
    /* background: linear-gradient(90deg, rgb(110, 94, 254) 0%, rgba(73, 63, 252, 1) 100%); */
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.2rem;

    overflow: hidden;
    background-color: white;
    position: fixed;
    top: 0;
    width: 100%;
}

.navbar__logo {
    color: #fff;
    justify-self: start;
    margin-left: 20px;
    cursor: pointer;
}

.fa__react {
    margin-left: 0.5rem;
    font-size: 1.6rem;
}

.nav__menu {
    display: grid;
    grid-template-columns: repeat(5, auto);
    grid-gap: 10px;
    list-style: none;
    text-align: center;
    width: 70vw;
    justify-content: end;
    margin-right: 2rem;
}

.nav__links {
    color: black;
    text-decoration: none;
    padding: 0.5rem 1rem;
    font-weight: bold;
}

.nav__links:hover {
    background-color: #6D76F7;
    border-radius: 4px;
    transition: all 0.2s ease-out;
}

.fa__bars {
    color: #fff;
}

.nav__links__mobile {
    display: none;
}

.menu__icon {
    display: none;
}

/* mobile start */
@media screen and (max-width: 960px) {
    .NavbarItems {
        position: relative;
    }

    .nav__menu {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 500px;
        position: absolute;
        top: 80px;
        left: -100%;
        opacity: 1;
        transition: all 0.5s ease;
    }

    .nav__menu.active {
        background: #6668f4;
        left: 0;
        opacity: 1;
        transition: all 0.5s ease;
        z-index: 1;
    }

    .nav__links {
        text-align: center;
        padding: 2rem;
        width: 100%;
        display: table;
    }

    .nav__links:hover {
        background-color: #7577fa;
        border-radius: 0;
    }

    .navbar__logo {
        position: absolute;
        top: 0;
        left: 0;
        transform: translate(25%, 50%)
    }

    .menu__icon {
        display: block;
        position: absolute;
        top: 0;
        right: 0;
        transform: translate(-100%, 60%);
        font-size: 1.8rem;
        cursor: pointer;
    }

    .fa-times {
        color: #fff;
        font-size: 2rem;
    }

    .nav__links__mobile {
        display: block;
        text-align: center;
        padding: 1.5rem;
        margin: 2rem auto;
        border-radius: 4px;
        width: 80%;
        background: #4ad9e4;
        text-decoration: none;
        color: #fff;
        font-size: 1.5rem;
    }

    .nav__links__mobile:hover {
        background: #fff;
        color: #6568F4;
        transition: 250ms;
    }

    Button {
        display: none;
    }
}

moment js bug for certain dates. moment.year(x).week(y).endOf(“week”)

I am getting some weird output for certain dates for moment js.
It is only for the dates 1st, 2nd and 3rd of Jan 2022 otherwise it works as expected.
I would expect the same output regardless of the current date.

Any idea why this is occurring?

console.log('Test 2019', moment().year(2019).week(48).endOf("week"));
console.log('Test 2020', moment().year(2020).week(48).endOf("week"));
console.log('Test 2021', moment().year(2021).week(48).endOf("week"));
console.log('Test 2022', moment().year(2022).week(48).endOf("week"));
console.log('Test 2023', moment().year(2023).week(48).endOf("week"));

// With date of device set to the future 3/Jan/2022
Test 2019 Sun Dec 09 2018 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2020 Sun Dec 08 2019 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2021 Sun Dec 06 2020 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2022 Sun Dec 04 2022 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2023 Sun Dec 03 2023 23:59:59 GMT+1300 (New Zealand Daylight Time)

// With date of device set to the today 15/dec/2021
Test 2019 Sun Dec 08 2019 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2020 Sun Dec 06 2020 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2021 Sun Dec 05 2021 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2022 Sun Dec 04 2022 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2023 Sun Dec 03 2023 23:59:59 GMT+1300 (New Zealand Daylight Time)

Paypal button terminates asp .net execution after approved purchase

When I test in the paypal sandbox with smart buttons with generated code from paypal, the purchase is successfully executed. BUT when I redirect to a successful purchase page, the asp .net engine in debug, crashes and then does not execute the server code (like sending successful purchase email to the customer, saving the paypal transaction id in the database, etc).
I tested with window.location, window.location.href, window.location.replace, etc … the page redirects but does not execute the code behind it. Maybe it executes 1 or 2 lines of code and then stops immediately, other times it gets the error that localhost rejects the connection.

By Example, this code not crash (debug and code behind of paypalok.aspx runs ok)

   <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"        
   Inherits="WebApplication8.WebForm1" %>

   <!DOCTYPE html>

   <html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
   <title></title>
   </head>
   <body>
  <form id="form1" runat="server">
    <div>

        <input id="Button1" type="button" value="button" onclick="redirect()" />
    </div>
  </form>

<script>
    function redirect() {
        window.location.href = 'paypalok.aspx';
    }
  </script>
   </body>
   </html>

You can try it yourself and you will see how the asp .net debug stops unexpectedly after the redirection to ‘paypalok.aspx’.

by Example, this code crash:…

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="paypal3.aspx.cs"               
                        Inherits="WebApplication7.paypal3" %>

      <!DOCTYPE html>

       <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
      <title></title>
    </head>
  <body>
     <form id="form1" runat="server">
    <div>
        <div id="smart-button-container">
          <div style="text-align: center;">
            <div id="paypal-button-container"></div>
          </div>
        </div>
    </div>
</form>
    <script src="https://www.paypal.com/sdk/js?client-id=sb&enable-funding=venmo&currency=USD"       
     data-sdk-integration-source="button-factory"></script>
    <script>
        function initPayPalButton() {

      paypal.Buttons({
          style: {
              shape: 'rect',
              color: 'gold',
              layout: 'vertical',
              label: 'paypal',

          },

          createOrder: function (data, actions) {
              return actions.order.create({
                  purchase_units: [{ "amount": { "currency_code": "USD", "value": 0.81 } }]
              });
          },

          onApprove: function (data, actions) {
              window.location.replace ('paypalok.aspx');
          },

          onError: function (err) {
              console.log(err);
          }
      }).render('#paypal-button-container');
  }

        initPayPalButton();

        </script>



  </body>
  </html>

I would appreciate any help

How to detect when key is pressed down in Javascript

I tried:

document.onkeypress = function(event) {
        var key = event.key;
        if( key == 13 ) {
            //code here
        }
    };

and

window.addEventListener

etc. The problem is, it says “window is not defined” or “document is not defined”. I’m not quite sure what to do next as I am a beginner with javascript, please help!