[[proto]] vs __proto__ in the following description

From this answer to __proto__ VS. prototype in JavaScript it states that:

  • Why would we need a reference object to the property [[prototype]] (of all objects)?
    • Because JavaScript doesn’t want to allow getting / setting the [[prototype]] directly, so it allows it through a middle layer which is __proto__. So you can think of __proto__ as a getter/setter of the [[prototype]] property.

The part I don’t follow is if __proto__ is ‘just a getter/setter’ for [[prototype]], then what is the difference between then two? Why would we ever need two items here instead of just one (either __proto__ or [[prototype]])? Is one similar to a pointer, or one compiled code, or why could they not be considered the same then?

React-Router V6 Protected Routes Firing Before Authentication Finishes

so I’m having issues with getting my protected route to work in React-Router-V6. I have set up a PrivateRoute, however it doesn’t appear to be working as I am stil able to manually navigate to the protected route via the URL. This leads me to believe that this check is occuring before the authentication status from firebase is returned. Heres the relevant bits of code:

PrivateRoute.js:

import React from 'react'
import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

export default function PrivateRoute() {
    const { currentUser } = useAuth();

    if (currentUser === undefined) return null; 

    return currentUser ? <Outlet /> : <Navigate to="/login" />
}

App.js:

import React from "react";
import { AuthProvider } from "../contexts/AuthContext";
// Import Components // 
import Signup from "./Signup";
import Dashboard from "./Dashboard";
import Login from "./Login";
import PrivateRoute from "./PrivateRoute";
// React-Router //
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <>
      <Router>
        <AuthProvider>
          <Routes>
            <Route element={<PrivateRoute/>}>
              <Route exact path="/dashboard" element={<Dashboard/>}/>
            </Route>
            <Route path="/signup" element={<Signup/>} />
            <Route path="/login" element={<Login/>} />
          </Routes>
        </AuthProvider>
      </Router>
    </>
  )
}

export default App;

AuthContext.js:

    import React, { useContext, useEffect, useState } from 'react'
import { auth } from '../firebase';

const AuthContext = React.createContext();

export function useAuth() {
    return useContext(AuthContext);
}

export function AuthProvider({ children }) {

    const [currentUser, setCurrentUser] = useState();
    const [loading, setLoading] = useState(true);

    function signup(email, password) {
        return auth.createUserWithEmailAndPassword(email, password);
    }

    function login(email, password) {
        return auth.signInWithEmailAndPassword(email, password);
    }

    function logout() {
        return auth.signOut();
    }

    useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
            setCurrentUser(user);
            setLoading(false);
        });

        return unsubscribe;
    }, []);

    const value = {
        currentUser,
        login,
        signup,
        logout
    }

  return (
    <AuthContext.Provider value={value}>
        {!loading && children}
    </AuthContext.Provider>
  );
};

Any help would be hugely appreciated, I’ve tried numerous different methods of protecting routes, each having the same issue of the authentication being ignored and allowing for direct navigation via the URL.

Thanks ๐Ÿ™‚

How to display automatically computed value on input type number?

I just started learning JavaScript in Scrimba and there is a practice part where to make a unit conversion but I already did the static one then I challenge myself to add an user input but I just burnout my self I’m so confused now

Here is my html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <main>
        <div class="unit">
            <h2 id="heading">Metric/Imperial Unit Converstion</h2>
            <!-- <h2 id="numToConvert"> 0 </h2> -->
            <input type="number" value="num" id="inputNum" min="0" onchange="unitConvert()">
            
        </div>
    </main>
    <section> 
        <div class="main-results"> 
            <div class="conversion-results">
                <p>Length (Meter/Feet)
                <p id="meterFeet">0 meters = 0.000 feet | 0 feet = 0.000 meters</p>
            </div>
            <div class="conversion-results">
                <p>Volumes (Liters/Gallons)
                <p id="litersGallons">0 liters = 0.000 gallons | 0 gallons = 0.000 liters</p>
            </div>
            <div class="conversion-results">
                <p>Mass (Kilograns/Pounds)
                <p id="kiloPounds">0 kilos = 0.000 pounds | 0 pounds = 0.000 kilos</p>
            </div>
        </div>
    </section>
    <script src="script.js"></script>
</body>
</html>

Here is my JavaScript code:

const unit = document.getElementById("inputNum").value;

