I wanted to generate some random or more like “fake” data like complete name for my web app, i’ve seen faker.js but it seemed there’s a little bit of drama from the maintainer. checked multiple options but they seem little bit complicated for my needs. Thanks.
Category: javascript
Category Added in a WPeMatico Campaign
JavaScript Button input and output reset
I’m working with a button and a text label in javascript and HTML. I have a code that clears the input text label, but i also need the same button to clear the output message it gives = “helloNameOP”. How would I add the 2 in the same function? I have both my codes listed below, that work perfectly separated, but I cant figure out how to put them together to work simultaneously.
What I have tried:
//for removing the Input text label:
onclick = document.getElementById("helloNameInput").value="";
//for removing the Output message recieved:
inputField = document.getElementById("helloNameOP")
document.getElementById('helloNameOP').textContent = " "
I’m not a javascript person, more of a kotlin gal, so I’m trying to learn.
SyntaxError: Unexpected token ‘;’ while compiling ejs while trying to make data to a table html
<body>
<h1>Hello, world!</h1>
<table class="table">
<thead>
<tr>
<th scope="col">Command</th>
<th scope="col">Total</th>
<th scope="col">Success</th>
<th scope="col">Last</th>
</tr>
</thead>
<tbody>
<%Object.entries(global.db.data.stats).map(([name, data]) => ({%>
<tr>
<th scope="row"><%= name =%></th>
<td><%= data.last =%></td>
<td><%= data.total =%></td>
<td><%= data.success =%></td>
</tr>
<%})%>
</tbody>
</table>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
i am very new to ejs and still learning, i am trying to make global.db.data.stats to become a table
Why is Net.Socket.Write() not sending the full string to my TCP client?
Everything else works fine. The server is well aware of the usernames associated with the clients and it sends information to them accordingly, but the weird thing is the string cuts off after the first variable. Here is the loop for a typical send message:
function SendMessage(msg, client)
{
const clientName = ClientNames.get(client);
let recieverMsg = `${clientName}: ${msg}`;
console.log(recieverMsg);
Clients.forEach(elm => {
if(elm != client)
{
elm.write(recieverMsg);
}
else {
elm.write("You: " + msg);
}
})
}
msg is the chunk.toString() in the socket.on(‘data’) event, again, node picks up what this string means, it debugs fine but in the client (imagine the windows cmd) itll just print the username and go to the next line.
The loop for the client side is pretty simple too,
char buff[4090];
do
{
ZeroMemory(buff, 4090);
int messageRevieved = recv(sock, buff, 4090, 0);
if (messageRevieved > 0)
{
userInput->FreezeInput();
cout << buff << endl;
userInput->UnFreezeInput();
}
} while (0 == 0);
User input is handled in its own class on a seperate thread, again, working just fine.
I think it has to do with a misunderstanding of what socket.write and recv actually do or maybe I just dont understand javascript strings enough. Either way this problem is annoying because its the last step in creating my app
Ive done some extensive tests too, it really just doesnt like the concat strings. Itll print everything up until the first variable, meaning I could have socket.write(“hehehehehehe ” + variable1 + ” kadjgkdgad”); and it would print hehehehehe [variable1 value] and just stop
Tl;dr: The server will write to the sockets up to the first variable in a concat’d string and then stop, its so weird.
EDIT: The dependencies used serverside are Net and dotnet if that makes a difference.
Dynamically displaying data results from left to right in table columns from json array
I wanted to achieve similar result as shown in below image.
Question: Looking for Jquery or javascript solution to dynamically displaying data results from left to right in table columns from json array.
Your help is much appreciated.
Here is my HTML & JSON format and what I am trying to achieve:
<table>
<tr>
<td rowspan='2'>ID</td>
<td rowspan='2'>Bagian</td>
<td colspan='12'>Tahun</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
<tbody id="zone_data">
</tbody>
const data =
{ result:
[ { TPM_MESIN_ID: 'CPU-20220115112327418526-20220122140952287412'
, KOMPONEN:
[ { TPM_MESIN_KOMPONEN_ID : '20220115112327418531-20220122140952462116'
, TPM_MESIN_KOMPONEN_NAMA : 'CPU01'
, BERKALA:
[ { TPM_BERKALA_ID: '20220127142100262686', TPM_BERKALA_JADWAL_MINGGU: 'M-1', TPM_BERKALA_JADWAL_BULAN: '1', TPM_BERKALA_PERIODE: '1' }
, { TPM_BERKALA_ID: '20220127154027581689', TPM_BERKALA_JADWAL_MINGGU: 'M-13', TPM_BERKALA_JADWAL_BULAN: '6', TPM_BERKALA_PERIODE: '2' }
, { TPM_BERKALA_ID: '20220129084334483646', TPM_BERKALA_JADWAL_MINGGU: 'M-28', TPM_BERKALA_JADWAL_BULAN: '9', TPM_BERKALA_PERIODE: '3' }
] }
, { TPM_MESIN_KOMPONEN_ID : '20220115112327418532-20220122140952272413'
, TPM_MESIN_KOMPONEN_NAMA : 'MNT01'
, BERKALA:
[ { TPM_BERKALA_ID: '20220127142100262698', TPM_BERKALA_JADWAL_MINGGU: 'M-2', TPM_BERKALA_JADWAL_BULAN: '1', TPM_BERKALA_PERIODE: '1' }
, { TPM_BERKALA_ID: '20220127142100262699', TPM_BERKALA_JADWAL_MINGGU: 'M-12', TPM_BERKALA_JADWAL_BULAN: '5', TPM_BERKALA_PERIODE: '2' }
, { TPM_BERKALA_ID: '20220127142100262700', TPM_BERKALA_JADWAL_MINGGU: 'M-31', TPM_BERKALA_JADWAL_BULAN: '10', TPM_BERKALA_PERIODE: '3' }
] }
, { TPM_MESIN_KOMPONEN_ID : '20220115112327418533-20220122140952428562'
, TPM_MESIN_KOMPONEN_NAMA : 'KYB01'
, BERKALA: []
} ] }
, { TPM_MESIN_ID: 'CPU-20220115112327418526-20220122140952287555'
, KOMPONEN:
[ { TPM_MESIN_KOMPONEN_ID : '20220115112327418531-20220122140952462117'
, TPM_MESIN_KOMPONEN_NAMA : 'CPU02'
, BERKALA:
[ { TPM_BERKALA_ID: '20220127142100262686', TPM_BERKALA_JADWAL_MINGGU: 'M-5', TPM_BERKALA_JADWAL_BULAN: '2', TPM_BERKALA_PERIODE: '1' } ]
} ] } ] }
function createRowHTML()
{
var tableContent = "";
for (var j = 0; j < data.result.length; j++)
{
}
$("tbody#zone_data").html(tableContent);
}
$(function(){createRowHTML();});
How can i stop the iteration of a Generator?
My following function is a Generator function* generator(arr) {
now i want to pass from js to ruby, i want to stop the iteration to do that in js i stopped with .done
, in ruby how can i stop?
in javascript i used to use .done to stop the iteration of an Generator
like this:
function* generator(arr) {
}
function definition(){
const state = data.map(v => iterHeapsAlgo(v));
while(true) {
const isEnd = state.every((v,i) => {
let n = v.next();
if(n.done) {
now i am becomming my code from js to ruby
how can i stop the iteration if(n.done) {
in ruby?
React not re-rendering after state update
I’m currently learning React. In my homepage component, I’m using a hook to initialize and populate the state. I have 2 states, 1 contains a random pokemon and another is an array of 20 random pokemons. The first one works fine, but not the array.
Here’s the homepage component:
// Hook
import { useHomeFetch } from "../hooks/useHomeFetch";
// Image
import NoImage from '../images/missingno.png';
const Home = () => {
const { state, collection, loading, error } = useHomeFetch();
return (
<>
{ state.heroPokemon ?
<HeroImage
image={`${API.fetchSprite(state.heroPokemon)}`}
title={state.heroPokemon.name}
text='Placeholder, should include abilities, etc. to show the pokemon off.'
/>
: null}
{ collection.pokemons[0] ?
<Grid header='Popular pokemons'>
{collection.pokemons.map( pokemon => (
<h3 key={pokemon.id}>{pokemon.name}</h3>
) )}
</Grid>
: null}
</>
);
}
export default Home;
The heroPokemon works fine after I added the conditional rendering. My first thought was to do the same thing with the collection, as it might have rendered before all of the API call promises have resolved.
If I look at the react dev tools, this is what I see for the state:
hooks
HomeFetch
1 State : {heroPokemon: {…}}
2 State : {pokemons: Array(20)}
pokemons :
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
So it looks to me that the call indeed completed fine with 20 random pokemon objects in there.
Here’s is the hook:
const initialState = {
heroPokemon: null
}
const fetchRandomPokemons = async (ids) => {
let pokemons = [];
ids.forEach(async num => {
pokemons.push(await API.fetchPokemon(num));
});
return pokemons;
}
export const useHomeFetch = () => {
const [state, setState] = useState(initialState);
const [collection, setCollection] = useState({pokemons: []});
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const fetchPokemons = async (limit = 20) => {
try {
setError(false);
setLoading(true);
const heroPokemon = await API.fetchPokemon(randomInt(1, 898));
const randomInts = randomUniqueInt(1, 898, limit);
const pokemons = await fetchRandomPokemons(randomInts);
setState(prev => ({heroPokemon}));
setCollection(prev => ({pokemons}));
} catch (error) {
setError(true);
}
setLoading(false);
};
// Initial render
useEffect(() => {
fetchPokemons(20);
}, [])
return { state, collection, loading, error };
};
When I take out the conditional, Grid
shows up, but it doesn’t have the h3s with the pokemon names in them. If I console.log out state
and collection
right before the return in home
. The last few ones show the correct state.heroPokemon
and collection.pokemons
populated correctly. This leads me to believe that the states are updated correctly, but why is React not re-rendering the grid component?
To add, I also tried adding this:
<p>{collection.pokemons[0]}</p>
To the home component, and nothing shows up. I feel like I may be misunderstanding or missing a crucial part of how states and re-renders work, which is leading me to missing what I could be doing wrong.
CSS Animation Issue – Button Animation
I have the following code:
var basicTimeline = anime.timeline({
autoplay: false,
});
var pathEls = $(".check");
for (var i = 0; i < pathEls.length; i++) {
var pathEl = pathEls[i];
var offset = anime.setDashoffset(pathEl);
pathEl.setAttribute("stroke-dashoffset", offset);
}
basicTimeline
.add({
targets: ".text",
duration: 1,
opacity: "0"
})
.add({
targets: ".button",
duration: 1300,
height: 20,
width: 81,
backgroundColor: "#717F7E",
border: "0",
zIndex: 0,
borderRadius: 100
})
.add({
targets: ".progress-bar",
duration: 2000,
width: 81,
easing: "linear"
})
.add({
targets: ".button",
width: 0,
duration: 1
})
.add({
targets: ".progress-bar",
width: 40,
height: 39,
delay: 500,
duration: 750,
borderRadius: 80,
backgroundColor: "#71DFBE",
left: 20
})
.add({
targets: pathEl,
strokeDashoffset: [offset, 0],
duration: 200,
easing: "easeInOutSine"
});
$(".button").click(playButtonAnim);
$(".text").click(playButtonAnim);
function playButtonAnim() {
basicTimeline.play();
}
//error animation
const form = document.forms.myform;
form.onsubmit = e => {
e.preventDefault()
let data = Object.fromEntries(new FormData(form).entries())
console.log(data)
let validationOK = true
for (let entrie in data) {
if (!form[entrie].checkValidity()) {
validationOK = false
form[entrie].classList.add('shakingErr')
setTimeout(() => {
form[entrie].classList.remove('shakingErr')
}, 820)
}
}
if (validationOK) {
fetch(form.action, {
method: form.method,
body: JSON.stringify(data),
headers: {
Accept: 'application/json'
}
})
.finally(() => {
window.location = "thankyou.html"
})
}
}
/* Contact Form */
input[type=text],
[type=email],
select,
textarea {
width: 100%;
padding: 12px;
border: 1px solid #555;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type="text"]:focus,
input[type="email"]:focus,
#subject:focus {
background: var(--bgFormElsFocus);
transform: scale(1.02);
transition: transform 0.2s ease-in-out;
}
.contactform {
position: relative;
border-radius: 50px;
background-color: #f2f2f2;
padding: 5px;
z-index: 2;
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: auto;
margin-top: 1%;
width: 100%;
animation-name: gradient;
animation-duration: 3s;
animation-iteration-count: infinite;
}
.contactform:hover {
animation-name: gradient;
animation-duration: 15s;
animation-iteration-count: infinite;
}
.column {
float: center;
width: 50%;
margin-top: 6px;
padding: 20px;
display: block;
margin-left: auto;
margin-right: auto;
}
.row:after {
content: "";
display: table;
clear: both;
}
@media screen and (max-width: 600px) {
.column,
input[type=submit] {
width: auto;
margin-top: 0;
}
}
.shakingErr {
border-color: red;
animation: shake 0.82s forwards;
}
@keyframes shake {
10%,
90% {
transform: translate3d(-1px, 0, 0);
}
20%,
80% {
transform: translate3d(2px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-4px, 0, 0);
}
40%,
60% {
transform: translate3d(4px, 0, 0);
}
}
/* fancy button styles */
.buttonWrapper {
height: 39px;
width: 81px;
position: relative;
}
.button {
background: #2B2D2F;
height: 39px;
width: 81px;
text-align: center;
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 0;
cursor: pointer;
border-radius: 4px;
z-index: 10;
}
.text {
font: .8rem/1 poppins;
color: #71DFBE;
position: absolute;
top: 50%;
transform: translateY(-52%);
left: 0;
right: 0;
cursor: pointer;
}
.progress-bar {
position: absolute;
height: 20px;
width: 0;
left: 40px;
top: 50%;
border-radius: 200px;
transform: translateY(-50%) translateX(-50%);
background: black;
}
svg {
width: 15px;
position: absolute;
top: 50%;
left: 20px;
transform: translateY(-50%) translateX(-8px);
}
.check {
fill: none;
stroke: #FFFFFF;
stroke-width: 3;
stroke-linecap: round;
stroke-linejoin: round;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Poppins:600" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Poppins:600" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.js">
</script>
</head>
<body>
<!-- start contact section -->
<section id="contact">
<div class="container" data-aos="fade-up">
<div class="contactform">
<div style="text-align:center">
<div class="section-title">
<h2><br />Get In Touch</h2>
</div>
<p>Feel Free To Reach Out To Me Through This Form! </p>
</div>
<div class="row">
<div class="column">
<form name="myform" action="https://formspree.io/f/xrg123232jbqpq" id="my-form" method="POST" novalidate>
<label for="firstname">First Name</label>
<input type="text" id="first name" name="firstname" placeholder="Your First Name.." required>
<label for="lastname">Last Name</label>
<input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Your Email.." required>
<label for="subject">Subject</label>
<textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
<!-- <input type="submit" value="Submit"> -->
<div class='buttonWrapper'>
<div class="button">
<div class="text">Submit</div>
</div>
<div class="progress-bar"></div>
<svg x="0px" y="0px" viewBox="0 0 25 30" style="enable-background:new 0 0 25 30;">
<path class="check" class="st0" d="M2,19.2C5.9,23.6,9.4,28,9.4,28L23,2" />
</svg>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<script src="script.js"></script>
</body>
</html>
The only problem I’m facing is that even though I have error animation code in the JS that calls in the shakingErr
class from CSS, the animation seems to be not working when the user clicks submit with empty/wrong fields. How can I make it so that when the user clicks the submit button, the contact form has a shaking error button.
Notice that when you click the submit button, there is also an animation that plays on the button? I would not like that animation to play when the user clicks submit button on empty fields. I would only like the animation to play once the user has filled all the information in the input fields.
Any suggestions?
EXPECTED OUTPUT
https://watch.screencastify.com/v/D2VXp3493XZXl3Lmh7yR
As you can see, whenever the user tries to click submit button on empty/wrong fields (Email) then the error animation plays. Also, the button animation should not play when the user clicks the submit button on empty/wrong fields. It should play once the fields are filled and are right.
Any suggestions?
Tried to split string using regex. I cannot extract the parentheses
I wanted my myResult = [ ’40’, ‘-‘, ‘(‘, ’60’, ‘*’, ‘2’, ‘)’ ]
let myInput = '40-(60*2)';
let myResult = myInput.split(/([*/+-])/);
console.log(myResult)
Changing a HTML element at a certain time and date
I have an open and closed indicator (Thanks to those who helped me!) that shows I am open from 8:00 AM to 10:00 PM and from 10:00 PM to 8:00 AM I am closed, but it shows this even on a weekend when I am not open. Can you help me make the Javascript say I am closed when it is a weekend and on a holiday like December 24-25? Below will be my current code. Thanks!
Javascript:
var messageElement = document.getElementById("message");
var circleElement = document.getElementById("circle");
const refreshStatus = () => {
// Set the current time
let currentDate = new Date().getHours();
// If the time is between 8 am and 10 pm
if (currentDate >= 8 && currentDate <= 21) {
// Update text and add classes
messageElement.innerHTML = "We are open until 10 PM";
circleElement.className = 'open-circle';
messageElement.className = 'open-p';
} else {
// 21 pm to 8 am
messageElement.innerHTML = "We are closed until 8 AM";
circleElement.className = 'closed-circle';
messageElement.className = 'closed-p';
}
}
// run when starting
refreshStatus();
// updates every 8 seconds
setInterval(refreshStatus, 8000);
CSS:
/* Start indicator CSS */
.open-circle {
position: relative;
top: 23rem;
height: 1.5625rem;
width: 1.5625rem;
background-color: #00BF13;
border-radius: 50%;
display: inline-block;
}
.open-p {
position: relative;
top: 23rem;
color: #00BF13;
font-weight: bold;
display: inline-block;
width: 8rem;
}
.closed-circle {
position: relative;
top: 23rem;
height: 1.5625rem;
width: 1.5625rem;
background-color: #ea001d;
border-radius: 50%;
display: inline-block;
}
.closed-p {
position: relative;
top: 23rem;
color: #ea001d;
font-weight: bold;
display: inline-block;
width: 8rem;
}
/* End indicator CSS */
HTML:
<!-- Start status indicator -->
<div id="circle"></div>
<p id="message">We are open until 10 PM</p>
<script src="js/open-closed-indicator.js"></script>
<!-- End status indicator -->
Unable to display data in Selectize JS from remote source via R Shiny
Problem
I’m trying to query a aws cloudsearch endpoint from R Shiny using selectize input, but I am having no luck. Cloudsearch returns additional information that is not necessary for selectize, below is the full object returning 3 rows worth of results. I’m trying to return fields in my selectize drop down.
Data (json object)
{
"status": {
"rid": "4YG+neovoAIK1BX3",
"time-ms": 2
},
"hits": {
"found": 3,
"start": 0,
"hit": [
{
"id": "equities.csv_3",
"fields": {
"function": "table",
"name": "PFIZER INC",
"type": "equity",
"dataset": "clinicals",
"ticker": "PFE"
}
},
{
"id": "equities.csv_5",
"fields": {
"function": "table",
"name": "AMGEN INC",
"type": "equity",
"dataset": "clinicals",
"ticker": "AMGN"
}
},
{
"id": "equities.csv_6",
"fields": {
"function": "table",
"name": "GILEAD SCIENCES INC",
"type": "equity",
"dataset": "clinicals",
"ticker": "GILD"
}
}
]
}
}
What I Don’t Get
I can confirm that the issue is not coming from my cloudsearch endpoint, the below shiny app returns all of the specified data in the console. My expectation was that I could remove console.log(res.hits.hit[i].fields)
within the below for loop of my success function and replace it with callback(res.hits.hit[i].fields)
to get my results. That did not work, so I then tried removing my for loop and just returning callback(res.hits.hit[0].fields)
with the expectation I’d at least return the first element, but that did not work either.
Shiny App (code blocks above reference changes in the success function of Ajax call)
library(shiny)
ui <- basicPage(
tagList(
selectizeInput('github', 'Select a Github repo', choices = '', options = list(
valueField = 'ticker',
labelField = 'ticker',
searchField = 'ticker',
options = list(),
create = FALSE,
render = I("{
option: function(item, escape) {
return '<div>' + escape(item.ticker) + '</div>';
}
}"),
load = I("function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'cloud-search-endpoint' + encodeURIComponent(query),
type: 'GET',
dataType: 'json',
error: function() {
callback();
},
success: function(res) {
console.log(res);
console.log(res.hits.hit[0].fields);
for (var i in res.hits.hit) {
console.log(res.hits.hit[i].fields)
}
}
});
}")
)),
h3("Parsed query string")
)
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
Creating a div and inserting HTML
I’m trying to create this in Javascript so that I can insert it into the document:
<div class="listing-small-badge award-badge" style=" vertical-align: top; position: relative; top: -250px; z-index: 2;"><i class="fa fa-tag award" style="background-color: #990000;"></i>Highest Rated</div>
And I’ve tried everything I can think of, but once I create the ‘i’ element, I can’t seem to properly append it to the div element.
For example:
<script type="text/javascript">
var div = document.createElement("div");
div.style.cssText += 'vertical-align:top; position: relative; top:-250px; z-index:2;';
div.classList.add("listing-small-badge");
div.classList.add("award-badge");
div.innerHTML = "Highest Rated"; //this works on its own, but disappears if/when I try to append the 'i' element/HTML tag
var i = document.createElement("i");
i.classList.add("fa");
i.classList.add("fa-tag");
i.classList.add("award");
//i.style.cssText("background-color: #990000;"); //doesn't like this for some reason TBD
//console.log(i); //prints out just fine
//div.innerHTML += i; //results in an empty div
//div.innerHTML += '<i class="test">x</i>'; //results in an empty div
//div.insertAdjacentHTML("afterend", "<i class='test'></i>"); //results in "The element has no parent."
console.log(div);
</script>
data undefined in React Hook Form inside a NPM input fields
I´m using a npm of inputs plus react hooks but when i submit the data i get undefined values in my console. I tried using the default input tags and works fine, the data i send shows perfectly. Any suggestions? is it possible to work with this NPM and react hook form or should i use the default data (Something that i don´t really like to do)
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import Nav from "./Navbar";
import Footer from "./Footer";
import { FormField } from 'react-form-input-fields';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useForm } from "react-hook-form";
import { faEye,faEyeSlash } from '@fortawesome/free-solid-svg-icons';
import 'react-form-input-fields/dist/index.css';
function Login() {
const {register, handleSubmit } = useForm();
const eye = <FontAwesomeIcon icon={faEye} />
const closeEye = <FontAwesomeIcon icon={faEyeSlash} />
const [passwordShown, setPasswordShown] = useState(false);
let [email, setEmail] = useState("");
let [password, setPassword] = useState("");
const togglePasswordVisiblity = () => {
setPasswordShown(passwordShown ? false : true);
};
const onSubmit = (data) => {
console.log(data)
}
return (
<div className="page-container">
<div className="content-wrap">
<Nav />
<div className="div-login-form">
<h1 className="title">Login</h1>
<form className="login-form" onSubmit={handleSubmit(onSubmit)}>
<FormField
type="email"
standard="labeleffect"
value={email}
keys={'email'}
name="email"
effect={'effect_1'}
handleOnChange={(value) => setEmail(value)}
{...register("email")}
placeholder={'Enter Email'} />
<div className="input-password">
<div className="icon-eye">
<i onClick={togglePasswordVisiblity} className="icon"> {passwordShown ? eye : closeEye} </i>
</div>
<FormField
type={passwordShown ? "text" : "password"}
standard="labeleffect"
value={password}
keys={'password'}
name="password"
effect={'effect_1'}
handleOnChange={(value) => setPassword(value)}
{...register("password")}
placeholder={'Enter Password'} />
</div>
<button className="button-shop" type="submit">
Log in
</button>
</form>
</div>
</div>
<Footer />
</div>
);
}
export default Login;
Uncaught Error: Actions must be plain objects. Use custom middleware
The error seems common and when I made some research I saw that it’s mostly due to omission of middlewere (like thunk) or failing to call the dispatch function. Even after trying to put those things in check I keep getting the error
function RegisterScreen({ signup, isAuthenticated }) {
const [accountCreated, setAccountCreated] = useState(false);
const [username, setUsername] = useState([])
const [email, setEmail] = useState([])
const [password, setPassword] = useState([])
const [re_password, setRe_password] = useState([])
const [message, setMessage] = useState('')
const dispatch = useDispatch()
const auth = useSelector(state => state.auth)
const { error, loading } = auth
const submitHandler = (e) => {
e.preventDefault();
if (password !== re_password) {
setMessage('Both passwords must be the same')
} else {
dispatch(signup(username, email, password, re_password));
setAccountCreated(true);
}
}
return (
<Container className='content auth-container'>
<div className="auth-header text-center mb-4">
<h2 className="auth-header">Sign Up</h2>
<p>Add your deatils to sign up</p>
</div>
{message && <Message variant='danger'>{message}</Message>}
{error && <Message variant='danger'>{error}</Message>}
{loading && <Loader />}
<Form className="auth-form" onSubmit={submitHandler}>
<Form.Group className="mb-3" controlId='name'>
<Form.Control
className="auth-input search-ppty"
required
minLength='6'
type="name"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</Form.Group>
<Form.Group className="mb-3" controlId='email'>
<Form.Control
required
className="auth-input search-ppty"
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="password">
<Form.Control
className="auth-input search-ppty"
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="passwordConfirm">
<Form.Control
className="auth-input search-ppty"
type="password"
placeholder="Confirm Password"
value={re_password}
onChange={(e) => setRe_password(e.target.value)}
/>
</Form.Group>
<Button type="submit" className="auth-button">Sign Up</Button>
</Form>
<Row className="p-2">
<Col>
<div className=""> Already have an account? <Link to="/login">Login</Link></div>
</Col>
<Col>
</Col>
</Row>
</Container>
)
}
export default connect(null, {signup}) (RegisterScreen)
Redux store
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
const middleware = [thunk]
const store = createStore(
reducer,
composeWithDevTools(applyMiddleware(...middleware))
)
export default store
I have spent several hours still can’t find where the error is coming from in the code. How do I fix it?
panzoom set specific bounds to not show space in container
Currently using timmywils panzoom library: https://github.com/timmywil/panzoom
Im currently trying to build a “map” where you can pan around and click on specific elements. Im currently having some issues with this though.
When panning I dont want to show space thats outside of the bounds if that makes sense.
In the image below, I would imagine the “div.adventure-map” to have a background image.
This would okay to show because the container element behind it is completely covered.
However, this image would NOT be okay because the container element behind it isnt covered completely and would just be black.
I feel like im approaching this problem incorrectly but am having a bit of a brain fart.
Im starting to think maybe just implementing my own drag/pan solution would be better. Would appreciate some guidance/help!