ReactJS Can’t get value of something because not rendered yet, but the function where i get value is called in the rendering

in my React app, I am making a contact form. At the moment I am trying to make it actually send an email, but the thing is that the function where i get the values of an input form (and then send the values in an email), needs to be made before the render of the input form, because the function is called in the render of the input form (in the onSubmit part). But because the elements aren’t rendered yet, i can’t get the values of them. So unless i made a dumb mistake or something, I’m in some sort of loop.

My code:

import logo from './logo.svg';
import './App.css';
import ContactForm from './contactForm.js'
import React from 'react';
import emailjs from '@emailjs/browser';

function sendEmail() {
  const nameValue = document.getElementById('nameInputId').value;
  const emailValue = document.getElementById('emailInputId').value;
  const subjectValue = document.getElementById('subjectInputId').value;
  const messageValue = document.getElementById('messageInputId').value; 
  const templateParams = {
    from_name: nameValue,
    from_email: emailValue,
    subject: subjectValue,
    message: messageValue
  }
  emailjs.send('service_vaofx8t', 'template_vh7z7yf', templateParams, '8r5pAEVrvJN47utJv');
}

class App extends React.Component {
  render() {
    return (
      <ContactForm submit={sendEmail()} />
    );
  }
};



export default App;

Create a new array of boolean values by comparing two arrays with objects

I have a question about creating JavaScript arrays. Here’s what I want to do.

I have two arrays. Each array has object(s) in them.

The first array has exactly 5 objects, each with a key/value pair (id/name). This array will ALWAYS have 5 objects.

Here’s what it looks like…

[
    {
        "id": 1,
        "name": "AnalyticalAdmin"
    },
    {
        "id": 2,
        "name": "Analyst"
    },
    {
        "id": 4,
        "name": "AdminReviewer"
    },
    {
        "id": 5,
        "name": "SystemAdministrator"
    },
    {
        "id": 6,
        "name": "CaseworkSTRTechLeader"
    }
]

The second array will have either…

  1. no objects,

  2. 4 or less objects,

  3. exactly 5 objects.

In the example below, the second array only has one of the 5 objects in the first array…

[
    {
        "id": 4,
        "name": "AdminReviewer"
    }
]

I need to create a third array that has exactly 5 boolean values that are determined by comparing the first two arrays.

For example, based on the first two arrays above, the third array would be…

[false, false, true, false, false]

The reason the third array would look like this is because “AdminReviewer” is the third object in the first array, so the third boolean value in the third array would be true (since it’s a match).

But because the first, second, fourth, and fifth objects in the first array do not exist in the second array, their boolean equivalent in the third array would be false.

To accomplish this, I know I need to either do a compare function on the first two arrays to generate the third one, or I need to do a for loop.

Can anyone help me with this?

my three.js scene is not rendering. not sure why

my main.js file contains :-

import './style.css';
import * as THREE from 'three';


//create scene
const scene = new THREE.Scene();

//arguments - field of view, aspect ratio, last 2 are view frustrum(controls which objects are visible relative to the camera) 
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth/window.innerHeight,
  0.1,
  1000,
);

const renderer = new THREE.WebGLRenderer({
  //which DOM element to use
  canvas: document.querySelector('.canvas'),
});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth / window.innerHeight);
camera.position.setZ(100);


//arguments - radius, widthsegments, heightsegements
const geometry = new THREE.SphereGeometry(15, 32, 16);
//wireframe true to get a better look at its geometry
const material = new THREE.MeshBasicMaterial({color: 0xffff00, wireframe: true}); 

//torus is creating the mesh with geometry and material //mesh = geometry + material
const globe = new THREE.Mesh(geometry, material);

scene.add(globe);

function animate(){
  requestAnimationFrame(animate); //optimized rendering

  //rotation
  globe.rotateOnAxis += 0.01;
  renderer.render( scene, camera );
}
animate();

renderer.render(scene, camera);

and my index.html :-

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Gautam</title>
  </head>
  <body>
    <canvas id="globe">This is the canvas
    </canvas>
    <script type="module" src="./main.js"></script>
  </body>
</html>
 

All that appears on my screen is :-
[what displays on my browser][1]
[1]: https://i.stack.imgur.com/PQmJu.png

