Handlebars helper – “Helper Not Defined” error

I am working with Handlebars. I am trying to write a helper, so that I can have some Javascript code. Here is an example of my code:

My handlebars template is:

<!doctype html>
<html>
  <head>
  </head>
  <body>
    {{loud name}}
  </body>
</html>

In the same directory, I have another Javascript file. This is that file:

Handlebars.registerHelper('loud', function (aString) {
    return aString.toUpperCase()
})

The error that I am getting is ‘Helper not defined: “loud”‘. Why is this the case?

Getting data to be fetched upon page render ReactJS

Still a newbie, so not sure how to solve this issue. The app gets data about movie genres from an API, it then uses those genres to create options in the drop-down selector. The user can choose a type (tv show or movie) and then the genre. When they hit search it will return a random movie or show in the genre. The starting values are tv show and action. I want the user to be able to immediately hit search and find a title to watch. My problem is the data about movies/ shows in the specified type and genre are only fetched when the user changes the selector option from the default one. You can see this hosted on GH Pages here or check the GH repository

So I want the data from the full_url to be fetched upon render. The feedback from the console is that upon render chosenType and chosenGenre are undefined in the fetch method fetchMovieList(). But once I change the type, an array of movies or shows are fetched.

Any help or advice would be appreciated.

Below is the code.

import { createContext, useState, useEffect } from "react";

export const MovieContext = createContext({});

export function MovieProvider({ children }) {
  const [movieList, setMovieList] = useState([]);
  const [randomMovie, setRandomMovie] = useState({});
  const [hasMovie, setHasMovie] = useState(false);
  const [genreOptions, setGenreOptions] = useState([]);
  const [chosenGenre, setChosenGenre] = useState();
  const [typeOptions, setTypeOptions] = useState([]);
  const [chosenType, setChosenType] = useState();

  const api = "api_key=3fa371d07ffd6838dc488ff081631c5d";

  const genres_url =
    "https://api.themoviedb.org/3/genre/movie/list?api_key=3fa371d07ffd6838dc488ff081631c5d&language=en-US";

  const types = [
    { type: "TV Show", value: "tv" },
    { type: "Movie", value: "movie" },
  ];


  //fetching genres from API to use in selector and for searching and setting types for selector
  const fetchGenres = () => {
    fetch(genres_url)
      .then((res) => res.json())
      .then((data) => {
        setChosenGenre(data.genres[0].id);
        setGenreOptions(data.genres);
        setTypeOptions(types);
        setChosenType(types[0].value);
        console.log(data);
      });
  };

  //getting genres when page loads 
  useEffect(() => {
    fetchGenres();
  }, []);

    //setting the value of slelector drop downs
    const onChangeGenre = (e) => {
      setChosenGenre(e.target.value);
    };
  
    const onChangeType = (e) => {
      setChosenType(e.target.value);
    };

  //fetching movies or shows from the selected genre
  const full_url = `https://api.themoviedb.org/3/discover/${chosenType}?${api}&with_genres=${chosenGenre}`;

  const fetchMovieList = () => {
      fetch(full_url)
      .then((res) => res.json())
      .then((data) => {
        setMovieList(data.results);
        console.log(data.results);
      });
  };

  console.log(chosenType, chosenGenre)


  //fetches data from API when type or genre is changed
  useEffect(() => {
    fetchMovieList();
  }, [chosenType, chosenGenre]);


  //function that selects a random movie or show from the already fetched data
  const getRandomMovie = (e) => {
    e.preventDefault();
    const randomItem = movieList[Math.floor(Math.random() * movieList.length)];
    setRandomMovie(randomItem);
    console.log(randomItem);
    setHasMovie(true);
  };

  //passing state and functions to child components
  return (
    <MovieContext.Provider
      value={{
        getRandomMovie,
        onChangeGenre,
        onChangeType,
        randomMovie,
        hasMovie,
        genreOptions,
        chosenGenre,
        typeOptions,
        chosenType,
        types,
      }}
    >
      {children}
    </MovieContext.Provider>
  );
}

