Cypress overwrite ‘type’ command to add a small wait throws promise error if .clear() is called before

Not sure quite why this is occurring. I’d like to add a .wait() before all type commands in my app by overwriting the type command. However I’m running into some issues with the promise quirks of cypress.

Here’s some minimal code to reproduce

<html>
<body>
  <input/> 
</body>
</html>
//someSpec.js
cy.get('input').clear().type(name);
//commands.js
Cypress.Commands.overwrite(
  "type",
  (originalFn, subject, text, options) => {
    cy.wait(0).then(() => originalFn(subject,text,options))
  }
);

This will trigger a cypress error complaining about returning a promise:

Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.

The command that returned the promise was:

  > cy.clear()

The cy command you invoked inside the promise was:

  > cy.wait()

Because Cypress commands are already promise-like, you don't need to wrap them or return your own promise.

Cypress will resolve your command with whatever the final Cypress command yields.

The reason this is an error instead of a warning is because Cypress internally queues commands serially whereas Promises execute as soon as they are invoked. Attempting to reconcile this would prevent Cypress from ever resolving.

Can anyone please help me get past this hurdle? Thanks!

Related issues: https://github.com/cypress-io/cypress/issues/3166

How to make content display in three columns instead of one column?

I am a beginner and learning from a tutorial using an API. I would like to change the layout of the design, and instead of having one column, I would like a three column layout. I don’t know if I am using flexbox correctly.

I have tried using row and then having three columns, but somehow its not displaying correctly.I am also using bootstrap.

jsfiddle.net/e5bqsywk/2/

Using Google App Script to find rental cars

Sorry for the rather generic title but making no assumptions on technical solutions…

I am new to Google Apps Script but learning fast. As a fun personal project, I want to build a small application which goes off to Avis and retrieves rental car prices and availability.

I have registered with developer.avis.com and successfully run the following code snippet:

function avis(){

  var avURL = 'https://developer.avis.com/swagger/spec/car_availability.json';
  var avHtml = UrlFetchApp.fetch(avURL).getContentText();
  var avDoc = JSON.parse(avHtml);

}

avDoc comes back as nice structured JSON with all the parameter fields the Avis document says will be needed to retrieve a rental quote.

I assume I now need to fill the parameters in and get avDoc back over to Avis.

But how ? Please indulge this total noob with pointers on how to do so !!

Thanks

How React update component and its children after state change?

I am watching Paul O Shannessy – Building React From Scratch

And i understand the mounting process very well but i have hard day trying to understand how React update a component and its children

The reconciler control the update process by this method:

function receiveComponent(component, element) {
  let prevElement = component._currentElement;
  if (prevElement === element) {
    return;
  }

  component.receiveComponent(element);
}

Component.receiveComponent

 receiveComponent(nextElement) {
    this.updateComponent(this._currentElement, nextElement);
  }

and this is the Component.updateComponent method:

  updateComponent(prevElement, nextElement) {
    if (prevElement !== nextElement) {
      // React would call componentWillReceiveProps here
    }

    // React would call componentWillUpdate here

    // Update instance data
    this._currentElement = nextElement;
    this.props = nextElement.props;
    this.state = this._pendingState;
    this._pendingState = null;

    let prevRenderedElement = this._renderedComponent._currentElement;
    let nextRenderedElement = this.render();
 
    if (shouldUpdateComponent(prevRenderedElement, nextRenderedElement)) {
      Reconciler.receiveComponent(this._renderedComponent, nextRenderedElement);
    } 
  }

This is the part of the code that updates the component after state change, and i assume that it should update the children too, but i can’t understand how this code achieves that, in the mounting process React instantate components to dive deeper in the tree but this doesn’t happen here, we need to find the first HTML element then we can change our strategy and update that HTML element in another place in the code, and i can’t find any way to find any HTML elements this way.