I checked and my main.js file is definitely executing, but nothing is rendering on the screen

Jquery Object and Array implementation

I have an Object

let data =  {
        a: 1,
        b: 2,
        c: {
            abc: "ak",
            bcd: "gh",
            cfv: "ht"
        }
    }

then I have variables which I need to show with these object value

   let abc = "first 1", bcd="sec2", cfv="third3" , def="fourth 4", tdf = "fifth 5";

Now the Object will come in API call it can be any of these variable.

How can I match the variable name with the object data.c.(object key) and concatinate their value.

for example the output should be
As we have (abc, bcd, cfv) as our object key then the output would be

first 1ak ==> that is the value of (abc + data.c["abc"])
sec2gh    ==> that is the value of (bcd + data.c["bcd"])
third3ht  ==> that is the value of (cfv + data.c["cfv"])

I tried using Object.keys() method so from this method we will get the object keys in array then how can I match with the variable name –
Object.keys(data.c);
==> [“abc”, “bcd”, “cfv”] (After this how can I proceed to match the variable and show their values?)

Shall I loop throught the object that (data.c)?

Please help me giving some ideas to achieve this implementation.
thank you

TypeError: can’t assign to property “_canInitEmulator” on “[email protected]”: not an object

i am using Firebase but when I try to make a reset pass word link this error ocour’s . What is the reason behind it and how can I solve this error. I have tried using email as a object cause i thought that it would solve the problem .My code:

> ` const handleReset = async () => {

`console.log(email)`

await sendPasswordResetEmail(email);

toast("reset password email send")

}`

FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created – call Firebase App.initializeApp() (app/no-app) – when using sinon

I have a NodeJS application and I’m trying to write some tests. Currently, I’m trying to stub Firebase. Current code:

sinon.stub(firebase, 'initializeApp');
const db = firebase.firestore();

const stub = sinon.stub(db, 'collection').returns({
  doc: sinon.stub().returns({
    set: sinon.stub().returns(null)
  })    
})

I’m trying to stub initializeApp but I’m getting:

FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created – call Firebase App.initializeApp() (app/no-app).

How do I stub initializeApp?

add a triangle icon to the div opening and closing

I have the code where onclick of the link, i am opening and closing the div

here is the code

<div id="opendialog" style="display:none;">
      <div style="width:100%;height:200px;background:grey;"></div>
    </div>

the function

function openx() {
      var x= document.getElementById("opendialog");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }

it works well but how can i add a traingle to the link when clicked it should show a traingle to the div, trying in a way that if the screen is small or bigger, the traingle should be placed properly under the link when clicked and should not be a problem

here is the html i have

<div onclick="openx()"><div>

wait for function execution before executing next instruction

I’m trying to upload images to firebase and get the download Url and save the url in the firestore in the database. The code was working until I modified it to handle multiple images. To handle multiple images I have implemented promises.

The functions uploadFiles() and addRecord() works completely fine seperately. But I want to run the functions together in onSubmit() function. The problem I’m facing is that addRecord() runs before the uploadFiles() completes its execution.

I have tried promises and async await to control the flow but unsuccessfull. I’m new to handling promises and stuck at it.

here’s the uploadFiles code

const uploadFiles = (data) => {
const promises = [];
data.images.map((file) => {
  console.log("loop");

  const sotrageRef = ref(storage, `files/${file.name}`);

  const uploadTask = uploadBytesResumable(sotrageRef, file);
  promises.push(uploadTask);
  uploadTask.on(
    "state_changed",
    (snapshot) => {
      const prog = Math.round(
        (snapshot.bytesTransferred / snapshot.totalBytes) * 100
      );
      setProgress(prog);
    },
    (error) => console.log(error),
    async () => {
      await getDownloadURL(uploadTask.snapshot.ref).then((downloadURLs) => {
        setUrls((prevState) => [...prevState, downloadURLs]);
        console.log("File available at", downloadURLs);
      });
    }
  );
});
Promise.all(promises)
  .then(() => alert("All images uploaded"))
  .catch((err) => console.log(err));
};

here’s the onSubmit function