function unitConvert() {
    const meterToFeet = (unit * 3.28084).toFixed(3)
    const feetToMeter = (unit * 0.3048).toFixed(3)

    const litersToGallons = (unit * 0.264172).toFixed(3)
    const GallonsToLiters = (unit * 3.785412).toFixed(3)

    const kilogramsToPounds = (unit * 2.2).toFixed(3)
    const poundsToKilograms = (unit / 2.2).toFixed(3)

    //Meter to Feet/Vice Versa
    document.getElementById("meterFeet").textContent = unit +" meters = "+ meterToFeet +" feet | "+unit+" feet = "+feetToMeter+" meters"
    //Liters to Gallons/Vice Versa
    document.getElementById("litersGallons").textContent = unit +" liters = "+ litersToGallons +" gallons | "+unit+" gallons = "+GallonsToLiters+" liters"
    //Kilo to Pounds/Vice Versa
    document.getElementById("kiloPounds").textContent = unit +" kilos = "+ kilogramsToPounds +" pounds | "+unit+" pounds = "+poundsToKilograms+" kilos"
}

Creating a program for movies based on the year Javascript [duplicate]

This is the question:

create an array of at least five objects based on the movie title and release date.

Title Release Date
Jaws 1975
E.T. 1982
Psycho 1960
IT 1990
Vertigo 1958

Then, create a loop that will loop through the array, displaying in an alert box, movies that were released after a year that the user enters.
For example, if the user types โ€˜1978โ€™, then the alert boxes will show movie titles for E.T. and IT only.

I’m not sure how to match the movie with the year and show the movies with the year greater than what the user input

function movies () {

movies = [
    {Movie:"Vertigo", Year:"1958"},
    {Movie:"Psycho", Year:"1960"},
    {Movie:"Jaws", Year:"1975"},
    {Movie:"E.T", Year:"1982"},
    {Movie:"IT", Year:"1990"},
    ];

user = prompt("Enter the year of movies you are interested innYear: ");




}

Web only for authenticated users Firebase

I am developing an HTML webpage using Firebase, my working tree is:

  • css: folder with CSS style files
  • js: folder with Javascript files
  • login.html: logging in page
  • signup.html: signing up page
  • app.html: main application page

I would like to restrict the app.html access only for logged users. I have implemented in Javascript some scripts to authenticate users via email and password using the login.html and signup.html pages. For the project, I use the hosting tool that offers Firebase. However, I’m not sure whether I need to apply this capability with the hosting tools or the real time database or other. Maybe the solution is to upload my web as a real time database resource and then, control the access to some paths modifying the database.rules.json file, but I don’t know how to implement it.

Thanks for your help ๐Ÿ™‚

App failing to work after deployment via Heroku

I’m trying to deploy my app to Heroku in which I believe is working. Whilst testing my app via localhost it works fine, everything is posting. However after deployment and replacing all my URLs to Heroku, number of things are not working:

  1. The GIPHY API no longer works
  2. Nothing would post (comments and likes work but not the posting)

I have tried debugging however nothing has worked. Where am I going wrong? Please see below for details

app: https://mitnickproject1-journal-app.netlify.app/
heroku: https://journal-post-pl.herokuapp.com/print

Front-end code

const formEl = document.querySelector('form');
formEl.addEventListener('submit', postFormData)
let count=0;

async function postFormData(e) {
  const current= new Date().toLocaleString() 
  const formData= new FormData(formEl) // console.log this to check what format this is in 
  const formDataSerialised=Object.fromEntries(formData) //console.log this to see what this does
  const jsonObject = {...formDataSerialised, "dateTime": current, "comment": [], "EmojiCount": [0,0,0], "gifLink":gifLink, 'id': count}
  console.log(JSON.stringify(jsonObject, null, 2))
  try{
    const options = { method: 'POST', 
    body: JSON.stringify(jsonObject),
    headers: {
      'Content-Type': 'application/json'
    }
  }

  await fetch("https://journal-post-pl.herokuapp.com/test", options);
    // const response = await fetch("https://journal-post-pl.herokuapp.com/test", {

    // })
    // const json = await response.json();
  }catch(err){
    console.error(err);
    alert('There was an error')
  }
}

Back End Code

app.post('/test', (req, res) => {
    formData.push(req.body)
    console.log(formData)
    writeToJson();
    res.json({success: true})
})

Any help would be appreciated

Is it possible to set an interval to when a forEach loop of an array returns it’s results?

Currently I’m trying to loop through an array, and in doing so a license plate is animated on screen in a marquee-like animation. Currently, how its displayed looks like this :
Working Example

I specifically need to only display one of these plates at a time, can this be done through setInterval/Timeout?

What I’ve tried doesn’t seem to have any effect. So im wondering if either, im doing it wrong, or is there a better way to do this?