Finding the first HTML is the way to stop this endless recursion and logically this is what i expect from the code is to stop recursion the same way in the mounting process, but this demanded component instantiation so we can delegate to the reconciler that will discover that we are dealing with a wrapper instance of an HTML element not a wrapper instance of a custom component then we can start put thatb html element in the DOM..

This is the code repo on Github

The Newbie to coding [closed]

To all
I’m new to this web site and new to coding. I’m trying to learn AppleScript/JavaScript to write code in Apple Numbers.
Could someone point me in the right direction
Thanks in advance
Jesper

Jest unable to load got libary for testing – ‘SyntaxError: Cannot use import statement outside a module’

I have a pretty simple problem but I can’t for the life of me figure out how to make it work, I’ve spent hours looking online..

I’m using the got library to work with a weather API here is the code below:

import got from 'got';
import dotenv from 'dotenv';
dotenv.config();

class WeatherApi {

  #getApiKey = () => process.env.WEATHER_API;
  
  fetchWeatherData = (city, callback) => {
    const apiKey = this.#getApiKey();
    const apiUrl = `http://api.openweathermap.org/data/2.5/weather?units=metric&q=${city}&appid=${apiKey}`;
    
    got(apiUrl).then((response) => {
      const weatherData = JSON.parse(response.body);
      callback(weatherData)
      });
  }
}

export { WeatherApi } 

The code works perfectly when I run it with node, however when I try and run tests using Jest I get the followig:

  C:UsersalfonOneDriveDocumentsCodingJavaScriptthermostatnode_modulesgotdistsourceindex.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import create from './create.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import got from 'got';
        | ^
      2 | import dotenv from 'dotenv';
      3 | dotenv.config();
      4 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (weather_api.js:1:1)

My issue is that it seems that only the got library has trouble being imported, if I remove it and run Jest dotenv library gets loaded normally. I have no idea what I’m missing here..

Typed.js semicolon glitch

I’m using Typed.js in my website to loop through a bunch of quotes about volunteering. When I saw it running, everything is working how it is supposed to be working. That is until the quote with a semicolon ran through. When it was typing it, everything was fine, but when it was untyping it, it would untype it normally until it got to the semicolon. When it got to the semicolon, it just completely deleted the whole line instead of continuing the animation of untyping it.

Here’s my code:

var data = {
  strings: ["“<i>As you grow older, you will discover that you have two hands — one for helping yourself; the other for helping others.</i>” — Audrey Hepburn", "“<i>Never doubt that a small group of thoughtful, committed citizens can change the world; indeed, it’s the only thing that ever has.</i>”  – Margaret Mead", "“<i>The best way to find yourself is to lose yourself in the service of others.</i>” – Gandhi", "“<i>Volunteering is at the very core of being a human.  No one has made it through life without someone else’s help.</i>” – Heather French Henry", "“<i>Volunteerism is the voice of the people put into action.  These actions shape and mold the present into a future of which we can all be proud.</i>” – Helen Dyer"],
  typeSpeed: 40,
  backSpeed: 20,
  shuffle: true,
  loop: !0
};
new Typed('.animated-text', data);

And here’s a small video to prove it:

https://im3.ezgif.com/tmp/ezgif-3-425cf91d8c.gif

As you can see in the gif, the quote with the semicolon types out just fine, but when it backspaces, or untypes, it doesn’t untypes until the semicolon and just deletes the line. When it goes on the the next quote, a quote that doesn’t a have semicolon, it types and untypes just fine.

My question is why is the happening and how to fix this.

Thank you! Any responses are appreciated!

How can I fetch a javascript file and store the response object as an array?

I am trying to fetch a javascript file and return the response object as an array. My javascript file is simply an array like [“1”, “2”, “3”, …] Here is my code right now:

function getNames() {
 let data = fetch('/path/to/file')
 .then((response) => response.json())
 .then(data => {
   console.log(data);
 return data()
 })
 .catch(error => {
   return error;
 });
}

I need to find a way to use the data variable outside of the function. How can I do this?

Touche event in react-native FlatList not working if item was deleted and readded