Need help importing data from Google sheets to Slides

I am trying to create a button in google sheets that run a script every time it is triggered. The script should first create a new copy of the template and then using that google sheet replace all placeholder text in that presentation with data from sheets. I am not sure why the code is not working as of now. Please help!

// The following creates the UI button in sheets (This works)
function onOpen() {
  let ui = SpreadsheetApp.getUi();
  ui.createMenu('Create Report')
  .addItem('Create Report', 'executeAll')
  .addToUi();
}

function executeAll (){
  var reportTemplate = DriveApp.getFileById('Presentation ID goes Here');
  var copiedTemplate = reportTemplate.makeCopy('New Report', DriveApp.getFolderById("Folder ID Goes here"));
  var skeleton = SlidesApp.openById(copiedTemplate.getId());
  var slides = skeleton.getSlides();
  return slide1();


  function slide1 (){
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('App Script Input Sheet');
    var data = sheet.getRange('E1:F26').getValues;
    var slide1 = slides[0];
    var newslide1 = slide1.duplicate();
    var shapes = (newslide1.getShapes());
      shapes.forEach(function(shape){
        shape.getText().replaceAllText('{{Date}}',data[2]);
        shape.getText().replaceAllText('{{Title}}',data[3]);
        shape.getText().replaceAllText('{{Value 1}}',data[4]);
        shape.getText().replaceAllText('{{Value 2}}',data[5]);
        //there are more to be replaced. will add once code works. 
       

      });
  }
}

TypeScript/Express: Method still not being exported

I have one method in my authentication-service.ts file that is not successfully exporting for some reason. This is what the method looks like:

function verifyAuth(req: Request): Promise<AuthResult> {
  return new Promise(async (resolve, reject) => {
    let verifyResult: AuthResult = {
      httpCode: 200,
      message: 'OK'
  };

const authHeader: string | undefined = req.headers["authorization"];

if (!authHeader) {
  verifyResult.httpCode = 400;
  verifyResult.message = 'missing Authorization in headers';
  reject(verifyResult);
}

let service: string | undefined = undefined;
if (Object.keys(req.headers).includes("looney-service") && !Array.isArray(req.headers["looney-service"])) {
  service = req.headers["looney-service"];
}

if (!service) {
  verifyResult.httpCode = 400;
  verifyResult.message = 'missing Looney-Service in headers';
  reject(verifyResult);
}

if (authHeader && service) {
  const token: string | null = getTokenFromAuth(authHeader);
  if (token) {
    const result: string = await verifyService(service, token).catch(err => {
      console.log('verifyAuth caught error!', err);
      return err;
    });
    if (result == 'OK') {
      verifyResult.httpCode = 200;
      verifyResult.message = result;
      resolve(verifyResult);
    } else {
      verifyResult.httpCode = 403;
      verifyResult.message = result;
      reject(verifyResult);
    }
  } else {
    verifyResult.httpCode = 403;
    verifyResult.message = 'missing token';
    reject(verifyResult);
  }
}
  });
}

export { getServiceConfig, getServicePublicKey, verifyService, genJwt, getTokenFromAuth, AuthResult, verifyAuth }

I am importing the file that this method sits in like so:

import * as auth from './services/authentication-service'

However, when I console log auth, the object does not contain the verifyAuth method:

{
  getServiceConfig: [Function: getServiceConfig]
  getServicePublicKey: [Function: getServicePublicKey]
  verifyService: [Function: verifyService]
  genJwt: [Function: genJwt]
  getTokenFromAuth: [Function: getTokenFromAuth]
}

Why is that? TypeScript is not complaining about any type reference, all that has seemingly been corrected.

Prevent users from leaving web page before it it fully loaded

I have this low budget website that hardly loads on time,it is a blog. Presently, I can’t afford the website with high bandwidth, but for the meantime I need answers to this question. I noticed because of the slow rate my website loads, users exit quickly and it so discouraging. I need a JavaScript code that can delay the exit of a user to 20 seconds, I want the user not to be discouraged and view my content.