const onSubmit = async (data) => {
console.log("before upload");
await uploadFiles(data);
console.log("after upload");
console.log(urls);
await addRecord({
  title: data.title,
  eventType: data.eventType,
  date: data.date,
  venue: data.venue,
  description: data.description,
  details: data.details,
  images: urls,
  link: data.link,
  scheduleType: data.scheduleType,
    });
  };

The upload files sets the state of the urls to the image urls from the firebase storage. I have console logged messages before and after the uploadFiles. The console.log(urls) returns an empty array after the uploadFiles is completed, but the values are being populated with urls after the addRecord is being executed. This is resulting the firestore record to be an empty array for images.

Here’s a screenshot of the console

enter image description here

Is anything wrong with the way I’m handling promises and async await.

Typescript: object with classes as a values

Let’s say I want to build a proxy class from this question’s accepted answer.

So I need to prepare some object which contains all the classes as values:

class Class1 {}
class Class2 {}

const ClassEnumeration = {
  class1: Class1,
  class2: Class2
}

// then it will be used like that
class DynamicClass {
    constructor (className, opts) {
        return new classes[className](opts);
    }
}

new DynamicClass('ClassOne'); //=> "Hi from ClassOne"
new DynamicClass('ClassTwo', 'Bye'); //=> "Bye from ClassTwo"

I can’t get which type ClassEnumeration has in this case. I guess it will be something like Record<string, ...?? > Which type has the second argument here?

Is it antipattern having array manipulations in React render like in the bellow sample?

I need to create new array of items from very complex props that includes array of objects. The component is class based component. I did all operations in render like bellow:

class Shop extends React.Component {
  render() {
    const clothesProducts = this.props.product.brands.filter(item => item.tag === 'clothes')
    let filterednewProducts = []
    let clothesProductsNames = []
    const newProducts = this.props.product.tags.filter(item => item.tag !== 'clothes') if (newProducts.length) {
      const newProductNames = newProducts.map(item => item.name).sort() newProductNames.forEach((item, index) => {
        if (newProductNames[index + 1] !== newProductNames[index]) {
          filterednewProducts.push(item)
        }
      })
    }
    if (clothesProducts.length) {
      clothesProductsNames = clothesProducts.map(item => item.clothes.name)
    }
    const totalProducts = [...filterednewProducts, ...clothesProductsNames] console.log(totalProducts)
    return (
      ...
    )
  }
}

Please note that my question is not about if this code works makes sense or not. I want to ask if it’s anti pattern having these kind of operations inside render method in the class based component?

How to prevent overlapping opacity of text in CSS?

There are two semi-transparent text characters that overlap. The characters are contained within the same tag.

<p>┻━</p>
p {
    color: rgba(255, 255, 255, 0.5);
}

In the area where these two characters overlap, their opacity adds up.

enter image description here

Is there a way to prevent “double opacity” when characters overlap?

How to execute executeScript before completing onBeforeRequest?

I have a function that intercepts the request and changes the url based on the data from the page

function my_func(requestDetails) {
  var count="0";
  chrome.tabs.executeScript(null, { //Add jquery
        file: "jquery-3.6.0.min.js",
  });
  
  chrome.tabs.executeScript(null, { //Get count
            file: "test.js",
    }, function (result) {
        count=result;     
        console.log("Result "+result);  
  });

  console.log("After "+count);
  return {
    redirectUrl : "https://another.site/ext.php?count="+count
  };  
}

Intercepts the request and calls my_func

chrome.webRequest.onBeforeRequest.addListener(
  my_func,
  {
    urls: ['https://www.site.ru/command'] // or <all_urls>
  }, ["blocking"]
);

test.js Takes text from select and returns it

test=$('select[ng-model="operation.test"] option:selected').text();
test;

When queried in the console, I get this

After 0
Result 1

chrome.tabs.executeScript terminates after executing my_func’s return, and I need to do the opposite somehow. What can I do?

Disable VERTICAL Scroll only

Bonjour amis développeur ! ,

Since yesterday i’m blocking to block a vertical scrolling of my site but just the vertical, i create a slider with parallax effect and i need to Scroll horizontaly
Without WordPress in a simple HTML / CSS / JS is good but when i integrated in WordPress the scroll (With the mousse) doesn’t 🙁 !

