Do these components use refs as state? When we update the component ref, do we update the DOM directly? When we update the component’s ref, does the component render and show the value or the change on the screen? If I create an internal state (useState) in the component, but do not update that state, is the component still controlled?
Category: javascript
Category Added in a WPeMatico Campaign
Canot find error who gives me “Can’t bind to ‘FormGroup’ since it isn’t a known property of ‘form’.” in Angular 17
Im having this error and i cannot find where it is im following a tutorial on youtube i tried searching on google ad i get alot of examples and i tried all from adding the FormsModule with CommonModule and ReactiveFormsModule, and also tried importing it in the component ut all to no avail.
here is the component code:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrl: './create-post.component.css',
})
export class CreatePostComponent implements OnInit {
enteredTitle = '';
enteredContent = '';
forms: FormGroup | any;
private mode = 'create';
private postId: any;
public post: Post | any;
constructor(
public postService: PostServiceService,
public route: ActivatedRoute
) {}
ngOnInit() {
this.forms = new FormGroup({
title: new FormControl(null, {
validators: [Validators.required, Validators.minLength(3)],
}),
content: new FormControl(null, {
validators: [Validators.required],
}),
});
this.route.paramMap.subscribe((paramMap: ParamMap) => {
if (paramMap.has('postId')) {
this.mode = 'edit';
this.postId = paramMap.get('postId');
this.postService.getPosts(this.postId).subscribe((postData) => {
this.post = {
id: postData._id,
title: postData.title,
content: postData.content,
};
this.forms.setValue({
title: this.post.title,
content: this.post.content,
});
});
} else {
this.mode = 'create';
this.postId = null;
}
});
}
onAddPost() {
if (this.forms.invalid) {
return;
}
if (this.mode === 'create') {
this.postService.addPost(
this.forms.value.id,
this.forms.value.title,
this.forms.value.content
);
} else {
this.postService.updatePost(
this.postId,
this.forms.value.title,
this.forms.value.content
);
}
this.forms.reset();
}
}
here is the html form:
<mat-card>
<form [FormGroup]="forms" (submit)="onAddPost()">
<mat-form-field style="margin-top: 20px">
<mat-label>Titulo</mat-label>
<input matInput formControlName="title" />
<mat-error *ngIf="forms.get('title').invalid"
>Porfabor yena un titulo di minimo 20 karakter</mat-error
>
</mat-form-field>
<mat-form-field style="background-color: rgb(230, 227, 227)">
<mat-label>Contenido</mat-label>
<textarea matInput rows="10" formControlName="content"></textarea><br />
<mat-error *ngIf="forms.get('content').invalid"
>Porfabor yena bo contenido</mat-error
>
</mat-form-field>
<button
mat-flat-button
color="primary"
style="border-radius: 25px; width: 250px; margin: 20px 0 20px 3px"
type="submit"
>
Post
</button>
</form>
</mat-card>
Getting undefined when assigning string to enum in typescript
We are trying to assign a text to an enum variable but getting undefined
enum Color {
Green = "GRN",
Red = "RD"
}
let text: string = "GRN";
let test: Color = Color[text as keyof typeof Color];
console.log(test);
This returns to undefined
Any help would be appreciated.
Javascript does not execute code right after an awaited call immediately (it does other stuff in between) after the async function returned
I’ll begin by showing what should be the expected output, both from a sensible view point and because it’s what happens if the functions weren’t async.
about to resolve
about to return from foo
code right after awaited return from foo
about to return from bar
code right after awaited return from bar
But between returning from a function and executing the next line of code in the caller, Javascript is interleaving other code, resulting in the following:
about to resolve
about to return from foo
about to return from bar
code right after awaited return from foo
code right after awaited return from bar
I wonder if there’s a way to prevent it. I need the next line of code in the caller to be executed right after the async function returns.
That’s the output of the following code:
async function caller(cb) {
await cb();
console.log(`code right after awaited return from ${ cb.name }`);
}
const { promise, resolve } = Promise.withResolvers();
async function foo() {
await promise;
console.log('about to return from foo');
}
async function bar() {
await promise;
console.log('about to return from bar');
}
caller(foo);
caller(bar);
console.log('about to resolve');
resolve();
How to use Javascript async/await in semi-asynchronous situations? (e.g. in String.replace)
For example I’m doing a RegExp replacement on a body of text:
text = text.replace(re, function (match, comment, op1, op2, op3, op4, op5, op6, op7) {
if (op1 !== undefined) {
log("processing @@");
parseEnum(config, op1, args1);
} else if (op2 !== undefined) {
log("processing {{}}");
parseConfig(config, interpolateConfig(config, op2));
return "";
} else if (op3 !== undefined && !configOnly) {
log("processing [[]]");
return await parseMacro(config, op3, asyncInstances); // <---------- HERE
} else if (op4 !== undefined) {
log("processing <<>>");
await parseInclude(config, interpolateConfig(config, op4)); // <---- HERE
return "";
} else if (op5 !== undefined && !configOnly) {
log("processing ~~~~");
// TODO parseStyle(op5);
} else if (op6 !== undefined) {
log("processing $$");
return interpolateConfig(config, op6);
} else if (op7 !== undefined) {
log("processing ^^");
}
});
And I need these replacements to occur synchronously, i.e. each call to the replacement function must complete before the next match and replacement. However, depending on the match, sometimes I have to call an async function. So to keep things synchronous, I decided to use await. But to do that, I also had to change the anonymous function to async:
text = text.replace(re, async function (match, comment, op1, op2, op3, op4, op5, op6, op7) {
++++++
Unfortunately however, String.replace doesn’t accept an async function. I found in this answer a utility for doing just that, copied verbatim from that post by @ChrisMorgan:
async function replaceAsync(string, regexp, replacerFunction) {
const replacements = await Promise.all(
Array.from(string.matchAll(regexp),
match => replacerFunction(...match)));
let i = 0;
return string.replace(regexp, () => replacements[i++]);
}
Using this like this (omitting code that hasn’t changed)—
text = await replaceAsync(
text,
re,
async function (match, op1, args1, op2, op3, op4, op5, op6, op7) {
...
}
);
—it actually seemed to work. I thought that the replacements would still occur synchronously—well maybe the better word here is sequentially—because underneath the hood we’re still calling String.replace one at a time. But later I began seeing strange results and realized I was mistaken. The replacement function was being called in parallel, and “future” replacements started processing whenever the current replacement gave up control (e.g. to fetch a file, etc. which is the reason some functions are async).
The only way I can see around this right now is to avoid async/await altogether and use Promise.resolve() instead. But I was trying to use async/await everywhere to keep a consistent style. Is there another way to do this using async/await that I’m not seeing?
Update: Hm, I cannot figure out how to solve this using Promise.resolve() either. I thought that that would essentially act like await but it does not.
JavaScript: Aync/Await not waiting until the function is fully processed [duplicate]
async function fnGetVehicleList(makeCode, responseModels){
let vehicleListData = [];
await responseModels.Table.forEach(async (model) => {
const vehicleDetailResponse = await getVehicleDetails('2024',makeCode, model.Code); // API call. This is also an Async function
await vehicleDetailResponse.Table.forEach(async (vehicleItem)=>{
await vehicleListData.push(vehicleItem);
});
});
return await vehicleListData;
}
Here the vehicleListData is not waiting until both the forEach loops are executed.
It waits till, it makes the API call for all the items in responseModels forEach Loop. But once the API call is made, it is not awaiting the second forEach loop i.e. (vehicleDetailResponse.Table.forEach) and simply returns the vehicleListData which is empty data from the function.
Please let me know how to wait the second forEach loop is also executed and then function to return the response
Need advice on how to store Encrypted verifier for PKCE auth0 workflow using Svelte kit
I’m working on an authentication workflow using SvelteKit and Auth0, and I’ve encountered a challenge that I hope someone can help me resolve.
Current Workflow:
Login Endpoint:
When a user is redirected to the login endpoint, I have a +server.ts file that generates the PKCE verifier and code challenge, so that I can send it to the authorization endpoint.
The endpoint the sends a query to the Auth0 authorization endpoint.
Callback Endpoint:
After the login process is complete, users are redirected to the callback endpoint, which also has a +server.ts file.
At this point, I make a call to the Auth0 token endpoint and need to pass the original PKCE verifier.
Initially, I stored the verifier token in an HTTP cookie then deleted it after I make the request to the token endpoint. However, I’ve read that storing this in plain text isn’t secure.
To address this, I encrypted the verifier before storing it.
I’m struggling to find a secure way to pass the encryption key and IV values to the callback endpoint so that I can decrypt the verifier token before sending it to the Auth0 token endpoint. Iv looked at different things such as stores, how the svelte documentation highly discourages the use of stores in server files.
Flickering unstyled content code need for elementor
I need this code to be usable with all my template instead of one specific template of my website.
I am using Elementor and it suggested following code:
add_action('wp_enqueue_scripts', function() {
if (!class_exists('ElementorCoreFilesCSSPost')) {
return;
}
$template_id = 123456;
$css_file = new ElementorCoreFilesCSSPost($template_id);
$css_file->enqueue();
}, 500);
How can I change it for use with any template? So when I insert in my function.php it will be applied to whole website instead of one specific template.
Unable to handle case of null variable in javascript/react native
I am trying to do something very simple in my react native log in screen. I first try and get the userId of a user and if it’s not set I want to redirect to the user’s login page. When the userId is not set I console out and get a null value for it. But when I create a if statement to check if the userId === null it doesn’t work. Any ideas on what I am doing wrong?
const userId = await AsyncStorage.getItem('userId');
console.warn(userId);
console.warn("When userId is not set I get a value of null");
if (userId === null) {
console.warn("However this check for null is not working");
navigation.navigate("UserLoginWeb");
}
Problem with request in my react native app
I’m the newbie here and newbie in React and laravel (computer science student)
I have problem with react native app.
I have backend with api on WSL with Laravel.React native app on Windows 11.
Problem is when i send “GET” to endpoint with axios:
Config axios:
import Axios from 'axios';
import * as SecureStore from 'expo-secure-store';
const axios = Axios.create({
baseURL: process.env.EXPO_PUBLIC_BACKEND_URL,
maxContentLength: Infinity,
maxBodyLength: Infinity,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json',
},
});
axios.interceptors.request.use(async function (config) {
const storedUser = await SecureStore.getItemAsync('user');
if (storedUser) {
const user = JSON.parse(storedUser);
if (user.token) {
if (!config.headers.Authorization) {
config.headers.Authorization = `Bearer ${user.token}`;
}
}
}
return config;
}, function (error) {
return Promise.reject(error);
});
export default axios;
Use of axios
async function getAllCars() {
try {
const response = await axios.get("/cars");
console.log(response.data);
setData(response.data);
} catch (error) {
console.error("Error fetching cars:", error.message);
}
}
sometimes (in first try when i want to get data, sometimes after 4 calls) my respone not closed with a bracket like this:
[
{
"id": 1,
"brand": "esse",
"model": "omnis",
"year": "1981-06-24",
"mileage": 4897997,
"vin_number": "illum",
"client": {
"id": 8,
"name": "Rasheed Dickens III",
"surname": "Fausto Ruecker",
"email": "[email protected]",
"phonenumber": 17576616844
},
"archive_service": [],
"services": []
},
*
*
*
{
"id": 60,
"brand": "quibusdam",
"model": "nobis",
"year": "1971-01-17",
"mileage": 85544,
"vin_number": "voluptatem",
"client": {
"id": 9,
"name": "Mr. Benedict Walker IV",
"surname": "Mrs. Elody Hoeger",
"email": "[email protected]",
"phonenumber": 5757802548
},
"archive_service": [],
"services": []
}
JSON need to be closed but something cutting off the close bracket
I debug the backend and always send the full JSON (with close bracket).
Also i try in react native change method to fetch (with and without async).
I use postman and the same result. Everything is fine.
I try to update React Native and this doesn’t change everything.
In my last try i write php script to fetch data and also i have good response.
Someone have the same problem? Maybe i do something wrong? This is a 6 day when i sitting with this problem and cant go any further (i have deadline to 24 to show my application)
How should I reference different files for different devices using Angular?
So this is my project’s structure in version 18.2.8.
enter image description here
This is the structure if I’m looking with a pc:
enter image description here
What I want to do is to show a css file depending on what you are logged with. But I’m not entirely sure on how I’m suposed to reference the CSS files in an angular project. I did not want to use media queries because I don’t want my app to show on the pc as if it were a phone whenever I make the window very small, so I tried to do it with userAgent to check if it’s beeing looked at with a phone or a desktop.
Right now I’m very confused because when I compile the code into the website, my styles.css gets combined with both of the other CSS files as if I were to do @include.
The website also creates another “copy?” of the desktop.css (when I’m looking with a desktop) and puts it on the same level as the styles.css, so if I have multiple variables named the same, it uses this file first and it’s fine. But if I have a variable in mobile.css and not in desktop.css, it shows in both because it gets combined in styles.css.
What should I do?
For some context this is what is in my AppComponent:
This works as it should.
constructor() {
const userAgent = navigator.userAgent.toLowerCase();
if (/mobile/i.test(userAgent)) {
this.device = "mobile";
} else {
this.device = "desktop";
}
this.loadStylesheet();
}
loadStylesheet() {
const head = document.getElementsByTagName('head')[0];
// Create a new link element
const linkElement = document.createElement('link');
linkElement.rel = 'stylesheet';
linkElement.type = 'text/css';
linkElement.href = this.device === 'mobile'
? 'mobile.css'
: 'desktop.css';
// Append the link element to the head
head.appendChild(linkElement);
}
I tried to add the css files like this in my angular.json:
"styles": [
"src/styles.css",
"src/app/styles/desktop.css",
"src/app/styles/mobile.css"
]
I expected to see the files just to stay as they are, and show only when I’m on the pc or phone as it should. But actually what happened is what I described before, it creates a css file automatically, and also combines all the css into styles.css.
Also, on the begining I just deleted styles.css and removed it from angular.json, but it got created anyway. I want to keep the file regardless, but I think it’s worth pointing out.
Scrolling the modal window in React
I created a component in React that I use as a modal window that opens when you click on a button, but I don’t know how to make it scroll when it opens, and not the main window.
import close from '/close.png';
import add from '/add1.png';
import './Modal.css';
import MainButton2 from '../Button/MainButton2'
import { useState, useRef } from "react";
export default function Modal ({ isOpen, onClose }, props) {
if (!isOpen) return null;
return (
<div className="modal-overlay">
<div className="modal-content">
<div className='thefirstrow'>
<div className='newpod'>jasjssj</div>
<img className='close' src={close} alt='user' style={{ cursor: 'pointer' }} onClick={onClose}/>
</div>
</div>
</div>
);
};
that’s how it opens in the main window:
<Modal isOpen={isModalOpenPodcast} onClose={() => setIsModalOpenPodcast(false)} />
how to make a function inside a function can can only be called inside that function JavaScript
how to make a function inside a function can can only be called inside that function JavaScript
like
function idk(callback) {
function test() {
console.log("Test function called!");
}
const frozenTest = Object.freeze(test);
callback(frozenTest);
}
// Usage
idk((tests) => {
tests();
});
but when doing
idk((testing)=>{
testing((
})
it can change names, im making a project so i dont want that
i tried a lot of ways but it can still be changed
i really needed to know how, if you guys can teach. Just teach me how to make a function that is only callable inside a function or how to make it so that it doesn’t change the name of the function like the example test()
How to ensure type compatibility without assertions or typeguards
I am trying to enforce type compatibility between a dynamically fetched object and a specific interface, without relying on assertions, type casting, or runtime checks like typeguards. Here’s a simplified example of the issue:
// @filename: api.ts
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
type JSONPrimitive = string | number | boolean;
type JSONObject = { [key: string]: JSONValue };
type JSONArray = Array<JSONValue>;
function fetchData(): JSONObject { return {}; }
// @filename: index.ts
type DoSomethingProps = { foo: string; bar: number };
function doSomething(obj: DoSomethingProps) {
// When typing `obj.` intellisense should suggest 'foo' and 'bar'
}
const data1 = fetchData(); // Does satisfies DoSomethingProps, e.g. is an object with keys as string and values as string or number (same schema as JSONObject)
const data2: undefined | number | string | Array<() => boolean> = undefined; // Does not satisfies DoSomethingProps, therefore should error if pass as argument
doSomething(data1); // Error, but should not
doSomething(data2); // Error as intended
Requirements:
- No assertions, casting (e.g.
as ...), or typeguard functions (e.g.obj is ...). - No runtime checks like
ifstatements orinoperators. - It must work for any type that matches the schema of
JSONObjectand not just this specific example. - Preferably solved at the typelevel, potentially using a utility type.
The ideal solution would be to have a utility type like ToMatchesSchema<T> that can enforce this compatibility for any given type T.
!!!NOTE!!!:
I understand that this approach is not type-safe and can be considered a “code smell”. Passing an empty object as a prop would result in runtime errors when accessing properties, but it’s still better than using any. This solution allows the rest of the project to benefit from TypeScript’s type safety, even if this function has some compromises.
Acessing variable outside the scope in handlebars
i have this handlebars template, that looks like this
{{#each leagues}}
<tr>
<td>{{leagueName}}</td>
<td>{{season}}</td>
<td>
<form action="/groups/{{../id}}/teams/{{id}}/leagues/{{leagueId}}/season/{{season}}" method="POST">
{{#if ../groups}}
<select name="group" class="form-select">
{{#each ../groups}}
<option value="{{id}}">{{name}}</option>
{{/each}}
</select>
<input type="submit" value="Add" class="btn btn-primary mt-2">
{{else}}
<div class="d-flex align-items-center">
<p class="text-danger mb-0">No groups available</p>
<a href="/createGroup" class="btn btn-secondary ms-2">Create Group</a>
</div>
{{/if}}
</form>
</td>
</tr>
{{/each}}
my issue is when I do the post, I want to pass on the body both, the id of the league, and the id of the group. both are called “id”. When I do {{../id}} to access the group “id” that is outside the scope it still doesn’t work.
this way, im getting for example
Cannot POST /groups//teams/123/leagues/321/season/1904
the group “id” is not going as planned.