Graphql Apollo Client query by ID

I’m new to GraphQL and I’m trying to build a work around project for training purposes.

For this project I’m using an external GraphQL API to get some movies.
I’m making my requests through Apollo-Client the newest version and display them within a small react native app and the useQuery hook from the Apollo-Client library. No particular backend for this app.

I’m currently trying to display 2 different screens :

  • The main one with a list of all the movies. Got them with this query :
const GET_MOVIES = gql `
{
allMovies {
movies {
title 
id } 
  } 
} 
`

Everything is ok so far. But I’m stuck with the next part. I’m trying to use this id i got from a movie (map through movies) as a variable for my next request which i want to use to display my next screen. The movie screen.

I got the id but i don’t know how to use it as a variable and pass it to my query to then get all the movie informations i need from this particular movie.

I found something like this :

const GET_THIS_MOVIE = gql `
{
movie (id : $movieID) {
title
.... 
.... 
  } 
} 
`

But i don’t know how to use the id i got as this movieID variable. Knowing this id will change depending on the movie selected.

A precise answer with some code would be really appreciated as im new to GraphQL

Thanks for your help !

How to setFormulas() to a range using Google Apps Script?

What do I need to change so that this script sets the formulas (from row 2) to the range defined?
The code below doesn’t give me any error, but it doesn’t set the formulas at all.

  var lc = sheet.getLastColumn();
  var range = sheet.getRange(2, 1, 1, lc);
  var formulas = range.getFormulas();
  
  range.copyFormatToRange(sheet, 1, lc, 3, 3+response); //This pastes the format to the range, whose number of rows is defined depending on the # that the user inputs.

  var pasteTo = sheet.getRange(3, 1, response, lc);//Defines the range for setting formulas
  for (var a = 3; a < response; a++){
    pasteTo = sheet.getRange("A" + a,sheet.getLastColumn());
    pasteTo.setFormulas(formulas);
  }
  }
}

Error (‘httpResponse is not defined’)Not sure where I’ve gone wrong but getting this error

Been trying to get this code to work for a while now can’t see where I’m going wrong when I try to ‘open with live server’ on visual studio code and inspect the page I can see I’m getting the error:

GET  https://txvxu97okj3q.usemoralis.com:2053/server/functions/getNFT?_ApplicationId=hvSK2mZVUIMqGoMT8CJA06NJG8KPEAjrt2ZlLokl&nftId=1 400

and then also,

{code: 141, error: 'httpResponse is not defined'}
code: 141
error: "httpResponse is not defined"

not sure where the error is would greatly appreciate any help 🙂

Moralis.start({ serverUrl: "https://txvxu97okj3q.usemoralis.com:2053/server", appId: "hvSK2mZVUIMqGoMT8CJA06NJG8KPEAjrt2ZlLokl" });
    
function fetchNFTMetadata(NFTs){
  for (let i = 0; i < NFTs.length; i++) {
    let nft = NFTs[i];
    let id = nft.token_id;
        
//Call Moralis Cloud function -> Static JSON file 
        
  fetch("https://txvxu97okj3q.usemoralis.com:2053/server/functions/getNFT?_ApplicationId=hvSK2mZVUIMqGoMT8CJA06NJG8KPEAjrt2ZlLokl&nftId=" + id)
  .then(res => res.json())
  .then(res => console.log(res))
  }
}

async function initializeApp(){
    let currentUser = Moralis.User.current();
    if(!currentUser){
        current = await Moralis.Web3.authenticate();
    }

    const options = { address: "0x3be1812365e150157a326a8d0860a72fadee2db0", chain: "rinkeby" };
    let NFTs = await Moralis.Web3API.token.getAllTokenIds(options);
    console.log(NFTs);
    fetchNFTMetadata(NFTs.result);
}

initializeApp();

{code: 141, error: ‘httpResponse is not defined’}

Convert HTML string to JSX string?

Is there is a tool or quick way to convert arbitrary HTML strings to valid JSX strings? And by string, I mean an actual string.

const htmlString = "<button class="foo" onclick="..." >Hello World</button>"
const jsxString = htmlStringToJsxString(htmlString)
console.log(jsxString)

And my desired output:

"<button className="foo" onClick="..." >Hello World</button>"