The Scroll bar is here but 0 Scroll with mousse

I’m Share my code, if you have a idea to disable Scroll vertical and Active horizontale you save me ! :p

A French studend, Antoine see u !!

let slider = document.querySelector('.slider');
let sliderWidth;
let imageWidth;
let current = 0;
let target = 0;
let ease = .05;
let images = [...document.querySelectorAll('.img')];

images.forEach((img, idx) => {
    img.style.backgroundImage = `url(https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg)`
})


    function lerp(start, end, t) {
        return start * (1 - t) + end * t;
    }

    function setTransform(el, transform) {
        el.style.transform = transform;
    }

    function init() {
        sliderWidth = slider.getBoundingClientRect().width;
        imageWidth = sliderWidth / images.length;
        document.body.style.height = `${sliderWidth - (window.innerWidth - window.innerHeight)}px`
    }

    function animate() {
        current = parseFloat(lerp(current, target, ease)).toFixed(2);
        target = window.scrollY;
        setTransform(slider, `translateY(-${current}px)`)
        animatedImage();
        requestAnimationFrame(animate);
    }

    function animatedImage() {
        let ratio = current / imageWidth;
        let RatioValue;

        images.forEach((image) => {
            RatioValue = ratio - (0.2);
            setTransform(image, `translateX(-${RatioValue * 20}px)`)

        })
    }


    init();

    animate();
@media (min-width: 800px) {
    body{
        background-color: #F2F2F2;
        box-sizing: border-box;
        overflow-x:scroll;
        overflow-y: hidden;


    }

    main {
        top: 0;
        left: 0;
        width: 100%;
        height: 100vh;
        display: flex;
    }

    .slider {
        position: absolute;
        top: 0;
        left: 0;
        width: 3400px;
        height: 68%;
    }

    .slider-inner {
        position: fixed;
        top: 15%;
        width: 100%;
        height: 50%;
        display: flex;
        justify-content: space-around;
    }

    .item {
        position: relative;
        width: 400px;
        height: 100%;
        overflow: hidden;
        padding-top: 6%;
    }

    .img {
        position: absolute;
        width: 500px;
        height: 100%;
        background-size: cover;
        background-position: center;

    }
    .title  {

        background-color: #F2F2F2;
        text-align:center ;
        padding: 12px;

    }

    .link {
        text-decoration: none;
        color: #053D21 ;
    }
    .link:hover {
        text-decoration: none;
        color: #EA734E ;
    }
}
@media (max-width: 801px) {
    .title  {
        background-color: #F2F2F2;
        text-align:center ;
        padding-top: 12px;
        padding-bottom: 12px;
        margin-bottom: 15%;
        width:100%;
    }

    body{
        background-color: #F2F2F2;
        margin: 0 ;



    }

    main {
        position: absolute;
        width: 100%;
        height: auto;
    }

    .slider-inner {
        display: block;

        justify-content: center;
    }

    .slider {
        display: flex;
        flex-wrap: wrap;

    }

    .item {

        border: solid 2px brown;
        width:90%;
        height: 20%;
    }

    .img {

        width:95%;
        height: 100%;
        background-size: contain;
        background-repeat: no-repeat;
    }
    .slider-inner {
        width: 100%;
        height: auto;
    }


    .link {
        text-decoration: none;
        color: #053D21 ;
    }
    .link:hover {
        text-decoration: none;
        color: #EA734E ;
    }




}
  <main>
    <div class="slider" align="center" >
        <div class="slider-inner">

                <a href="#" class="link">
                    <div class="item">
                        <div class="img" ></div>
                    </div>
                    <div class="title"><h2>Ma super vidéo</h2></div>
                </a>



            <section>
                <a href="#" class="link">
                    <div class="item">
                        <div class="img" ></div>
                    </div>
                    <div class="title"><h2>Ma super vidéo</h2></div>
                </a>
            </section>

            <section>
                <a href="#" class="link">
                    <div class="item">
                        <div class="img" ></div>
                    </div>
                    <div class="title"><h2>Ma super vidéo</h2></div>
                </a>
            </section>

            <section>
                <a href="#" class="link">
                    <div class="item">
                        <div class="img" ></div>
                    </div>
                    <div class="title"><h2>Ma super vidéo</h2></div>
                </a>
            </section>

            <section>
                <a href="#" class="link">
                    <div class="item">
                        <div class="img" ></div>
                    </div>
                    <div class="title"><h2>Ma super vidéo</h2></div>
                </a>
            </section>

            <section>
                <a href="#" class="link">
                    <div class="item">
                        <div class="img" ></div>
                    </div>
                    <div class="title"><h2>Ma super vidéo</h2></div>
                </a>
            </section>

            <section>
                <a href="#" class="link">
                    <div class="item">
                        <div class="img" ></div>
                    </div>
                    <div class="title"><h2>Ma super vidéo</h2></div>
                </a>
            </section>
        </div>
    </div>
    </div>

