const students = [{
name: 'Quincy',
grade: 65
}, {
name: 'Jason',
grade: 65
}, {
name: 'Alexis',
grade: 100
}, {
name: 'Sam',
grade: 65
}, {
name: 'Katie',
grade: 90
}]
Category: javascript
Category Added in a WPeMatico Campaign
UseState – Invalid hook call. Hooks can only be called inside the body of a function component
-
I am using useState to update response from API.
-
Then I am taking the data I need, and map them in a new array (arr)
-
After the above step I am updating the “setData” useState hook to use “data” state
-
But it is giving me Error
“Invalid hook call. Hooks can only be called
inside the body of a function component “
Here is the part of the code i am facing problem with
import {useEffect, useState} from 'react'
import logo from './logo.svg';
import './App.css';
import axios from 'axios'
import ReactSearchBox from 'react-search-box'
import { set } from 'express/lib/application';
function App() {
let [data, setData] = useState()
useEffect(onMount,[])
function onMount(){
axios.get('https://restcountries.com/v3.1/all').then(res=>{
let arr = res.data.map((c)=>{
return {key:c.name.common, value: c.name.common}
})
setData(arr)
})
}
My Full Page Code
import "./styles.css";
import axios from 'axios'
import ReactSearchBox from 'react-search-box'
import {useEffect, useState} from 'react'
export default function App() {
let [data, setData] = useState()
useEffect(onMount,[])
function onMount(){
axios.get('https://restcountries.com/v3.1/all').then(res=>{
let arr = res.data.map((c)=>{
return {key:c.name.common, value: c.name.common}
})
setData(arr)
})
}
return (
<div className="App">
<h1>Countries</h1>
{data.length>0 ? <ReactSearchBox
placeholder="Placeholder"
value="Doe"
data={data}
callback={(record) => console.log(record)}
/>: null}
</div>
);
}
Picture of Error
Fetch Auth User(s) UID from Firebase via server side
Puppeteer how to block DOM element from loading
For my project I am trying to use puppeteer to block a paywall on a website, but using a mutation observer does not seem to work. Here is a link to the article with the paywall: https://www.nytimes.com/2022/06/18/world/europe/odesa-opera-ukraine-russia.html.
I am using page.evaluate to modify the article and trying to return the article without a paywall. To do this I am blocking the id #gateway-content which stops the paywall. However, the mutation observer does not seem to find the id. Here is the code:
await page.goto(URL, {
waitUntil: 'networkidle0',
});
const content = await page.evaluate(async () => {
function removeTheElement (...elements) {
for (const element of elements) {
if (element) { element.remove(); }
}
}
function blockElement (selector, blockAlways = false) {
new window.MutationObserver(function (mutations) {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node instanceof window.HTMLElement) {
if (node.matches(selector)) {
removeTheElement(node);
if (!blockAlways) {
this.disconnect(); // Stop watching for element being added after one removal
}
}
}
}
}
}).observe(document, { subtree: true, childList: true });
}
const previewButton = document.querySelector('.css-3s1ce0');
if (previewButton) { previewButton.click(); }
blockElement('.css-3fbowa'); // Prevent bottom dock from appearing
blockElement('#gateway-content'); // Remove paywall
blockElement('.css-1bd8bfl'); // Remove filter
// Restore scrolling
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
document.querySelector('.css-mcm29f').setAttribute('style', 'position:relative');
}
};
return document.documentElement.outerHTML;
});
await browser.close();
response.send(content);
After response.send is sending back the content to display it. The code works when I used it as a chrome extension, but with puppeteer the code breaks. Here is a link to the chrome extension: https://github.com/iamadamdev/bypass-paywalls-chrome/blob/master/src/js/contentScript.js (Under the domain nytimes.com). I do not get any errors, but the mutation observer does not do anything and I am not sure how to fix it. Any help would be greatly appreciated.
Canvas sketch, how to animate so transition is smooth
I’m working with generative design production in javascript, and I like what I’ve got so far.
The last step I’m hoping for is to see this transition less like a gif, and more smoothly as an animation. In a different assignment, I saw how to make points move on the screen — is this possible in a similar way with arcs here?
const canvasSketch = require('canvas-sketch');
const math = require('canvas-sketch-util/math');
const random = require('canvas-sketch-util/random');
const settings = {
dimensions: [ 1080, 1080 ],
animate: true,
fps: 1.2,
playbackRate: 'throttle'
};
const degToRad = (degrees) => {
return degrees / 180 * Math.PI;
};
const randomRange = (min, max) => {
return Math.random() * (max - min) + min;
}
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = '#ccebff';
context.fillRect(0, 0, width, height);
context.fillStyle = '#d78465';
const cx = width * 0.5;
const cy = height * 0.5;
const w = width * 0.008;
const h = height * 0.3
let x,y;
const num = 12;
const radius = width * 0.2;
for (let i = 0; i < num; i++) {
const slice = math.degToRad(360 / num);
const angle = slice * i;
x = cx + radius * Math.sin(angle);
y = cy + radius * Math.cos(angle);
// spokes
// context.save();
// context.translate(x,y);
// context.rotate(-angle);
// context.scale(random.range(0.8, 2), random.range(0.3, 0.9));;
// context.beginPath();
// context.rect(-w * 0.6, random.range(0, -h * 0.5), w, h);
// context.fill();
// context.restore();
// light blue spirals, inner
context.save();
context.translate(cx, cy);
context.rotate(-angle);
context.lineWidth = random.range (5, 20);;
context.beginPath();
context.strokeStyle = '#52bafc';
context.arc(0, 0, radius * random.range(0.7, 1.8), slice * random.range(0, -5), slice * random.range(1, 7));
context.stroke();
context.restore();
// dark blue spirals, outer
context.save();
context.translate(cx, cy);
context.rotate(-angle);
context.lineWidth = random.range (8, 15);;
context.beginPath();
context.strokeStyle = 'blue';
context.arc(0, 0, radius * random.range(0.9, 2), slice * random.range(1, -8), slice * random.range(1, 6));
context.stroke();
context.restore();
}
};
};
canvasSketch(sketch, settings);
Why can’t this if statement do 2 things? [duplicate]
I’m trying to update the counter and use it so I can switch the question each time but it only works if i remove the counter +=1, help please!
Code below:
const questions= [
"What is Orochimaru's last name?",
"What is Sasuke's least favorite food?",
"What was Itachi's girlfriend's name?"
]
const correctAnswers= ["None", "sweets", "Izumi"]
const counter= 0 //for keeping track of answer alignment
//const score= 0 //keeps track how many they get right
submitButton.onclick= function(){
if (answer_a.checked == true && labelA.textContent == correctAnswers[counter]) {
counter +=1 //will work if I delete counter+=1 and replace counter as 1
questionContainer.innerHTML = questions[counter]
}
CSS – Issues animating child on parent hover?
I have looked at Move HTML element upwards on hover and I know how to define the CSS animation I want, however given the other animations at play in this snippet I am running into issues animating a child element on parent hover.
Snippet:
html,
body {
padding: 0;
margin: 0;
font-family: "sequel-sans-roman", -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
.container {
padding: 0 2rem;
}
.main {
min-height: 100vh;
padding: 4rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
.navIcon {
display: inline-block;
flex-grow: 1;
}
.nav {
display: flex;
justify-content: space-between;
width: 100%;
margin-top: 2.4em;
/* coordinates w height of line away from link, MUST BE = */
}
.snip1168 {
text-align: center;
text-transform: uppercase;
}
.snip1168 * {
box-sizing: border-box;
}
.snip1168 li {
display: inline-block;
list-style: outside none none;
margin: 0 1.5em;
padding: 0;
}
.snip1168 a {
padding: 2.4em 0 0.5em;
/* height of line away from link */
color: rgba(0, 0, 0, 1);
position: relative;
text-decoration: none;
}
.snip1168 a:before,
.snip1168 a:after {
position: absolute;
-webkit-transition: all 0.35s ease;
transition: all 0.35s ease;
}
.snip1168 a:before {
top: 0;
display: block;
height: 3px;
width: 0%;
content: "";
background-color: black;
}
.snip1168 a:hover:before,
.snip1168 .current a:before {
opacity: 1;
width: 100%;
}
.snip1168 a:hover:after,
.snip1168 .current a:after {
max-width: 100%;
}
.mainText {
text-transform: uppercase;
font-size: 1.1rem;
}
<div class='container'>
<main class='main'>
<div class='nav'>
<div class='navIcon'>
<img src="https://picsum.photos/40" height={40} width={40} />
</div>
<ul class='snip1168'>
<li class='current'><a href="#" data-hover="Work">Work</a></li>
<li><a href="#" data-hover="Recs">Recs</a></li>
<li><a href="#" data-hover="Say Hi">Say Hi</a></li>
</ul>
</div>
</main>
</div>
This is the animation I want to apply to only the text of the nav bar (not the animated lines) on hover of the whole <li> :
transition: transform ease 400ms;
transform: translate(0, -10px);
Without breaking the existing line animations, how can I animate move only the text of these nav items on hover of each parent <li>?
JSON file generated by cypress-cucumber-preprocessor only contains one scenario
i have the following issue using Cucumber with cypress. I have the following feature file:
Feature: Validate search.
As a user i want to validate a search using different pages
Scenario: Make a search using google
Given Enter to google
Then I Make a search
And I validate the results
Scenario: Make a search using yahoo
Given I enter to Yahoo
Then I Make a search
And I validate the results
When i execute all the tests pass, however, when i check the Json file generated by cucumber only the informarion of the last Scenario (Make a search using yahoo) is displayed. Does anyone know a way to make the two scenarios appear in the JSON file?
Thanks!
Angular application is not loading my component path when manually navigated to in the browser
My application starts on a login page which has a button to a create-account page.
If I am on the create-account page and I refresh my browser, it goes back to the login page.
Why is that? I tried reading through the documentation to find a solution, but it wasn’t entirely clear. I can see from the browser that if I manually navigate to http://localhost/create-account, it returns a 301 and goes back to the login page. What must be done to the route to fix this in order to allow create-account to be hit?
Here is my app-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CreateAccountComponent } from './create-account/create-account.component';
import { LoginComponent } from './login/login.component';
import { PasswordResetComponent } from './password-reset/password-reset.component';
const routes: Routes = [
{ path: "login", component: LoginComponent },
{ path: "create-account", component: CreateAccountComponent },
{ path: "password-reset", component: PasswordResetComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Unable to embed vega-lite visualization in react
I am trying to use vega-lite in react. I tried below (check on codesandbox) and its working:
Attempt 1 – data hardcoded in spec (working)
radialChart.js
import { createClassFromSpec } from "react-vega";
export const RadialChart = createClassFromSpec({
spec: {
$schema: "https://vega.github.io/schema/vega-lite/v5.json",
data: {
values: [
{
"i-type": "A",
count: 3,
color: "rgb(121, 199, 227)"
},
{
"i-type": "B",
count: 20,
color: "rgb(26, 49, 119)"
},
{ "i-type": "C", count: 24, color: "rgb(18, 147, 154)" }
]
},
description: "A simple pie chart with labels.",
encoding: {
theta: { field: "count", type: "quantitative", stack: true },
color: { field: "color", type: "nominal", legend: null, scale: null }
},
layer: [
{
mark: { type: "arc", outerRadius: 80 }
}
]
}
});
index.js
import { RadialChart } from "./radialChart.js";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>react-vega-lite test</h1>
<RadialChart />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
It renders:
Attempt 2 – dynamic data as suggested by docs (not work,g)
However, as you can see, data is hardcoded in radialChart.js. But I wanted to dynamically pass the data. So, I checked the docs and found this. It suggests following changes:
radialChart.js
...
"data": [{ "name": "table" }],
...
radialData.js
const data = [ ... whole data array goes here ... ];
export default data;
index.js
import radialData from "./radialData";
//...
<RadialChart data={{ table: radialData }} />
However its still not working and it gives following error:
Error: Unrecognized data set: table
at error (https://d78mhq.csb.app/node_modules/vega-util/build/vega-util.module.js:517:9)
at dataref (https://d78mhq.csb.app/node_modules/vega-view/build/vega-view.module.js:75:31)
at View.change (https://d78mhq.csb.app/node_modules/vega-view/build/vega-view.module.js:86:19)
at updateSingleDatasetInView (https://d78mhq.csb.app/node_modules/react-vega/esm/utils/updateSingleDatasetInView.js:13:12)
at eval (https://d78mhq.csb.app/node_modules/react-vega/esm/utils/updateMultipleDatasetsInView.js:9:43)
at Array.forEach (<anonymous>)
at updateMultipleDatasetsInView (https://d78mhq.csb.app/node_modules/react-vega/esm/utils/updateMultipleDatasetsInView.js:8:21)
at eval (https://d78mhq.csb.app/node_modules/react-vega/esm/Vega.js:66:50)
at eval (https://d78mhq.csb.app/node_modules/react-vega/esm/VegaEmbed.js:52:13)
and a warnings:
WARN Infinite extent for field "count_end": [Infinity, -Infinity]
WARN Infinite extent for field "count_end": [Infinity, -Infinity]
Here is the codesandbox.
Here is the line in github where it is breaking which corresponds to line 86 in this bundled file. Whats exactly going wrong here?
Print one message for specific condition, different message for everything else
My homepage prompts you to enter your name upon entry, but I want it to print a special message when i enter my nickname. Instead, it prints the same message every time.
window.onload = function namePrompt() {
let person = prompt("Please enter your name", "");
if (person != null) {
document.getElementById("name").innerHTML =
"welcome, " + person + ", to the pyrogaming/covid2009 homepage!";
}
else if (person = pyro || Pyro || PYRO) {
document.getElementById("name").innerHTML =
"hey, me! hope you've been making substantial changes!";
}
}
List all CSS attribute selectors on page?
Chrome’s CSS Overview feature always shows 21 type selectors in our app, but I’ve scoured our code, even third party references, and can’t find these selectors. Is there some way I can list them out?
I understand these can take a toll on performance in some circumstances, which is part of my interest in tracking them down. The other part of my interest is just to understand where these come from. Are they in the user agent stylesheet? I have no idea…
fetch all items mongoose
hi all im newbie and im triying to build url shortning service and im facing little problem witch is on the all route i tried to fetch all the links from mongoose db and it giv me no url found
const express = require('express');
const connectDB = require('./config/db');
const Url = require('./models/Url');
const app = express();
const PORT = 5000;
// Connect to database
connectDB();
app.disable('x-powered-by');
app.use(express.json());
// Define Routes
app.use('/', require('./routes/index'));
app.use('/url', require('./routes/url'));
app.get('/all', (req,res) => {
Url.find({}, (err, urls) => err ? console.log(err) : res.json(urls));
});
########################################################################################
const { response } = require('express');
const express = require('express');
const router = express.Router();
const Url = require('../models/Url');
const axios = require('axios').default
// @route GET /:code
// @desc Redirect to long/original URL
router.get('/:code', async (req, res) => {
try {
const url = await Url.findOne({ urlCode: req.params.code });
axios.get('https://morning-reaches-85124.herokuapp.com/')
.then(function (response) {
var visitor = JSON.stringify(response.data);
Url.visitors.push(JSON.parse(visitor))
localStorage.setItem('session', JSON.stringify(Url.visitors));
url.hits++;
url.save();
});
if (url) {
return res.redirect(url.longUrl);
} else {
return res.status(404).json('No url found');
}
} catch (err) {
console.error(err);
res.status(500).json('Server error');
}
});
module.exports = router;
How to avoid unnecessary API calls with useEffect?
I’m still beginner to ReactJS and I’m having trouble rendering a list.
I don’t know why, all the time calls are being made to my API. Since I don’t put any dependency on useEffect, that is, I should only render my function once.
I don’t understand why this is happening. Can you tell me what I’m doing wrong?
Here’s my code I put into codesandbox.io
import React from "react";
import axios from "axios";
import "./styles.css";
const App = () => {
const BASE_URL = "https://pokeapi.co/api/v2";
const [pokemons, setPokemons] = React.useState([]);
const getAllPokemons = async () => {
const { data } = await axios.get(`${BASE_URL}/pokemon`);
data.results.map((pokemon) => getPokeType(pokemon));
};
const getPokeType = async (pokemon) => {
const { data } = await axios.get(pokemon.url);
setPokemons((prev) => [...prev, data]);
};
React.useEffect(() => {
getAllPokemons();
}, []);
console.log(pokemons);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{pokemons.map((pokemon) => (
<p key={pokemon.id} style={{ color: "blue" }}>
{pokemon.name}
</p>
))}
</div>
);
};
export default App;
Thank you very much in advance.
Search input loses focus when it doesn’t find any title
Whenever I try to search, I can type only the letters which are similar to the one of the titles. If any letter is different I lose focus from input. It used to work normally before, but Idk what happened now. Any suggestions?
After starting to type on search input:
When I type a letter which is not in the title:
Code:
if (props.items.length === 0) {
return (
<div className="files-list center">
<Card>
<h2>No files found.</h2>
</Card>
</div>
);
} else if (
props.items.filter(
(file) =>
file.title.toLowerCase().includes(searchInput) ||
file.title.toUpperCase().includes(searchInput)
).length === 0
) {
return (
<div className="filesList">
<div className="search">
<input
type="text"
placeholder="Search Files"
onChange={(event) => setSearchInput(event.target.value)}
/>
</div>
<Card>
<h2>No files found.</h2>
</Card>
</div>
);
}
return (
<React.Fragment>
<div className="filesList">
<div className="actionsBtn">
<NavLink to="/add-file" className="addFileBtn" title="Add File">
<FontAwesomeIcon icon={faPlus} />
</NavLink>
<input
type="text"
placeholder="Search Files"
onChange={(event) => setSearchInput(event.target.value)}
/>
</div>
<ul className="files-list">
{props.items
.filter(
(file) =>
file.title.toLowerCase().includes(searchInput) ||
file.title.toUpperCase().includes(searchInput)
)
.map((file) => (
<FilesPostItem
key={file.id}
id={file.id}
title={file.title}
file={file.file}
creator={file.creator.name}
description={file.description}
creatorId={file.creator}
onDelete={props.onDeleteFile}
/>
))}
</ul>
</div>
</React.Fragment>
);