Code Below:

    const insertMarquee = $('#insertMarquee');
    const startMonthlies = $('#startMonthlies');
    const stopMonthlies = $('#stopMonthlies')

    const marqueeMonthlies = () => {
        insertMarquee.empty();
        let marqueeMonthlyPlates = JSON.parse(localStorage.getItem('Monthly Plates'));
        setInterval(marqueeMonthlyPlates.forEach((plate) => {
            insertMarquee.append(`
            <div class="container" id="generatedMonthlyPlates">
            <input type="text" width="100px" name="monthlyLicensePlate" id="${plate}" class="licensePlate" placeholder="AB12345" value="${plate}"/>
            </div>
            `) 
        }),1000)
       
        
    }

    startMonthlies.click((event) => {
        event.preventDefault();
        marqueeMonthlies();
    })

I recieve an empty request.body on my nodejs server from my page [duplicate]

Iยดm using nodejs to make a server what connect with a DB and a simple website, i can do a GET fetch and i take the data, but when i do a POST fetch my server receive and empty request.body.I try 2 diferents versions of nodejs 12.16.1 and 16.10.0 also i use express and body-parser and i got the same result.

This is my config on the server site

const express = require('express');
const morgan = require('morgan');
const app = express();

const router = require('../routes/routes.js');
/**configuraciones */

app.set('port',3000);

app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(router);


app.listen(app.get('port'), () =>{
    console.log("El server esta operativo ")
});

This is my code on website

var username = document.getElementById('user-reg');
var emailreg = document.getElementById('email-reg');
var btnReg = document.getElementById('btn-reg')
btnReg.addEventListener('click', sacarInformacion)

function sacarInformacion(){
    var user = username.value
    var email = emailreg.value
    var jsonString = `{"correo": "${email}", "nombre":"${user}"}`
    const options = {
        method : 'POST',
        mode: 'no-cors',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.parse(jsonString)
    }
    fetch('http://localhost:3000/to', options);
    console.log(JSON.parse(jsonString))
    //i catch in the console the data i pass on body
}

The main problem is that i used postman as API and i get the body on the server, but
when i use it on website i get an empty body

Toggle between two divs using a button

Basically i have 2 divs on my HTML page, and i’m trying to create a function to toggle between the two, using the buttons on my HTML. One button would be to toggle to div 2, and the other would be to toggle back to div 1, just like the code below:

<button id="toggle-to-2">Toggle to div 2</button>
<button id="toggle-to-1">Toggle to div 1</button>

<div id="div-1">
This is div 1
</div>

<div id="div2">
This is div 2
</div>

Also, when using CSS, how should i position them? Should i give them the same position, and rely on the function to toggle between the two?

CodeMirror rendering TextArea multiple times in react application

I am trying to use the CodeMirror package to integrate code Editor inside React Application. Calling the Editor Component only a single time but the code mirror div is mounted twice.

import React, { useEffect } from 'react';
import Codemirror from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/theme/dracula.css';
import 'codemirror/addon/edit/closetag';
import 'codemirror/addon/edit/closebrackets';

const Editor = () => {
    useEffect(() => {
        function init() {
            Codemirror.fromTextArea(document.getElementById('realTimeEditor'), {
                mode: { name: 'javascript', json: true },
                theme: 'dracula',
                autoCloseTags: true,
                autoCloseBrackets: true,
                lineNumbers: true,
            });
        }
        init();
    }, []);

    return <textarea id='realTimeEditor'></textarea>;
};

export default Editor;

Not able to figure out what could be the reason for this issue. Below Image attached of a Screenshot of the same. Not able to debug where is the issue. Please tell how to fix this.

enter image description here

enter image description here

How to make onclick function that write out text from inputs? [duplicate]

To be more precise, I have few input fields where user write something. My button need to call onclick function that will take texts from input fields and write it out in paragraph

CODE (FOR EXAMPLE):

YOUR NAME: <input type="text" id="name">
YOUR CAR COLOR: <input type="text" id="color">
NUMBER OF WHEELS: <input type="number" id="nmbrofwheels">
<button onclick="writeThisOut()">

How do I make function that will print out (for example) “John has blue car with four wheels” (or whatever user wrote in input fields)
And how do I choose place on web page where I want to print out paragraph ?

How to customize google app script “result” : “success” confirmation message ..?

I am sending html form data to an email address using google app script. After clicking the submit button it goes to a different page and shows a confirmation message like …
{“result”:”success”,”data”:”{“subject”:[“”],”name”:[“”],”message”:[“”],”email”:[“”]}”} … I want to change it and implement my own message but don’t know where to modify and how in the script.js file. The data part looks messy. Is it possible to just send result = success message without the data value part ..? And can I add an alert(email submission successful) in the script ..? I can do the alert using onclick event connected to the button. But it is not an actual confirmation. So how can I set an alert message like result = success in the google script.js ..?

JAVASCRIPT