</main>

Unhandled runtime error found in your files. Help figure error messages

Whenever I open your files, I always get an unhandled runtime error. However, I have never understood what it meant. If anyone can explain it slowly so that anyone can understand and offer suggestions and advice on how to resolve this issue.

When I re-ran my development yesterday, the first error message appeared on line 9. Now today message says the error is on line 35, which drives me insane.

As person with ADHD and Learning Difficulties. What are some tool or plugin that recommend for Visual Studio Code? or Other help tools that better understand coding error match clearly as person with Neurodiversity.

  • Error in function ArticleListing in
    ./src/templates/ArticleListing.js:9

const data = useStaticQuery(graphql // This is line 9.

  • Error in function ArticleListing
    in ./src/templates/ArticleListing.js:35

const siteTitle = data.site.siteMetadata.title || “ // this is line 35

Below I have copy the code I have write for you to review:

import * as React from "react"
import { useStaticQuery, Link, graphql } from "gatsby"
import Layout from "../components/layout"
import Seo from "../components/seo"
import { GatsbyImage as CoverImage, getImage } from 'gatsby-plugin-image' // use the GatsbyImage but if you want to custom it.


const ArticleListing = ({ location, post  }) => {
  const data = useStaticQuery(graphql
  `
    query MyQuery {
      allMarkdownRemark(
        limit: 1000, 
        sort: {
          fields: 
          frontmatter___date, order: ASC}) 
        {
        nodes {
          id
          fields {
            slug
          }
          frontmatter {
            date(formatString: "MMMM DD, YYYY")
            description
            tags
            featuredimage
          }
        }
      }
    }
` )


const siteTitle = data.site.siteMetadata.title || ``
const posts = data.allMarkdownRemark.nodes 

if (post.length === 0) { // is message tell us if there no post being display post this message
  return (
    <div id="content">
        <Layout location={location} title={siteTitle}>
          <Seo title="All posts" />
          <p>There were no blogs found. Our team is working hard to create content you will enjoy.</p>
        </Layout>
    </div>
  )
}

  return ( // This where you be rendering your post.
    <div id="content">
      <Layout location={location} >
        <Seo title="All posts" />

        <ol className="inline_blog" style={{ listStyle: `none` }}>
                {posts.length > 0 && posts.map((post) => { // When is no post you will get this error message but when is post you will not get a error message.
                const title = post.frontmatter.title || post.fields.slug

                let image = getImage(post.frontmatter.featuredimage) // this is getting the post cover image
                let alt = post.frontmatter.title // this is getting the title of the post

                return (
                    <li key={post.fields.slug}>
                        <article
                            className="post-list-item"
                            itemScope
                            itemType="http://schema.org/Article">

                            <header>
                                <div className="cover_image">
                                    <CoverImage
                                        height="150"
                                        image={image}
                                        alt={alt}/>
                                </div>

                                <small>
                                    {post.frontmatter.date}
                                </small>

                                <h2 className="post_heading_title">
                                    <Link to={post.fields.slug} itemProp="url">
                                        <span
                                            itemProp="headline">
                                            {title}
                                        </span>
                                    </Link>
                                </h2>
                            </header>

                            <section>
                                <p dangerouslySetInnerHTML=
                                  {{   
                                    __html: post.frontmatter.description || post.excerpt, 
                                  }}
                                itemProp="description" />
                            </section>
                        </article>
                    </li>
                );
            })}
        </ol>
      </Layout>
    </div>
  )
}

export default ArticleListing