I’m doing an app on android using react-native and I have a problem using touche input within my FlatList after removing and adding element to the FlatList.

How the problem happens :

  1. I add one element in my data array and it adds a Button to the FlatList.
  2. I can interact with the Button as expected.
  3. I reset the data array to [].
  4. It removes the Button from the FlatList.
  5. I add another element in my data array and it adds a Button to the FlatList
  6. (PROBLEM start here) even tho the Button appears in the FlatList, I can’t interact with it (I’ve tried other touchable elements like Pressable, TextInput or just using an onPress on an element and I get the same behavior)
  7. If I add another element to the data array, it will add a new working Button (i.e. first Button not working but second Button working)
  8. If I delete n Button and start adding n + m Button again, Then the first n would not work but the m-th last would work.

I reduced the problem to the following small code :

import React, {useState} from 'react';
import {Button, FlatList, View} from 'react-native';

export default function Test() {
  const [data, setData] = useState([]);

  function addData() {
    setData(prev => [...prev, {key: new Date().getTime(), text: 'some text'}]);
  }

  function deleteAllData() {
    setData([]);
  }

  return (
    <View
      style={{
        flex: 1,
      }}>
      <Button title={'ADD'} onPress={() => addData()} />
      <Button title={'DEL'} onPress={() => deleteAllData()} />
      <FlatList
        data={data}
        renderItem={({item, index}) => {
          return (
            <Button
              key={item.key}
              title={`${item.key}`}
              onPress={() => console.log('Clic!')}
            />
          );
        }}
      />
    </View>
  );
}

I think I’m missing something obvious but it’s driving me crazy^^ Any help would be appreciated !

I’m using react-native 0.66.0 and react 17.0.2 testing on my physical android device.

“Child_Process” function Exec hanging on Windows

Before I get bashed for using Guilded over Discord, that isn’t the point of this question. Also, yes this is a Client Mod for Guilded, for which we have been given permission by Guilded to program.

The issue is closing the software, before messing with the files and the opening once we’ve finished the process. Two issues come from both exec commands, I’ve tried solutions I found on other questions, but none were successful, I also tried awaiting SpawnSync, with a callback, no dice.

// Close Guilded, then continue, because we need to make sure Guilded is closed for the new injection.
exec(platform.close).on("exit", () => {
    // Creates path for ReGuilded
    const reguildedPath = resolve(dir || join(process.env.APPDATA || process.env.HOME, ".reguilded"));

    tasks[taskArg](platform, reguildedPath, elevator)
        .then(() => {
            console.info(
                "Relaunching Guilded (If not opened in 10 minutes after this please manually execute the app)"
            );

            // Open the app Again after the injection task is done
            exec(platform.open).on("exit", () => {
                process.exit();
            });
        })
        .catch(err => {
            console.error("Failed to do task", taskArg, ":", err);
        });
});
// platform.close
// Linux: "killall guilded"
// Darwin: "killall Guilded"
// Win32: "taskkill /f /IM Guilded.exe >nul"

// platform.open
// Linux: "/opt/Guilded/guilded& disown"
// Darwin: "/Applications/Guilded.app"
// Win32: join(process.env.LOCALAPPDATA, "Programs/Guilded/Guilded.exe") + " >nul"

All these commands do launch & close Guilded successfully, but the issue lies in the shell, not closing/returning primarily on Windows.

The code is TS at source but gets compiled into JS. Any help or pointers would be helpful. We’re using the latest LTS of Node, and are looking for 100% cross-compatibility.

Reactjs cannot set properties of null (setting ‘currentTime’) [duplicate]

I am trying to solve front-end development libraries projects using React from Freecodecamp.

In Drum Machine App, I am able to replicate almost all the functions but there is a bug and I am not able to identify that.

So, there are 2 set of sounds and there is a checkbox. When checkbox is not checked(default) Set 1 Sounds are played and when checkbox is checked Set 2 sounds are played.