// spit out all the keys/values from the form in HTML for email
// uses an array of keys if provided or the object to determine field order
function formatMailBody(obj, order) {
  var result = "";
  if (!order) {
    order = Object.keys(obj);
  }
  
  // loop over all keys in the ordered form data
  for (var idx in order) {
    var key = order[idx];
    result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + sanitizeInput(obj[key]) + "</div>";
    // for every key, concatenate an `<h4 />`/`<div />` pairing of the key name and its value, 
    // and append it to the `result` string created at the start.
  }
  return result; // once the looping is done, `result` will be one long string to put in the email body
}

// sanitize content from the user - trust no one 
// ref: https://developers.google.com/apps-script/reference/html/html-output#appendUntrusted(String)
function sanitizeInput(rawInput) {
   var placeholder = HtmlService.createHtmlOutput(" ");
   placeholder.appendUntrusted(rawInput);
  
   return placeholder.getContent();
 }

function doPost(e) {

  try {
    Logger.log(e); // the Google Script version of console.log see: Class Logger
    record_data(e);
    
    // shorter name for form data
    var mailData = e.parameters;

    // names and order of form elements (if set)
    var orderParameter = e.parameters.formDataNameOrder;
    var dataOrder;
    if (orderParameter) {
      dataOrder = JSON.parse(orderParameter);
    }
    
    // determine recepient of the email
    // if you have your email uncommented above, it uses that `TO_ADDRESS`
    // otherwise, it defaults to the email provided by the form's data attribute
    var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
    
    // send email if to address is set
    if (sendEmailTo) {
      MailApp.sendEmail({
        to: String(sendEmailTo),
        subject: "Contact form submitted",
        // replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
        htmlBody: formatMailBody(mailData, dataOrder)
      });
    }

    return ContentService    // return json success results
          .createTextOutput(JSON.stringify({"result":"success"}))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(error) { // if error return this
    Logger.log(error);
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": error}))
          .setMimeType(ContentService.MimeType.JSON);
  }
}

Where and how can I create a custom alert and result success message …?

Is there a way to plot a date ranges (Start Date/End Date) value on Echarts Bar Chart?

I was wondering if this can be done on echarts.

I have categories on the y-axis and date values on the x-axis. The values will be the start date and end date for the category.

This is the chart produced by the code below.
enter image description here

xAxis: {
    type: 'time',
    axisLabel: {
          formatter: function (value, index) {
              var date = new Date (value);
              return date.toLocaleDateString("en-US")
          }
      }
  },
  yAxis: {
    type: 'category',
    data: ['Category1', 'Category2', 'Category3', 'Category4', 'Category5', 'Category6'],
    axisLine: { show: true },
  },
  series: [
    {
      name: 'Task 1',
      type: 'bar',
      encode: {
                  x: 0,
              },
      data: [
          new Date('2022-04-10').getTime(), 
          new Date('2022-04-12').getTime(),
          new Date('2022-04-14').getTime(),
          new Date('2022-04-16').getTime(),
          new Date('2022-04-18').getTime(),
          new Date('2022-04-20').getTime(),
        ]
    },
    {
      name: 'Task 2',
      type: 'bar',
      data: [
        new Date('2022-04-04').getTime(), 
        new Date('2022-04-07').getTime(), 
        new Date('2022-04-08').getTime(),
        new Date('2022-04-03').getTime(),
        new Date('2022-04-09').getTime(),
        new Date('2022-04-12').getTime()]
    }
  ]

What I wanted to achieve is something like this.
enter image description here

How to pass a variable in an href in HTML

I have this search bar set up for my website I am developing as my senior project. I was trying to figure out how to pass the value in the input to the new page that I will have an href to so that I can search through all my pages and display the ones with matching values on the new page that I navigated to. Not sure how to pass that input data to the new page.

HTML in a code editor

Bar chart with two sets of labels in Quickchart

I am trying to create a bar chart for tracking a budget with quickchart. I want the chart to have one set of labels on top of the bars (for % remaining), and a second set of labels inside each bar (for $’s remaining).

I was able to figure out the labels on top of the bars, but need help adding a second set of labels within the bars. The labels within the bars will need to be based on a second array of data.

I have posted my code, which can be tweaked in the live editor here. Any help would be greatly appreciated!

{
  type: 'bar',
  data: {
    labels: ['Food', 'Gas', 'Other'],
    datasets: [{
      label: 'Category',
      data: [.5, .7, .8]
    }]
  },
  options: {
        plugins: {
      datalabels: {
        formatter: function(value) {
            return Math.round(value*100) + '%';},
        anchor: 'end',
        align: 'end',
        color: 'black',
        labels: {
          percent: {
            font: {
              weight: 'bold',
              size:26,
            }
          }
        }
      }
    },
    scales: {
      yAxes: [ {
        type: 'linear',
        ticks: {
            beginAtZero: true,
            suggestedMin : 0,
            suggestedMax : 1,
            }
        }]
      } 
  }
}