I’m trying to implement a login page for my app.
When the login button is clicked, a fetch is called and tries to login with the user’s info.
If the login succeeds, login button’s value updates to be the homepage, else it changes back to the login page address.
Any idea on how to make it work?
I tried <Link to={redirect?"/home":"/"}>
but it didn’t do anything, and I also tried using a state prop which holds the link value but still had problems with it.
Category: javascript
Category Added in a WPeMatico Campaign
Get URL Params before server Next js render
I am trying to get the params in a url redirected from the Spotify api, ex: http//link.com/?code=examplecode
How can I get the value of code before it renders so I can redirect it and pass the code value to another page?
Detect data changes and update redux persist?
I know we can use redux-persist for saving our redux store in localstorage.
Let’s say I have a API data which I want to save in redux-persist.
But problem is that let’s say this data can be changed any time.
For example; I have a users list and I don’t want to get this users list on every page refresh so I decide to save them in redux-persist. But what will be happen if the new user added to db and I want to see this user also in my users list. How can I do this ? Is that even possible ? It’s look like silly question I know because if I want to detect new users I have to make a call anyway 😀 I just want to know is there anyway for that ?
Angular: How to bind an array model attribute to a copy able div element
First of all I apologize for the bad title, I wasn’t sure exactly how to describe it.
I have this div for the user to enter contact information pertaining to a “program” for which the user also entered data. Right now you can only enter 1 set of contact information in this div:
<div id="programContactContainer" class="container">
<div id="programContact">
<div class="form-group mt-2">
<label>Name</label>
<input type="text" class="form-control" id="contactName"
required
[(ngModel)]="model.contact.name" name="contactName">
</div>
<div class="form-group mt-2">
<label>Email</label>
<input type="text" class="form-control" id="contactEmail"
required
[(ngModel)]="model.contact.email" name="contactEmail">
</div>
<div class="form-group mt-2">
<label>Phone</label>
<input type="text" class="form-control" id="contactPhone"
required
[(ngModel)]="model.contact.phone" name="contactPhone">
</div>
<br>
<hr/>
</div>
</div>
<input class="btn btn-primary" type="button" value="Add another contact" (click)="cloneContactDiv()">
If you click that button it adds an identical div below the existing one so the user can enter multiple contacts.
Code for copying div:
cloneContactDiv(){
const myDiv = document.getElementById(('programContact'));
const divClone = myDiv.cloneNode(true);
document.getElementById('programContactContainer').append(divClone);
}
This is the model for both the program and the contact info (I know that not all of this is used in the question but I thought it might help):
export class ContactModel {
name: string;
email: string;
phone: string;
}
export class ProgramModel {
category: string;
name: string;
description: string;
shortDescription: string;
support: string [];
address: string;
location: [];
areaServed: string;
baseLocation: string;
website: string;
topic: string [];
ownerLid: string;
keywords: string[] = [];
startDate: Date;
endDate: Date;
notification: boolean;
daysForNotice: number;
filter: string [];
active: boolean;
/// Contacts
contact = new ContactModel();
/// Departments
departmentContact = new ContactModel();
}
If I change contact = new ContactModel();
to contact: ContactModel[] = [];
then I can save an array of them, but I have no idea how to handle this in the html page. As you can see, the contact info was bound like this: [(ngModel)]="model.contact.name"
, but how do I handle that when there is more than 1 and an unknown number of how many?
how to delete a specified object from an array in discordjs [duplicate]
const afkUsers = [];
client.on("messageCreate", function(message) {
if (message.author.bot) return;
afkUsers.map(x => {
if(x == message.author.id) return message.reply('I removed your AFK status.')
});
});
And now I want to delete the message author’s ID from the array
Access Array Values in Typescript
Display data of chart.js from data in html jquery
I using SignalR by Js to update my data from the database and put my data to Chart.js . But maybe my syntax goes wrong. Could you help me to edit my code? Thank you very much.
My signalR function code :
<script type="text/javascript">
$(function () {
//Proxy created on the fly
var cus = $.connection.cusHub;
//Declare a function on the job hub so the server can invoke
cus.client.displayValue = function () {
getData();
};
//Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblValue');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
//'<tr>' +
//'<td>' + model.DeviceID + '</td>' +
//'<td>' + model.Value + '</td>' +
//'</tr>'
model.Value
);
});
}
});
}
</script>
I display data in HTML by ID “tblValue” and my browser is “1000” :
<h2 id="tblValue"> </h2>
And I get data with getElementByID from id “tblValue” into data of Chart.js but it is null and there is nothing in my chart :
<script>
var ctx = document.getElementById("percent-chart2");
var my_val = document.getElementById('tblValue').innerHTML;
var vals = parseFloat(my_val);
if (ctx) {
ctx.height = 209;
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [
{
label: "My First dataset",
data: [vals , vals, vals ],
backgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
hoverBackgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
borderWidth: [
0, 0, 0
],
hoverBorderColor: [
'transparent',
'transparent',
'transparent'
]
}
],
labels: [
'STATION 1',
'STATION 2',
'STATION 3'
]
},
options: {
maintainAspectRatio: false,
responsive: true,
cutoutPercentage: 87,
animation: {
animateScale: true,
animateRotate: true
},
legend: {
display: false,
position: 'bottom',
labels: {
fontSize: 14,
fontFamily: "Poppins,sans-serif"
}
},
tooltips: {
titleFontFamily: "Poppins",
xPadding: 15,
yPadding: 10,
caretPadding: 0,
bodyFontSize: 16,
}
}
});
}
</script>
I haven’t learned about web building but my thesis relates to it. So I really need your support. Please help me.
Display three rows of duplicated data in one row using Javascript Filter()
You can see two data tables in the attached photo.
The first data table shows the same data in all three rows. I don’t need the duplicated datas, so I want to remove the duplicated row of datas and make only one row of data. Please tell me what to do. Everyone Please help me.
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
<template>
<v-container class="container-padding">
<v-breadcrumbs class="px-0 pt-0" large>
<span class="breadcrumb-line rounded-pill mr-2"></span>
<v-breadcrumbs-item class="text-h5 mr-5">Timecard</v-breadcrumbs-item>
<span class="breadcrumb-divider rounded-pill mr-5"></span>
<v-breadcrumbs-item class="text-h6">View</v-breadcrumbs-item>
</v-breadcrumbs>
<v-card>
<v-container fluid>
<v-row>
<v-col cols="1">
<v-subheader></v-subheader>
</v-col>
<v-col cols="2">
<v-layout row wrap justify-space-around>
<v-text-field v-model="calendarVal" label="Date" type="date" value="2022-02-05"></v-text-field>
</v-layout>
</v-col>
<v-col cols="1">
<v-btn @click="fetchWorkerTimeCard">enter</v-btn>
</v-col>
</v-row>
</v-container>
<v-data-table v-if="worker_time_card.length > 0" :headers="headers1" :items="worker_time_card"></v-data-table>
</v-card>
<v-card>
<v-data-table v-if="worker_time_card.length > 0" :headers="headers2" :items="worker_time_card"></v-data-table>
</v-card>
</v-container>
</template>
<script>
export default {
data() {
return {
worker_time_card: [],
calendarVal: null,
headers1: [{
text: 'Start Time',
value: 'start_time'
},
{
text: 'End time',
value: 'end_time'
},
{
text: 'Rest time',
value: 'rest_time'
},
{
text: 'Worked time',
value: 'worked_time'
},
],
headers2: [{
text: 'Project id',
value: 'project_id'
},
{
text: 'Duration',
value: 'duration'
},
{
text: 'Work log',
value: 'work_log'
}
],
}
},
computed: {
calendarDisp() {
return this.calendarVal
},
},
mounted() {
this.calendarVal = this.getDataToday()
this.fetchWorkerTimeCard()
},
methods: {
getDataToday() {
return (new Date().toISOString().substr(0, 10))
},
submit() {
console.log(this.calendarVal)
},
async fetchWorkerTimeCard() {
try {
this.worker_time_card = []
await this.$axios.$get('/worker_time_card', {
params: {
work_date: this.calendarVal
}
}).then(data => {
data.time_cards.forEach(card =>
this.worker_time_card.push({
start_time: data.start_time,
end_time: data.end_time,
rest_time: data.rest_time,
worked_time: data.worked_time,
duration: card.duration,
work_log: card.work_log,
project_id: card.project_id,
})
)
})
} catch (error) {
console.log(error)
this.worker_time_card = []
}
},
},
}
</script>
This project uses the vuetify framework, and the code below is part of the “v-data-table” component. Perhaps if this part is fixed well, it will be possible to make a data table with only one row, but it may be necessary to fix the Javascript part as well.
Javascript how to filter an array using forEach() inside filter()
How to use Next Auth for OTP login?
I’m new to Next Js. Please help me to solve this. I’ve been trying to authenticate my OTP using Next Auth. But I don’t know how to pass the values from component to […nextauth].js
Used signIn property in a function that gets called when I give a right OTP.
function signInHandler() {
signIn();
router.push('/')
}
My UI where I have the input box and Login Button
const detail = {
title: (
<div style={{ width: "100%" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
}}
>
<h3 onClick={callApi}>OTP Verification</h3>
<div onClick={() => setOtpModal(false)}>X</div>
</div>
<div style={{ width: "100%" }}>
<SmallText style={"text"}>OTP</SmallText>
</div>
</div>
),
body: (
<div style={{ textAlign: "left", width: "100%" }}>
<div style={{ marginTop: "10px", textAlign: "left", display: "flex" }}>
<div>
<SmallText style={styles.stylesheet.text}>
{validity && " Did not receive OTP ?"}
{!validity && (
<div style={{ display: "flex" }}>
<div style={{ display: "flex" }}>
<Warning /> <div style={{"margin":"0px 0px 0px 10px"}} >OTP seems to be invalid</div>
</div>
</div>
)}
</SmallText>
</div>
<div>
<SmallText style={"glow"}>Resend OTP</SmallText>
</div>
</div>
Called the SignInHandler function here to login using “signIn()” in this Button.
<button style={styles.stylesheet.btnStyle} onClick={signInHandler}>
Login !
</button>
My current […nextauth].js
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import axios from "axios"
import { API_URL } from "./../../../helpers/api/mutations"
import OtpVerification from './../../../components/Components/SignIn/OtpVerification';
This is the place I got stuck. I’m trying to give my API call here with “SignIn” from OTP Verification Component. I want to replace the Email credential to OTP based. Is it possible ?
export default NextAuth({
providers:[
Providers.Email({
// Need the credentials. In my case the OTP to get passed here.
},
}),
],
secret: process.env.SECRET,
session: {
jwt: true,
},
Login API call hits when I use signIn(). I first tried with async authorize but it was failed in my case.
callbacks: {
jwt: async ({ token, users }) => {
const user = await axios({
url: API_URL,
method: "post",
data: {
query: `mutation{
login(
mobileNumber: "1111111146",
mobileCountryCode: "00",
password: "admin123"
) {
expiresAt
accessToken
}
}`,
},
}).then((result) => {
console.log(result.data.data,'result')
return result.data
})
token = user.data.login.accessToken
return user
},
session: ({ session, token }) => {
if (token) {
session = token
}
return session
},
},
theme: {
colorScheme: "dark",
brandColor: "",
logo: "/logo.png",
},
debug: process.env.NODE_ENV === "development"
})
React hooks issue when create a drag and drop component
I create a drag and drop component using React hook, with the callback function when drag enters below. If I use the line dragItem.current.itemIndex, 1
instead of currentItemIndex, 1
it is not working. Can somebody tell me why? Thanks!!!
Call back here:
const handleDragEnter = function handleDragEnter(e, targetItem) {
if (dragItemNode.current !== e.target) {
const currentItemIndex = dragItem.current.itemIndex
setOrder((oldOrder) => {
let newOrder = JSON.parse(JSON.stringify(oldOrder));
newOrder.splice(
targetItem.itemIndex,
0,
newOrder.splice(
//currentItemIndex, 1 // working
dragItem.current.itemIndex, 1 // not working
)[0]
);
dragItem.current.itemIndex = targetItem.itemIndex
return newOrder;
});
}
};
Full code here:
function DragNDrop({
items,
order,
setOrder,
}) {
const [dragging, setDragging] = useState(false);
const dragItem = useRef();
const dragItemNode = useRef();
const handleDragStart = function handleDragStart(e, item) {
dragItemNode.current = e.target;
dragItemNode.current.addEventListener("dragend", handleDragEnd);
dragItem.current = item;
setTimeout(() => {
setDragging(true);
}, 0);
};
const handleDragEnter = function handleDragEnter(e, targetItem) {
if (dragItemNode.current !== e.target) {
const currentItemIndex = dragItem.current.itemIndex
setOrder((oldOrder) => {
let newOrder = JSON.parse(JSON.stringify(oldOrder));
newOrder.splice(
targetItem.itemIndex,
0,
newOrder.splice(
//currentItemIndex, 1 // working
dragItem.current.itemIndex, 1 // not working
)[0]
);
dragItem.current.itemIndex = targetItem.itemIndex
return newOrder;
});
}
};
const handleDragEnd = function handleDragEnd(e) {
dragItem.current = null;
dragItemNode.current.removeEventListener("dragend", handleDragEnd);
dragItemNode.current = null;
setDragging(false);
};
const getStyles = (item) => {
if (dragItem.current.item == item.item) {
return "dnd-item current";
}
return "dnd-item";
};
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
width: "100%",
}}
className="drag-n-drop"
>
{order.map((item, itemIndex) => (
<div
draggable
key={item}
onDragStart={(e) => handleDragStart(e, {item, itemIndex})}
onDragEnter={
dragging
? (e) => {
handleDragEnter(e, {item, itemIndex});
}
: null
}
className={dragging ? getStyles({item, itemIndex}) : "dnd-item"}
>
{items[item]}
</div>
))}
</div>
);
}
What is the difference between plug-ins Quokka.js and Wallaby.js?
They seem to have similar functions.They are from the same company. Their introduction websites are also very similar. Which is better to buy?
Why does Intellij Code Inspection tell me a selector is never used?
I have this mini-project. It is composed of 2 files in the same folder.
- App.css
.App-align-left {
text-align: left;
}
- App.js
import React from 'react';
import 'App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: ''
}
}
render() {
let contents = <h4>Contents</h4>;
return (
<div style={{ display: "inline-block" }}><br />
<h3 style={{ display: "inline-block" }}>Header</h3>
<div className="App-align-left">{contents}</div><br />
</div>)
}
}
export default App;
When I run code inspection on this, it gives me a warning for App being unused (unused global export
), but also for Selector App-align-left is never used
. Why is this? It is clearly used.
when pressing submit PHP Error requested URL was not found
I have just installed XAMPP on my machine yesterday, and I working on some examples when pressing submit button I get the following error. (I got this only with this file)
`Not Found
The requested URL was not found on this server.
Apache/2.4.52 (Win64) OpenSSL/1.1.1m PHP/8.1.2 Server at localhost Port 80`
How to fix the black screen with canvas.toDataURL() on Safari browser?
I have a video player (video.js) in my application, and a function which takes a snapshot of the video.
The function create a canvas which draws the snapshot and convert the canvas into a DataURL.
But this doesn’t work in Safari.
I’m getting a black screen on Safari.
the video tag looks like:
<video crossorigin="anonymous" playsinline="playsinline" id="player_2140_html5_api" class="vjs-tech" data-setup="{ "inactivityTimeout": 0 }" tabindex="-1" autoplay="autoplay" loop="loop"></video>
This is the function which creates the snapshot:
var canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 480;
var ctx = canvas.getContext('2d');
var video = document.querySelector('video');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
this.snapshotVideo = canvas.toDataURL('image/jpeg', 2.0);
The generated dataUrl in Chrome is an image.
The generated dataUrl in Safari browser is a black rectangle.
In Safari the output is black instead of an image of the taken snapshot via the video, how can I solve this?
Trying to retrieve unique data through a json file
I’m looking for help I’m trying to get some data of json file from an api that I’m using for student project ( I’m very beginner on API stuff).
I’m at the beginning of the project and they asked me to get all of the json file data on the homepage with all informations associated with :
Those are the data that I extract for the API
It’s works fine and when the user click on one of the item it’s show the same information but only the for the one clicked and this is where I’m stuck.
When I click on an item each of them have an id related to a link showing their own id :
The small code use through a loop to get all items id
So I create another js file for the product page where I have to implement them only with Javascript Vanilla and this is what I’ve tried :
// API REQUEST
const connection = fetch ('http://localhost:3000/api/products')
/* *********CONNECION*********** */
connection.then((response) => {
if(response.ok){
return response.json();
}
else{
console.log('Connection failed');
}
})
/* ********END DE CONNEXION*********** */
.then((jsonArray) => {
function JsDemo(myData){
// TARGETING ON HTML SELECTORS
const imgOfTheActualProduct = document.querySelector(".item__img > img");
const titleOfTheActualProduct = document.querySelector(".item__content__titlePrice > #title");
const priceOfTheActualProduct = document.querySelector(" .item__content__titlePrice #price");
const colorOfTheActualProduct = document.querySelector("#colors");
const descriptionOfTheActualProduct = document.querySelector('.item__content__description #description');
// Loop to get json elements
for(let i = 0 ; i < myData.length; i++){
imgOfTheActualProduct.src=`${myData[i].imageUrl}`;
titleOfTheActualProduct.innerHTML=`${myData[i].name}`;
priceOfTheActualProduct.innerHTML=`${myData[i].price}`;
descriptionOfTheActualProduct.innerHTML=`${myData[i].description}`
// colorOfTheActualProduct.innerHTML=`${myData[i].colors}`;
}
}
JsDemo(jsonArray);
})
The code above work(only with the api not here 🙂 ) but it’s showing only the last data of the json file and I retrieve the same thing when I’m selecting all of the item on homepage…
Just to get an idea of what I’m talking about for the JSON part :
[
{
"colors": ["Blue", "White", "Black"],
"_id": "107fb5b75607497b96722bda5b504926",
"name": "Kanap Sinopé",
"price": 1849,
"imageUrl": "http://localhost:3000/images/kanap01.jpeg",
"description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"altTxt": "Photo d'un canapé bleu, deux places"
},
{
"colors": ["Black/Yellow", "Black/Red"],
"_id": "415b7cacb65d43b2b5c1ff70f3393ad1",
"name": "Kanap Cyllène",
"price": 4499,
"imageUrl": "http://localhost:3000/images/kanap02.jpeg",
"description": "Morbi nec erat aliquam, sagittis urna non, laoreet justo. Etiam sit amet interdum diam, at accumsan lectus.",
"altTxt": "Photo d'un canapé jaune et noir, quattre places"
},
{
"colors": ["Green", "Red", "Orange"],
"_id": "055743915a544fde83cfdfc904935ee7",
"name": "Kanap Calycé",
"price": 3199,
"imageUrl": "http://localhost:3000/images/kanap03.jpeg",
"description": "Pellentesque fermentum arcu venenatis ex sagittis accumsan. Vivamus lacinia fermentum tortor.Mauris imperdiet tellus ante.",
"altTxt": "Photo d'un canapé d'angle, vert, trois places"
},
{
"colors": ["Pink", "White"],
"_id": "a557292fe5814ea2b15c6ef4bd73ed83",
"name": "Kanap Autonoé",
"price": 1499,
"imageUrl": "http://localhost:3000/images/kanap04.jpeg",
"description": "Donec mattis nisl tortor, nec blandit sapien fermentum at. Proin hendrerit efficitur fringilla. Lorem ipsum dolor sit amet.",
"altTxt": "Photo d'un canapé rose, une à deux place"
},
{
"colors": ["Grey", "Purple", "Blue"],
"_id": "8906dfda133f4c20a9d0e34f18adcf06",
"name": "Kanap Eurydomé",
"price": 2249,
"imageUrl": "http://localhost:3000/images/kanap05.jpeg",
"description": "Ut laoreet vulputate neque in commodo. Suspendisse maximus quis erat in sagittis. Donec hendrerit purus at congue aliquam.",
"altTxt": "Photo d'un canapé gris, trois places"
},
{
"colors": ["Grey", "Navy"],
"_id": "77711f0e466b4ddf953f677d30b0efc9",
"name": "Kanap Hélicé",
"price": 999,
"imageUrl": "http://localhost:3000/images/kanap06.jpeg",
"description": "Curabitur vel augue sit amet arcu aliquet interdum. Integer vel quam mi. Morbi nec vehicula mi, sit amet vestibulum.",
"altTxt": "Photo d'un canapé gris, deux places"
},
{
"colors": ["Red", "Silver"],
"_id": "034707184e8e4eefb46400b5a3774b5f",
"name": "Kanap Thyoné",
"price": 1999,
"imageUrl": "http://localhost:3000/images/kanap07.jpeg",
"description": "EMauris imperdiet tellus ante, sit amet pretium turpis molestie eu. Vestibulum et egestas eros. Vestibulum non lacus orci.",
"altTxt": "Photo d'un canapé rouge, deux places"
},
{
"colors": ["Pink", "Brown", "Yellow", "White"],
"_id": "a6ec5b49bd164d7fbe10f37b6363f9fb",
"name": "Kanap orthosie",
"price": 3999,
"imageUrl": "http://localhost:3000/images/kanap08.jpeg",
"description": "Mauris molestie laoreet finibus. Aenean scelerisque convallis lacus at dapibus. Morbi imperdiet enim metus rhoncus.",
"altTxt": "Photo d'un canapé rose, trois places"
}
]
To be honest I don’t know what to I’m not looking for the solution just an hint.
I looked for URL search parameters on mdn but I don’t really understand on what it’s could be useful here because I already know that each Id is correctly linked ( Or maybe I’m wrong ?!)
Sorry its little long.
Thanks for reading !