There are 2 ways sounds are generated. By mouse click and by key press[Q,W,E,A,S,D,Z,X,C].

The problem is when the checkbox is checked and I’m trying to generate sound by key press only [C,D] are working rest are showing error cannot set properties to NULL. When checkbox is unchecked all keydown event are working properly.

This is the problem statement : https://www.freecodecamp.org/learn/front-end-development-libraries/front-end-development-libraries-projects/build-a-drum-machine

And here is my code:

App.js

import "./styles.css";
import React, { useState, useEffect } from "react";
import { bankOne, bankTwo } from "./Sounds";
import ReactFCCtest from "react-fcctest";

const KeyboardKey = (props) => {
  const handleKeyDown = (e) => {
    if (e.keyCode === props.sound.keyCode) {
      props.play(props.sound.id, props.volume, props.power);
    }
  };

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
  }, []);

  return (
    <button
      className="drum-pad"
      id={props.sound.keyTrigger}
      onClick={() => props.play(props.sound.id, props.volume, props.power)}
    >
      <audio className="clip" id={props.sound.id} src={props.sound.url} />
      {props.sound.keyTrigger}
    </button>
  );
};

const Keyboard = (props) => {
  return props.sounds.map((sound) => (
    <KeyboardKey
      play={props.play}
      sound={sound}
      power={props.power}
      volume={props.volume}
    />
  ));
};

export default function App() {
  const [power, setPower] = useState(true);
  const [bank, setBank] = useState(false);
  const [volume, setVolume] = useState(0.5);
  const [sounds, setSounds] = useState(bankOne);
  const [soundName, setSoundName] = useState("");

  const play = (key, volume, power) => {
    if (power) {
      setSoundName(key);
      console.log(key);
      const audio = document.getElementById(key);
      console.log(audio);
      console.log(volume);
      audio.currentTime = 0;
      audio.volume = parseFloat(volume);
      audio.play();
    }
  };

  const handleVolumeChange = (e) => {
    if (power) {
      setVolume(e.target.value);
    }
  };

  const handleBankChange = (e) => {
    if (power) {
      setBank(!bank);
      setSounds(e.target.checked ? bankTwo : bankOne);
    }
  };

  const handlePowerChange = (e) => {
    setPower(!power);
  };

  return (
    <>
      <ReactFCCtest />
      <div id="drum-machine">
        <div id="display"></div>
        <Keyboard play={play} sounds={sounds} volume={volume} power={power} />
        {power && (
          <>
            <p>Bank</p>
            <label className="switch">
              <input
                type="checkbox"
                defaultChecked={bank}
                onChange={(e) => handleBankChange(e)}
              />
              <span className="slider rounded" />
            </label>
            <p>{soundName}</p>
            <h3>Volume: {Math.round(volume * 100)} %</h3>
            <input
              max="1"
              min="0"
              type="range"
              step="0.01"
              value={volume}
              onChange={(e) => handleVolumeChange(e)}
            />
            <br />
          </>
        )}
        <p>Power</p>
        <label className="switch">
          <input
            type="checkbox"
            defaultChecked={power}
            onChange={(e) => handlePowerChange(e)}
          />
          <span className="slider rounded" />
        </label>
      </div>
    </>
  );
}

Sounds.js

export const bankOne = [
  {
    keyCode: 81,
    keyTrigger: "Q",
    id: "Heater-1",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
  },
  {
    keyCode: 87,
    keyTrigger: "W",
    id: "Heater-2",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3"
  },
  {
    keyCode: 69,
    keyTrigger: "E",
    id: "Heater-3",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3"
  },
  {
    keyCode: 65,
    keyTrigger: "A",
    id: "Heater-4",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3"
  },
  {
    keyCode: 83,
    keyTrigger: "S",
    id: "Clap",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3"
  },
  {
    keyCode: 68,
    keyTrigger: "D",
    id: "Open-HH",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3"
  },
  {
    keyCode: 90,
    keyTrigger: "Z",
    id: "Kick-n'-Hat",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3"
  },
  {
    keyCode: 88,
    keyTrigger: "X",
    id: "Kick",
    url: "https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3"
  },
  {
    keyCode: 67,
    keyTrigger: "C",
    id: "Closed-HH",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3"
  }
];

