typeof foo
will just evaluate to 'object'
whether foo is a list []
or a dictionary {}
or any kind of object. How can one tell the difference?
Category: javascript
Category Added in a WPeMatico Campaign
Custom React Hook Causing Memory Leak Error
I had created a custom hook to fetch data for a single item but for some reason its causing this error
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at PostPage (http://localhost:3000/static/js/bundle.js:2530:81)
at Routes (http://localhost:3000/static/js/bundle.js:48697:5)
at div
at Router (http://localhost:3000/static/js/bundle.js:48630:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:48110:5)
Here is the code
const useFetchMultiSingle = (mainUrl, secondaryKey, mainUrlPath, secondaryUrlPath, path) => {
const [mainUrlDataSingle, setMainUrlDataSingle] = useState(null);
const [secondaryUrlDataSingle, setSecondaryUrlDataSingle] = useState(null);
const [loadingMultiUrlSingle, setLoadingMultiUrlSingle] = useState(false);
const [errorMultiUrlSingle, setErrorMultiUrlSingle] = useState(null);
useEffect(() => {
const apiOnePromise = axios.get(`${mainUrl}/${mainUrlPath}?secondary_id=${path}`);
const apiTwoPromise = axios.get(`http://localhost:5555/${secondaryUrlPath}?id=${path}`);
setLoadingMultiUrlSingle(true);
Promise.all([apiOnePromise, apiTwoPromise])
.then(values => {
const response01 = values[0].data;
const response02 = values[1].data;
setMainUrlDataSingle(response01);
setSecondaryUrlDataSingle(response02);
})
.catch((err) => {
setErrorMultiUrlSingle(err);
})
.finally(() => {
setLoadingMultiUrlSingle(false);
})
}, [mainUrl, secondaryKey, mainUrlPath, secondaryUrlPath, path]);
const refetch = () => {
const apiOnePromise = axios.get(`${mainUrl}/${mainUrlPath}?secondary_id=${path}`);
const apiTwoPromise = axios.get(`http://localhost:5555/${secondaryUrlPath}?id=${path}`);
setLoadingMultiUrlSingle(true);
Promise.all([apiOnePromise, apiTwoPromise])
.then(values => {
const response01 = values[0].data;
const response02 = values[1].data;
setMainUrlDataSingle(response01);
setSecondaryUrlDataSingle(response02);
})
.catch((err) => {
setErrorMultiUrlSingle(err);
})
.finally(() => {
setLoadingMultiUrlSingle(false);
})
};
return { mainUrlDataSingle, secondaryUrlDataSingle, loadingMultiUrlSingle, errorMultiUrlSingle, refetch };
};
This hook fetches the data from the main url and then fetches the data from the second url based on the first api response data
Autofill by Selector not working on all Pages
Normally, i Login to formbased login pages by executing the following:
cefsharp_browser.ExecuteScriptAsyncWhenPageLoaded("document.querySelector('#input-email').value='[email protected]';");
cefsharp_browser.ExecuteScriptAsyncWhenPageLoaded("document.querySelector('#input-password').value='mysupersecretpassword';");
But now i´m actually struggeling to login to a Page(https://lagerimgriff.app/login) on which the code above doesn´t work.
The Form is beeing filled with the Values shown above but injecting the Values that way or by ID, the Login-Form doesn´t realize any input, saying the field beeing empty.
I´m not a WebDev but it seems to me that there is some intermediate JS which is checking the Fields for validity(f.e. the mail must contain @ followed by a . ), maybe that is the Problem?
As this seems to be JS related i´ll tag it too.
Is there any way of archieving an automated login on that Page?
How do I resize my Leaflet map when the viewport/ bootrap navbar changes?
I’m using Leaflet and a bootstrap navbar and I’d like to be able to resize the Leaflet map div when the viewport size changes.
My html is: (I have left out the sidebar and modal html as I don’t think it’s relevant)
<!DOCTYPE html>
<html lang="en">
<head>
<title>MyApp</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--Bootstrap CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!--This link is required by L.easyButton-->
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<!--Leaftlet CSS-->
<link rel="stylesheet" href="./css/leaflet.css">
<link rel="stylesheet" href="./css/easy-button.css">
<link rel="stylesheet" href="./css/L.Control.Sidebar.css">
<link rel="stylesheet" href="./css/MarkerCluster.css">
<link rel="stylesheet" href="./css/MarkerCluster.Default.css">
<!--Font Awesome CSS-->
<link rel="stylesheet" href="../fontAwesome/css/all.min.css">
<!--Document CSS-->
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- Main navbar -->
<nav class="navbar-inverse">
<div class="container-fluid">
<div class="row">
<div class="col-lg-4 text-center">
<ul id="currentLocation" class="list-inline navbar-text navbar-left">
<li></li>
<li><p class="text-success"</p></li>
<li><button id="resetLocation" type="button" class="btn btn-primary active">Locate</button></li>
</ul>
</div>
<div class="col-lg-4 text-center text-primary text-uppercase">
<h2 id="appNameTitle">My App</h2>
</div>
<div class="col-lg-4 text-center">
<ul class="list-inline navbar-text navbar-right">
<li></li>
<li><select></select></li>
</ul>
</div>
</div>
</div>
</nav>
<!-- Leaflet Map div -->
<div id="map"></div>
<div id="preloader"></div>
<script src="./js/jquery3.6.0.js"></script>
<!--Preloader-->
<script type="application/javascript" src="./js/preloader.js"></script>
<!--Preloader-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="application/javascript" src="./js/leaflet.js"></script>
<script type="application/javascript" src="../fontAwesome/js/all.min.js"></script>
<script type="application/javascript" src="./js/easy-button.js"></script>
<script type="application/javascript" src="./js/L.Control.Sidebar.js"></script>
<script type="application/javascript" src="./js/leaflet.markercluster.js"></script>
<script type="application/javascript" src="./js/money.js"></script>
<script type="application/javascript" src="./js/script.js"></script>
<!--
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin="" defer></script>
-->
</body>
</html>
I’ve set map div height to 89vh for now as I can still view the map and the nav bar at full width but it’s only temporary as it doesn’t maintain it’s ‘fit to screen’ behaviour that I want.
CSS:
#map {
width: 100%;
height: 89vh;
}
When the browser window’s width is reduced the navbar will begin to stack and the map div will overflow down and have the lower part of the map clip.
I’d like to have the map’s div element resize it self automatically so that it always takes up the remaining available space after the nav bar resizes/ browser viewport changes. The nav bar doesn’t seem to be taken into account when I resize the browser window and I guess that it’s taking up the other 11% of vh.
I’ve tried putting the map div into another container-fluid and setting it’s size to auto and 100% but whatever I try it seems to require a fixed height in px or vh for the map div, which is not what I want.
Please help.
webpack-pug js function is not a function
Im new to webpack and pug . Working on a small task and
- I wrote a function dropDown() in drop.js exported it in index.js file,
- tried to put it in PUG file
but: - console writing wether ‘function is not defined’ or f’unction is not a function’.
- Please could anyone help me to solve that problem with correct defining js function
here is the link to my webpack.config
enter link description here
here is my json file
enter link description here
in PUG file i use function like this:
.searchbox-drop
button(href="#" data-dropdown='drop1' onclick='dropDown()' aria-controls='drop1' aria-expanded=false class='dropbtn') Вce
+image('triangle','searchbox-drop__icon' )
in index.js
import $ from "jquery";
import 'bootstrap';
import './styles/index.scss';
import {dropDown} from './drop.js';
window.dropDown = dropDown();
in drop.js
export function dropDown(){
function show() {
document.getElementById('myDropdown').classList.toggle('show');
}
//close dropdown id the user cliks outside of it
window.onclick = function(e){
if(!e.target.matches('.dropbtn')){
var myDropdown = document.getElementById('myDropdown');
if(myDropdown.classList.contains('show')){
myDropdown.classList.remove('show');
}
}
}
}
NestJS loosing request with Passport JWT strategy
In order to implement multitenancy in my NestJS app, I create the database connection in a request-scoped provider (depending on request subdomain). Authentication handled by Passport is working fine when using local strategy. However when using JWT strategy later on, the request in my connection provider is undefined:
ERROR [ExceptionsHandler] Cannot read property 'headers' of undefined
TypeError: Cannot read property 'headers' of undefined
at InstanceWrapper.useFactory [as metatype] (/Users/peterbienek/dev/nestjs/multitenant-typeorm/src/tenancy/tenancy.module.ts:14:29)
at Injector.instantiateClass (/Users/peterbienek/dev/nestjs/multitenant-typeorm/node_modules/@nestjs/core/injector/injector.js:304:55)
at callback (/Users/peterbienek/dev/nestjs/multitenant-typeorm/node_modules/@nestjs/core/injector/injector.js:48:41)
at processTicksAndRejections (node:internal/process/task_queues:94:5)
This is my connection provider:
import { Module, Scope, Global, BadRequestException } from '@nestjs/common';
import { getConnectionManager, createConnection } from 'typeorm';
import * as tenantOrmConfig from './tenant-ormconfig'
import { REQUEST } from '@nestjs/core';
const connectionFactory = {
provide: 'CONNECTION',
scope: Scope.REQUEST,
useFactory: async (req) => {
let subdomain = req.headers.host.split('.')[0]
const connectionName = subdomain
if (subdomain.indexOf('localhost') != -1 || subdomain.indexOf('127.0.0.1') != -1) {
throw new BadRequestException('Tenant code not valid')
}
const connectionManager = getConnectionManager()
const connectionPublic = connectionManager.get('default')
if (connectionManager.has(connectionName)) {
const connection = await connectionManager.get(connectionName)
return Promise.resolve(connection.isConnected ? connection : connection.connect())
}else{
console.log("CREATING CONNECTION ", connectionName)
connectionPublic.query(`CREATE SCHEMA IF NOT EXISTS ${connectionName}`)
await createConnection({
...tenantOrmConfig,
name: connectionName,
type: 'mysql',
database: connectionName,
})
const connection = await connectionManager.get(connectionName)
return Promise.resolve(connection.isConnected ? connection : connection.connect())
}
},
inject: [REQUEST]
}
@Global()
@Module({
providers: [connectionFactory],
exports: ['CONNECTION']
})
export class TenancyModule { }
JWT strategy looks like this:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from '../auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { ModuleRef, ContextIdFactory } from '@nestjs/core';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { SETTINGS } from 'src/app.config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private moduleRef: ModuleRef) {
super({
passReqToCallback: true,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: SETTINGS.JWT_SECRET,
});
}
async validate(
payload: any, request: Request
): Promise<any> {
const contextId = ContextIdFactory.getByRequest(request);
const authService = await this.moduleRef.resolve(AuthService, contextId);
const user = await authService.validateUserByJwt(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
Local strategy (almost identical):
import { ModuleRef, ContextIdFactory } from '@nestjs/core';
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, 'local') {
constructor(private moduleRef: ModuleRef) {
super({passReqToCallback: true, usernameField: 'email'});
}
async validate(
request: Request,
email: string,
password: string
): Promise<any> {
const contextId = ContextIdFactory.getByRequest(request);
const authService = await this.moduleRef.resolve(AuthService, contextId);
const user = await authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
Auth service using the connection:
import { Scope, Injectable, Inject, NotFoundException, UnauthorizedException, BadRequestException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { JwtPayloadService } from "./jwt.payload.service";
import { JwtPayload } from "./interfaces/jwt-payload.interface";
import { User } from "src/common/users/entities/user.entity";
import { UsersService } from "src/common/users/users.service";
import { Repository } from "typeorm";
import * as bcrypt from "bcrypt";
export class AuthService {
userRepository: Repository<User>;
constructor(
@Inject("CONNECTION") connection,
private jwtService: JwtService,
private jwtPayloadService: JwtPayloadService,
private usersService: UsersService
) {
this.userRepository = connection.getRepository(User);
}
async validateUser(email: string, pass: string): Promise<any> {
const user = await this.usersService.validate(email);
const isPasswordMatching = await bcrypt.compare(pass, user.password);
if (user && isPasswordMatching) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
async validateUserByJwt(payload: JwtPayload) {
console.log("payload", payload);
const user = await this.usersService.findOneByEmail(payload.email);
if (user) {
return this.jwtPayloadService.createJwtPayload(user);
} else {
throw new UnauthorizedException();
}
}
}
How can the local strategy work and the JWT strategy not?
How to make event listener in javascript generator function?
I need to change a part of github library code. Below function is for searching bluetooth devices. The problem is, this function will return devices when all task is finished. As you know, if you do searching bluetooth, connectable devices appear one by one, not at once.
startDiscovery() {
return __awaiter(this, void 0, void 0, function* () {
let discoveredDevices = yield this._nativeModule.startDiscovery();
for (let discovered of discoveredDevices) {
devices.push(new BluetoothDevice(discovered, this));
}
return devices;
});
}
Current Behavior
const devices = await startDiscovery()
setDevices(devices) // update 10 devices at once - annoying.
What I wish
startDiscovery((newDevice) => {
if(newDevice) setDevices([...devices, newDevice])
// it would update devices one by one, smoothly.
})
Is it possible to change startDiscovery
function?
Javascript three.js shadow map with noise why?
Upload a Blob as a regular file
I have a server running Laravel, hosting an endpoint expecting a file
parameter, upon which it validates the rules required
and image
.
In Javascript, I use Axios to send a HTTP request containing a blob of type image/png
. Code example:
const data = new FormData();
data.append('file', blob);
axios.post(submitUrl, data).then(r => console.log(r));
I can’t seem to get that request to pass Laravel’s validation, reporting that the file-upload has failed and responding with 422 Unprocessable Entity
.
How do I get Axios to send a blob, just as a regular form would upload an image?
Things (all of them at once, and invidually) I tried so far:
- Wrapping the blob in a
File
object, specifying it’slastModified
parameter and filename; - Adjusting the
Content-Type
header to reflect the Blob MIME type; - Sending it as
base64
instead of blob; - Just using
fetch()
and making the request body contain the image.
So far all my attempts are unsuccessful. Thanks in advance.
how can get the first div data with regex
I am trying to get the first div data through regex replace but i don’t know how can i do that because first time i am doing this. I am trying to get the data from mail
JS
previousValueDisplay() {
return this.previousValue
.replace()
}
<div dir="ltr">First div </div>
first div
i want to get the whole text from the first div like this
<div dir="ltr">First div <div>is use </div><div>for test</div></div>
First div is use for test
Adding new input fields on check box ticked
I have a table with 3 text fields
i want to add the same text fields on clicking check box i have the following code
how can i do it with php and javascript
echo "<td>Screen ".$i."</td>";
echo "<td><input type='text' id='filmname".$k."' name='filmname".$k."'value='".$prefilm."'></td>";
echo "<td><input type='text' id='Language".$k."' name='Language".$k."'value='".$prelang."'></td>";
echo "<td><input type='text' id='showtime".$k."' name='showtime".$k."'value='".$prescreen."'></td>";
echo "<td ><input type='checkbox' class='Checkbox' id='addshow".$k."' autocomplete='off'
name='addshow".$k."' value='addshow' onclick='addshow(".$k.")</td>";
How to use access token from google calendar in js
I have question regarding google calendar, and hope you can help me.
I have access_token from google calendar and that access_token
was stored in localStorage
.
const googleAccessToken = e.vc.access_token;
localStorage.setItem('googleAccessToken', googleAccessToken);
Now please help me understand how can I use this to avoid authorization every time.
For example I want to delete all events, And for that I wrote this code, and this code every time wants from me authorization:
const handleDisconnect = () => {
gapi.load('client:auth2', () => {
console.log('loaded client');
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES_CLEAR,
});
gapi.client.load('calendar', 'v3', () => {
console.log('sdsd');
});
gapi.auth2
.getAuthInstance()
.signIn()
.then(() => {
var events = bb;
var makeRequest = resource => {
console.log(resource);
var request = gapi.client.calendar.calendars.clear({
calendarId: 'primary',
});
request.execute(resp => {
console.log(resp);
});
};
for (var j = 0; j < events.length; j++) {
makeRequest(events[j]);
}
});
});
};
Please help me to fixed that code with access_token
for avoiding authorization
Why we use keyword in: and not transition: ? [Svelte Transition]
Can someone explain me why custom transition functions using keyword in:
and not transition:
like each native svelte transition ?
spyOn not working for calling the function multiple times
I am using NgbModal in my components and i am trying to write test case for that component.
My component function where i have opened modal look like this:
cancelLicense(activeMiningLicensesName: string, subscriptionId: string) {
const dialogueComponent: any = this.modalService.open(DialogueComponent, {
size: "md" as "lg",
centered: true,
backdrop: "static",
keyboard: false,
});
console.log(dialogueComponent, "===========================>");
dialogueComponent.componentInstance.message = `Are you sure you want to cancel your weekly subscription for ${activeMiningLicensesName}?`;
dialogueComponent.componentInstance.confirmText = "Yes";
dialogueComponent.componentInstance.cancelText = "No";
dialogueComponent.result.then((isConfirmClicked) => {
if (isConfirmClicked) {
this.confirmCancelLicense(activeMiningLicensesName, subscriptionId);
}
});
}
confirmCancelLicense(activeMiningLicensesName: string, subscriptionId: string) {
const dialogueComponent: any = this.modalService.open(DialogueComponent, {
size: "md" as "lg",
centered: true,
backdrop: "static",
keyboard: false,
});
console.log("----------------------->3", dialogueComponent);
dialogueComponent.componentInstance.message = `Please note that once you cancel, you can not get a refund unless the request for a refund falls within thirty (30) days of purchase. Also, refund only applies to the Yearly subscriptions; for more details, refer to the Terms and Conditions. Cancel anyway?`;
dialogueComponent.componentInstance.confirmText = "Yes";
dialogueComponent.componentInstance.cancelText = "No";
dialogueComponent.result.then((isConfirmClicked) => {
console.log("----------------------->2");
if (isConfirmClicked) {
this.subscriptionCancellation(activeMiningLicensesName, subscriptionId);
}
});
}
Here modelService is an injector to NgbModal service.
Now coming to test case, I have mocked modelService like below:
modalService = TestBed.inject(NgbModal);
component = fixture.componentInstance;
const ngBmodalref: Partial < NgbModalRef > = {
componentInstance: {},
result: new Promise((resolve, reject) => {
resolve({
status: true
});
}),
};
modelOpenSpy = spyOn(modalService, "open").and.returnValue(ngBmodalref as NgbModalRef);
Everything works fine when the model.open function is called in test case for the first time but when it is called second time rather than returning spied value it returns a NgBModalRefrence(see attached image)
If anyone can help me figure out why this is happening!
Note: I also tried spyOn().and.returnValues() and passing two different value, then also it is working the same way.