I’m not trying to parse HTML then render JSX, nor am I injecting HTML into the DOM. I specifically need to convert an HTML string to the conventions of JSX (camel-casing attributes, replacing “class” with “className”, etc).

Using two querySelector in js

I’m trying to use js in a way that when you hover the mouse over text links, the background image changes with each link.
I’ve been able to initiate the Event Listener to the link texts but am unable to direct the output to the background image div (style elemet)

Here is my html code

<div id="livestream">  
      </div>
      <div id="wedding">  
      </div>
      <div id="documentary">  
      </div>

      <div class="container text-box">
          <a href="#">Livestreaming</a> 
          <a href="#">Weddings</a>
          <a href="#">Documentaries</a>
      </div>

My css, which im stuck too;

.landing #documentary{
    background-image: url("/img/pic-01.jpg");
    background-size: cover;
    height: 100vh;
    z-index: -1;
}

.landing #livestream, #wedding, #documentary{
    display: none;
}

.text-box a:nth-child(1):hover{
    color: #e08416;
    transition: 0.4s ease;}
}

And here is my js code

document.querySelector('.text-box a:nth-child(1)').addEventListener('mouseenter', entering);
document.querySelector('.text-box a:nth-child(1)').addEventListener('mouseleave', leaving);

function entering(ev){
    ev.currentTarget.style.display = "block";
    console.log('mouseenter  a');
}

function leaving(ev){
    ev.currentTarget.style.display = "none";
    console.log('mouseleave a');
}

I got stuck here

How can I call Discord.js functions from a lib.js file into index.js?

I am trying to have a separate class full of my functions so index.js doesn’t get cluttered up. The problem I encountered is that my new lib.js file cannot work with discord.js. I am planning on adding multiple, more complex functions, so replacing lib.start() with msg.channel.send('Game Started') won’t fix my issue. Is there a way I can get discord.js commands to work in lib.js so I can call them into index.js?

index.js

const Discord = require('discord.js')
const client = new Discord.Client();

const lib = require("./classes/lib");

const { token } = require('./Data/config.json');

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
})

client.on('message', async msg => {
  if(msg.content.startsWith("m!")) {
    const command = msg.content.substring(2)

    switch(command) {
      
      //Calling 'start()'
      case "start game" : lib.start(); break;
    
      default: msg.channel.send('Unknown Command');
    
    }
  } 
})

client.login(token)

lib.js

function start() {
    msg.channel.send('Game Started');   //Trying to get this to work
}

module.exports = {start};

I am trying to retrieve data from a single key in firebase