export const bankTwo = [
  {
    keyCode: 81,
    keyTrigger: "Q",
    id: "Chord-1",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Chord_1.mp3"
  },
  {
    keyCode: 87,
    keyTrigger: "W",
    id: "Chord-2",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Chord_2.mp3"
  },
  {
    keyCode: 69,
    keyTrigger: "E",
    id: "Chord-3",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3"
  },
  {
    keyCode: 65,
    keyTrigger: "A",
    id: "Shaker",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Give_us_a_light.mp3"
  },
  {
    keyCode: 83,
    keyTrigger: "S",
    id: "Open-HH",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Dry_Ohh.mp3"
  },
  {
    keyCode: 68,
    keyTrigger: "D",
    id: "Closed-HH",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Bld_H1.mp3"
  },
  {
    keyCode: 90,
    keyTrigger: "Z",
    id: "Punchy-Kick",
    url: "https://s3.amazonaws.com/freecodecamp/drums/punchy_kick_1.mp3"
  },
  {
    keyCode: 88,
    keyTrigger: "X",
    id: "Side-Stick",
    url: "https://s3.amazonaws.com/freecodecamp/drums/side_stick_1.mp3"
  },
  {
    keyCode: 67,
    keyTrigger: "C",
    id: "Snare",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Brk_Snr.mp3"
  }
];

PS: Some of my code is from a Tutorial.

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘data’)

I’m building out CRUD functionality and create had worked the other day with the same code in the component, but now it is giving an error:

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading ‘data’)

I’m getting an error with the validations, and not sure if it has to do with props. Here is the code where the error exists:

> 30 |     const errorResponse = err.response.data.errors;
     | ^  31 |     const errorArr = [];
  32 |     for (const key of Object.keys(errorResponse)) {
  33 |         errorArr.push(errorResponse[key].message)```

Is anyone familiar with this issue and knows how to fix it?

adding and subtracting a string-number works differently in javascript

HTML

<body>
    <h1>Counter</h1>
    <p id="num">0</p>
    <div>
        <button id="minus">-</button>
        <button id="plus">+</button>
    </div>
    <script src="src/main.js"></script>
</body>

JS

const num = document.getElementById('num')
const minus = document.getElementById('minus')
const plus = document.getElementById('plus')

minus.addEventListener('click', () => {
  num.textContent -= 1;
})

plus.addEventListener('click', () => {
  num.textContent += 1;
})

This is a simple counter app. If I press minus btn, it acts as expected (i.e. subtracts 1 from number)
But if I press plus, I get a string concatenation (i.e. ’01’)

I’m confused here. Why one acts like a number and the other string? it seems like there is a auto-conversion of type in very inconsistant way.

and what would be the best practice to fix ‘plus’?

Why regex matches when tested but not being captured in String replacement

I am trying to perform the following String replacement via regex.

This is the String.

let originalStr = 'localhost:3000/sample/prospect/card/intl/name?ref=-huNn';

I am replacing the String via following implementation where I am calling 2 different regex replacements on the original string.

// this works 
originalStr = originalStr.replace(`/name`, `/${router.location.query.ref}`); 

// This is the issue. Not replacing. 
// There is an OR in this regex cos I want to replace even if there is no `/card` in the String.
originalStr = originalStr.replace(//prospect/card/|/prospect//, '/prospect/cards/'); 

This is the current updated String.

localhost:3000/sample/prospect/card/intl/-huNn?ref=-huNn

I was expecting it to be the following:

localhost:3000/sample/prospect/cards/intl/-huNn?ref=-huNn // cards instead of card

When tested via https://regex101.com/, the regex is capturing the value correctly.

But in code. the replacement is not happening. What am I doing wrong with this regex?