Reset button on form not working for javascript?

I am trying to reset every input that has been entered on this form when the “reset” button
gets clicked. Below is my code that I tried using, the reset button wont reset anything.
Thank you.

    <form id="todoForm">
        <input type="text" id="todoInput" placeholder="Input new note..">
        <input type="text" id="description" placeholder="Input description..">
        <button type="button" id="button" onclick="todoList()">Submit</button>
        <button type="button" id="reset" onclick="resetForm()">Reset</button>
    </form>
    <ol id="todoList">
    </ol>
 
      function todoList() {
    var item = document.getElementById("todoInput").value
    var text = document.createTextNode(item)
    var addItem = document.createElement("li")
    addItem.appendChild(text)
    document.getElementById("todoList").appendChild(addItem)

     var item = document.getElementById("description").value
     var text = document.createTextNode(item)
     var addItem = document.createElement("p")
     addItem.appendChild(text)
     document.getElementById("todoList").appendChild(addItem)
    }

   function resetForm() {
   document.getElementById(todoList).reset();
   }

React forwardRef – access ref within component, and in parent

I need to access the ref to a textarea inside a component. Within the component, its easy enough:

const MyComponent = () => {
  const inputRef = useRef();

  return <textarea ref={inputRef} />
}

Now the ref is available within MyComponent and I can use it for some internal logic.

There are cases where I need to access the ref from the parent component as well. In that case, I can use forwardRef:

const MyComponent = React.forwardRef((props, ref) => {
  return <textarea ref={ref} />
})

// In some parent
const MyParent = () => {
  const inputRefFromParent = useRef();
  return <MyComponent ref={inputRefFromParent} />
}

Now I can access to ref of the textarea from the parent component, and use it for logic within the parent component.

I find myself in a situation where I need to do some internal logic with the ref within MyComponent, but I may also need to get that ref from MyParent. How can I do this?

Error React Proxy error: Could not proxy request

Why do I got this error:

Proxy error: Could not proxy request /api/v1/management/me from localhost:3000 to http://localhost:8080 (ECONNREFUSED).

Got this axios setting:

axios.defaults.baseURL = “http://localhost:3000/”;

And set this in package.json:

“proxy”: “http://localhost:8080”

And have following call:

axios({
  method: "get",
  url: "api/v1/management/me",

When I call directly http://localhost:8080/api/v1/management/me I got response from server.

How can I add a new to-do item to my Ajax web app?

I am currently undertaking the Udacity Full Stack developer “degree” and it seems that the lesson on Ajax is incorrect (the code presented on the lesson does not work) and that is causing trouble to all students who take the course. Their help portal is filled with people questioning why the code wont work and it’s been over 1 year and Udacity has not provided an answer or corrected the material.

I am hoping to find an answer here to help all of the community.

The task is a simple to-do web app with a postgresql database behind it. Please see below for the code and view:

from xmlrpc.client import Boolean
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://antoniofurtado:abc@localhost:5432/todoapp'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

migrate = Migrate(app, db)

class Todo(db.Model):
    __tablename__='todos'
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(), nullable=False)
    completed = db.Column(db.Boolean, nullable=False, default=False)
    
    def __repr__(self):
        return f'<todo {self.id} {self.description}>'

@app.route('/todos/create', methods=['POST'])
def create_todo():
    description = request.get_json()['description']
    todo = Todo(description=description)
    db.session.add(todo)
    db.session.commit()
    return jsonify({
        'description': todo.description
    })

@app.route('/')
def index():
    return render_template('index.html', data=Todo.query.all())



# FLASK-SETUP This code should be at the bottom of all your files.
if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=3000)