var ratingRef = firebase.database().ref(“hollywood/”); ratingRef.orderByValue().on(“value”, function(data) { data.forEach(function(data) { var name = (“The ” + data.val().name + ” rating is ” + data.val().director +data.val().
year);
var pic= data.val().src;
alert(pic)
var fame= $(“#tame”).attr(“src”,pic +””)
$(“#test”).append(name +”
“);
}); });

Why is my confirm password field not firing validation at all (react-hook-form)

Here is a codesandbox to see my problem replicated: https://codesandbox.io/s/inspiring-haslett-1c8sw?file=/pages/index.js

I want to ensure the confirmPassword field matches the password field, however it will always say “Passwords match”, it never changes.

I have followed the docs however I cannot seem to get the functionality im after. I have set the mode to onChange

Here is my form:

import { SubmitHandler, useForm, useFormState } from "react-hook-form";

function IndexPage() {
  //Hook form
  const {
    register,
    watch,
    formState: { errors, isValid, dirtyFields }
  } = useForm({
    mode: "onChange",
    defaultValues: {
      email: "",
      password: "",
      confirmPassword: "",
      username: "",
      firstName: "",
      surname: "",
      isShop: false
    }
  });
  const { password } = watch();

  const [passwordFocused, setPasswordFocused] = useState(false);

  const onSubmit = async (data) => {
    //submit here
  };

  return (
    <>
      {/* NEW SIGNUP FORM */}
      <main className="min-h-screen flex">
        <div className="w-full flex flex-col py-12 md:w-1/2 flex-grow min-h-full">
          <div className="mt-6 h-full w-full flex flex-col md:w-96 mx-auto">
            <form
              onSubmit={onSubmit}
              autoComplete="off"
              className="space-y-6 relative flex flex-col w-full flex-1"
            >
              <span className="flex-1"></span>
              {/* STEP 1*/}
              <div>
                <div className="space-y-1">
                  <label
                    htmlFor="password"
                    className="block text-sm font-medium text-gray-700"
                  >
                    Password
                  </label>
                  <div className="mt-1">
                    <input
                      {...register("password", {
                        required: true,
                        minLength: 8,
                        maxLength: 50,
                        pattern: /^(?=.*[A-Za-z])(?=.*d)[A-Za-zd@$!%*#?&^_-]{8,}$/
                      })}
                      id="password"
                      name="password"
                      type="password"
                      autoComplete="current-password"
                      required
                      className="input w-full"
                      onFocus={() => {
                        setPasswordFocused(true);
                      }}
                      onBlur={() => {
                        setPasswordFocused(false);
                      }}
                    />
                    <span
                      className={`${
                        passwordFocused && errors.password
                          ? "max-h-46 opacity-100"
                          : "max-h-0 opacity-0"
                      } duration-500 ease-in-out transition-all flex flex-col overflow-hidden`}
                    >
                      <p className="text-gray-600 mt-2">
                        Passwords must contain:
                      </p>
                      <ul className="space-y-2">
                        <li
                          className={`mt-2 ${
                            password.length >= 8
                              ? "text-green-600"
                              : "text-gray-600"
                          }`}
                        >
                          At least 8 characters
                        </li>
                        <li
                          className={`mt-2 ${
                            /[A-Z]/.test(password)
                              ? "text-green-600"
                              : "text-gray-600"
                          }`}
                        >
                          Upper and lower case characters
                        </li>
                        <li
                          className={`mt-2 ${
                            /d/.test(password)
                              ? "text-green-600"
                              : "text-gray-600"
                          }`}
                        >
                          At least one digit
                        </li>
                      </ul>
                    </span>
                  </div>
                </div>
                <div
                  className={`space-y-1 ${
                    !errors.password && dirtyFields.password
                      ? "visible"
                      : "invisible"
                  } `}
                >
                  <label
                    htmlFor="password"
                    className="block text-sm font-medium text-gray-700"
                  >
                    Confirm password
                  </label>
                  <div className="mt-1">
                    <input
                      {...register("confirmPassword", {
                        validate: (value) =>
                          value === password || "Passwords do not match"
                      })}
                      id="confirm-password"
                      name="confirm-password"
                      type="password"
                      autoComplete="confirm-password"
                      required
                      className={`input w-full`}
                    />
                  </div>
                  {errors.confirmPassword
                    ? "Passwords do not match"
                    : "Passwords match"}
                </div>
              </div>
            </form>
          </div>
        </div>
      </main>
    </>
  );
}

export default IndexPage;

JavaScript to use a different proxy link if the first one returns a 404 error

I have some JS that works as follows:
If the Word Count button is pressed, go to the Word Count function, if the status of the requested page is 200, then let the url be proxyURL, which is defined correctly in index.html and this as it stands works.

I have then added an else if statement to say if a 404 is returned, then go to the function “WordCountProxyBackup” function, which works the same way as the original, but instead of using “proxyURL”, it uses proxybackupURL, which is defined in index.html

I have intentionally broken by original proxyURL to try and test this, and a 404 is returned, but the button is not finding it’s way to the backup function to then find it’s way to the backup link, can someone help with this? The code is below.

   function Wordcount()
{
    $(".operation").attr('disabled', true);
    this.disabled = true;
    let xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var j = JSON.parse(this.response);
            document.getElementById('output').value = j.answer;
        }else if (this.readyState == 4 && this.status == 404) {
            document.getElementById('output').value = "Error Bad Pathway - Rerouting";
            WordcountProxyBackup();
        }
    };

    let url = proxyURL + "/?text=" + encodeURI(document.getElementById('content').value) + "&route=" + "wordcount";
    xhttp.open("GET",url);
    xhttp.send();
    $(".operation").attr('disabled', false);
}

function WordcountProxyBackup()
{
    $(".operation").attr('disabled', true);
    this.disabled = true;
    let xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var j = JSON.parse(this.response);
            document.getElementById('output').value = j.answer;
        }else if (this.readyState == 4 && this.status == 500) {
            document.getElementById('output').value = "Error Bad Pathway - Rerouting";
            WordcountProxyBackup2();
        }
    };

    let url = proxybackupURL + "/?text=" + encodeURI(document.getElementById('content').value) + "&route=" + "wordcount";
    xhttp.open("GET",url);
    xhttp.send();
    $(".operation").attr('disabled', false);
}

How to force an Iframe to reload its source every time a page is opened?

I tried to find a solution to my problem for a few hours and I can’t seem to find it so here is my problem…

I’m not into coding and I’m a complete noob in making websites so bear with me please, I’m trying

I’m using an iframe generator to display a “moving fluid script” that I uploaded to a directory on my website (it’s displayed at ex: mywebsite.com/fluid) and every time that I open that page that script always starts its thing from the start but when I implement it on a homepage with iframe it doesn’t load every time from the beginning like on the mywebsite.com/fluid

I’m sorry if I didn’t explain it correctly but I hope someone understands my problem…

Is there a better way to show content from that page to my homepage but that I still have the ability to use Elementor to add some stuff over that “fluid script” or a way to force iframe to always show the script from the start as its seen when I visit mywebsite.com/fluid?

Thanks!

sum input fields value if they have the same value

I’m getting stuck on the logic to use to accomplish this in javascript/jquery and could use some help if anyone had any ideas.

I have table which shows the per item cost of the products on an invoice.

The goal is to find all the products by their class(currently shirtcountrow and hoodiecountrow but there will be more later) and combine the ones that have the same value.

The table currently looks like this:

<table id="productmathtable">
<tr>    
<td>Shirt</td>       
<td><input class="shirtcountrow" type="text" value="4" style="width:60px"> x <input class="productpricerow" type="text" value="25" style="width:60px"> = </td>      
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="100" style="width:60px"></td>
</tr>
<tr>         
<td>Shirt</td>       
<td><input class="shirtcountrow" type="text" value="2" style="width:60px"> x <input class="productpricerow" type="text" value="25" style="width:60px"> = </td>       
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="50" style="width:60px"></td>       
</tr>
<tr>         
<td>Shirt</td>       
<td><input class="shirtcountrow" type="text" value="2" style="width:60px"> x     <input class="productpricerow" type="text" value="25" style="width:60px"> = </td>      
 <td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="50" style="width:60px"></td>     
 </tr><tr>       
<td>Hoodie</td>     
 <td><input class="hoodiecountrow" type="text" value="4" style="width:60px"> x <input class="productpricerow" type="text" value="35" style="width:60px"> = </td>         
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="140" style="width:60px"></td>      
</tr>
<tr>         
 <td>Hoodie</td>        
 <td><input class="hoodiecountrow" type="text" value="4" style="width:60px"> x <input class="productpricerow" type="text" value="35" style="width:60px"> = </td>         
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="140" style="width:60px"></td></tr>     
</table>

And I want it to look like this after a jquery/javascript function is preformed:

<table id="productmathtable">
<tr>    
<td>Shirt</td>       
<td><input class="shirtcountrow" type="text" value="8" style="width:60px"> x <input class="productpricerow" type="text" value="25" style="width:60px"> = </td>      
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="200" style="width:60px"></td>
</tr> 
<td>Hoodie</td>     
 <td><input class="hoodiecountrow" type="text" value="8" style="width:60px"> x <input class="productpricerow" type="text" value="35" style="width:60px"> = </td>         
<td class="tabletotalrow"><input class="productotalrow totalrow" type="text" value="280" style="width:60px"></td>      
</tr>   
</table>

I am pretty sure i need to change my html so it’s easier to identify each part that i want to change, but im not exactly sure how

Why doesnt my HTML load on my browser and how can i fix it?

i am currently working on an eCommerce website and I’ve got the HTML and CSS codes down. Right now, i am currently working on the JavaScript for the add to cart functionality.
i have an array of 48 objects of products.
const products = [
{
id: 0,
name: “product one”,
price: 3000,
instock: 10,
category: “first”,
description:
“lhjsdbf whaiudehwi hlawbdiw lawdhawiudh IWUEHiawb hjabd”,
imgsrc: “img/jeans.jpg”,
},..]
and as a result, the page doesn’t load on my browser. i have also decided to instead make 4 array of products objects but that messes with the add to cart functionality even though the page loads.
merging the 4 arrays into one doesn’t work either. gives the same problems as a single array would.