The view related to the above code is:

  <html>
  <head>
    <title>Todo App</title>
    <style>
        .hidden {
            display: none;
        }
    </style>
  </head>
  <body>
    <form>
        <input type="text" id="description" name="description" />
        <input type="submit" value="Create" />
    </form>
    <div id="error" class="hidden">Something went wrong!</div>
    <ul>
        {% for d in data %}
        <li>{{ d.description }}</li>
        {% endfor %}
    </ul>
    <script>
        document.getElementById('form').onsubmit = function(e) {
            e.preventDefault();
            fetch('/todos/create', {
                method: 'POST',
                body: JSON.stringify({
                    'description': document.getElementById('description').value
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(jsonResponse) {
                console.log(jsonResponse);
                const liItem = document.createElement('LI');
                liItem.innerHTML = jsonResponse['description'];
                document.getElementById('todos').appendChild(liItem);
                document.getElementById('error').classname = 'hidden';
            })
            .catch(function() {
                document.getElementById('error').classname = '';
            })
        }
    </script>
  </body>
</html>

When I add a new item to the todo list and hit the create button, the item is not added to the database and the page isn’t updated. All that happens is the URL changes to http://127.0.0.1:3000//?description=new+item and the terminal shows 127.0.0.1 - - [02/Mar/2022 00:37:57] "GET /?description=new+item HTTP/1.1" 200 -. The item is not added to the database or displayed on the page.

Can anyone see what the issue is? Any assistance would be hugely helpful to me but also to hundreds of Udacity students who can’t count on Udacity.

React state not updating inside a for loop

I’m trying to run a for loop in a React app which will run through a user defined range of tokens and place bids based on i of the for loop. Sounds very simple, and it is.

However I’m having an issue where I’ve added a block to check whether “isBidding” changes to false, which should then break the for loop. isBidding is a state variable local to the component.

It seems like when the for loop starts, isBidding will always be true, even when the state is changed to false whilst the loop is running. I can’t for the life of me figure out how to ensure the global state variable isBidding gets updated within a for loop.

for (let i = startTokenId; i < endTokenId + 1; i++) {
  // Inside the loop we try to place bids on each token, waiting for user action
  setBidderScanningString(`Bidding on token id #${i} (${i} of ${endTokenId})...`);
  // Try to place the bid
  try {
    await createBuyOrder(i);
  } catch (e) {
    parseBidError(e);
  }
  // Check if loop is over, if so set bidding to false and end
  if (i.toString().toLowerCase() === endTokenId.toString().toLowerCase()) {
    setBidderScanningString('Bidding finished...');
    setIsBidding(false);
    return;
  }
  // Check whether isBidding has been set to false
  if (!isBidding) {
     return;
  }
}

From within the loop I have tried to call a function, which returns the latest isBidding state, however this always evaluates to true.

I have tried to add isBidding in the 2nd condition of the for loop however it still always evaluates to true. I have also tried to add labels and nest it inside a while (isBidding) loop however it still always evaluates to true.

I have also tried moving this code into a useEffect with a dependency on isBidding however the for loop still always returns true.

Is there something blindingly obvious I’m missing?

how to manage [object HTMLDivElement] and get its content?

I have saved an array in local storage and trying to use it but when I console log the localstorage.getitem it returns
[object HTMLDivElement] I have tried to use .innerhtml or [… ] on it but they didn’t work. btw since its an array, I have to use JSON.stringify(movieWatchlistArray):

 localStorage.setItem("key",JSON.stringify(movieWatchlistArray))
 let str =localStorage.getItem("key")
 console.log(JSON.parse(str) )

but when I do this it will return an empty object inside an array while when I console.log the original array it’s fine so I tried to do it without JSON part it worked but returns a string of
[object HTMLDivElement]

 localStorage.setItem("key",movieWatchlistArray)  
 let str =localStorage.getItem("key")
 console.log(str)

so how to get the content of [object HTMLDivElement] I have used .innerhtml but it says can’t use .innerHTML on undefined .

How to add a image on individual primeng steps title on angular 9?

I’m using PrimeNG p-steps on Angular 9 and I want to show a “check” icon/image on each step title when previous screen was complete. I did on last step the behavior I wanted:
enter image description here

I did this changing the css, putting the image on all steps and removing of highlighted:

:host ::ng-deep .ui-steps .ui-steps-item.ui-state-highlight .ui-steps-title{
  font-size: 18px;
  background-image: none; /* This remove image on highlighted step */
}

:host ::ng-deep .ui-steps .ui-steps-item .ui-steps-title{
  font-size: 18px;
  background-image: url('src/assets/img/check-circle-2.png');
  background-repeat: no-repeat;
  background-position: left;
  padding-left: 25px;
}

However, if I am on step 2, the same aproach is not possible because I was adding the image on all steps “unactive” and in this case, the step 3 would affected. So, if it’s possible, how can I put the checked image on example below, only in step 1?
enter image description here

I even tried to find a way to manipulate the CSS by component.ts but I can’t. I tried to put a icon on object in ts file but not works, some like on this post question: How to add images in steps using primeNG for Angular8?.

My implementation :

HTML:

<p-steps id="steps" [model]="steps"></p-steps>

TS component:

steps: MenuItem[];

ngOnInit(): void {

    this.steps = [
      { label: 'Step 1' },
      { label: 'Step 2' },
      { label: 'Step 3' }
    ];
  }

If anyone known a way to identify the fist step title by CSS, could solve the problem.

Thanks!

Adding equals on primitive object

I’m trying to write a generic method so that I can test equality of two variables, for example:

function shallow_equals(x, y) {
    let
        same_type = typeof x === typeof y,
        is_object = typeof x === 'object';

    if (!same_type) return false;
    if (same_type && !is_object) return x === y;

    // treat it as an object
    if (Object.keys(x).length !== Object.keys(y).length) return false;
    for (key of Object.keys(x)) {
        if (x[key] !== y[key]) {
            return false;
        }
    }

    return true;
}


// shallow comparison of two objects
Object.prototype.equals = function(other) {
    console.log('self ==>', this);
    console.log('other ==>', other);
    console.log('shallow equal?', shallow_equals(this, other));
}

let z = 4;
let w = 4;
z.equals(w);

I’m curious why the above doesn’t work, as the two types it gets are:

[Number: 4] --> object
4 --> number

Why does this occur and what would be the proper way to have a function like this?

How do I override the tooltip for the Zoom Out button in amCharts 4?

In our application, users are able to specify what language they want to see text in the UI in. To that end, I’m trying to set the tooltip text on amChart’s zoom out button to the appropriate language string. However, it’s not working. In the code where we configure the zoom out button, I’ve added the following line:

chart.zoomOutButton.tooltipText = zoomOutText;

where zoomOutText is set to the appropriate text for this tooltip in the user’s chosen language. However (and chart is the xyChart that contains the zoom out button), when I select a non-English language and go to a page with the chart, the tooltip remains defiantly in English.

How can I get this override to work? (Or is it even possible?)

Object from echo PHP (Laravel) is not iterable in javascript

I’m trying to iterate an object that is comming from a PHP file via jquery ajax, but even when is a simple array I get an error.

        let addresses = connection ('post',{search: term},'/orders-addresses').then((data)=>{
            // this gets :['address 1', 'addres 2']
            console.log(data);
            return( data );
        });
        
        // This gets: Uncaught TypeError: addresses.map is not a function
        addresses.map((address)=>{
            console.log(address);
        });

        // This gets: Uncaught TypeError: Uncaught TypeError: addresses is not iterable
        for(address of addresses){
            console.log(address);
        }

The PHP (Laravel) code is:

    $addresses = Order::orderBy('address','asc')->select('id','address')->limit(5)->groupBy('address');
    $response = [];

    if($request->search != ''){
        $addresses = $addresses->where('address', 'like', '%' .$request->search . '%');
    }
    
    $addresses = $addresses->get();

    foreach($addresses as $address){
        $response[] = $address->address;
     }

    echo json_encode($response);