what can i do?

Please explain how does this JS piece of code work?

my javascript is rusty, and I am having trouble understanding the code is hosted at w3schools – https://www.w3schools.com/howto/howto_js_cascading_dropdown.asp. But the full code I will add below.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
var subjectObject = {
  "Front-end": {
    "HTML": ["Links", "Images", "Tables", "Lists"],
    "CSS": ["Borders", "Margins", "Backgrounds", "Float"],
    "JavaScript": ["Variables", "Operators", "Functions", "Conditions"]    
  },
  "Back-end": {
    "PHP": ["Variables", "Strings", "Arrays"],
    "SQL": ["SELECT", "UPDATE", "DELETE"]
  }
}
window.onload = function() {
  var subjectSel = document.getElementById("subject");
  var topicSel = document.getElementById("topic");
  var chapterSel = document.getElementById("chapter");
  for (var x in subjectObject) {
    subjectSel.options[subjectSel.options.length] = new Option(x, x);
  }
  subjectSel.onchange = function() {
    //empty Chapters- and Topics- dropdowns
    chapterSel.length = 1;
    topicSel.length = 1;
    //display correct values
    for (var y in subjectObject[this.value]) {
      topicSel.options[topicSel.options.length] = new Option(y, y);
    }
  }
  topicSel.onchange = function() {
    //empty Chapters dropdown
    chapterSel.length = 1;
    //display correct values
    var z = subjectObject[subjectSel.value][this.value];
    for (var i = 0; i < z.length; i++) {
      chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
    }
  }
}
</script>
</head>   
<body>

<h1>Cascading Dropdown Example</h1>

<form name="form1" id="form1" action="/action_page.php">
Subjects: <select name="subject" id="subject">
    <option value="" selected="selected">Select subject</option>
  </select>
  <br><br>
Topics: <select name="topic" id="topic">
    <option value="" selected="selected">Please select subject first</option>
  </select>
  <br><br>
Chapters: <select name="chapter" id="chapter">
    <option value="" selected="selected">Please select topic first</option>
  </select>
  <br><br>
  <input type="submit" value="Submit">  
</form>

</body>
</html>

How does this part of the code work?

for (var x in subjectObject) {
    subjectSel.options[subjectSel.options.length] = new Option(x, x);
  }
  subjectSel.onchange = function() {
    //empty Chapters- and Topics- dropdowns
    chapterSel.length = 1;
    topicSel.length = 1;
    //display correct values
    for (var y in subjectObject[this.value]) {
      topicSel.options[topicSel.options.length] = new Option(y, y);
    }
  }
  topicSel.onchange = function() {
    //empty Chapters dropdown
    chapterSel.length = 1;
    //display correct values
    var z = subjectObject[subjectSel.value][this.value];
    for (var i = 0; i < z.length; i++) {
      chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
    }
  }

Im not understanding completely how the code works. Please correct me where I falter.

  • var subjectSel = document.getElementById("subject"); this gets the value of the option that is currently selected in the dropdown right?
  • im not sure what this means for (var x in subjectObject) { subjectSel.options[subjectSel.options.length] = new Option(x, x);. is it counting the number of options in the dropdown? what is new Option(x, x)?
  • subjectSel.onchange basically says if the 1st dropdown changes then do the following code. does chapterSel.length = 1; select the 1st option in the 2nd dropdown being what is already in the html – please select subject first?
  • for (var y in subjectObject[this.value]) { topicSel.options[topicSel.options.length] = new Option(y, y); } . What happens here? similar to the first dropdown, is it counting the number of the options in the dropdown?

Im not sure at what point or how it is determined which piece of information in the subjectobject object is put into which dropdown. how is the following 3 lines associated:

for (var x in subjectObject) {
 for (var y in subjectObject[this.value]) {
var z = subjectObject[subjectSel.value][this.value];
    for (var i = 0; i < z.length; i++) {

I can guess that it is linked to the object subjectobject, and I can see that “this.value” is getting nested further and further to select the relevant values. can you explain further how it is picking the value of the array and not the id, i.e. html,css, javascript, and not 0,1,2?

thanks in advance for your help