How can I apply the patchValue method on deeply nested form groups in this Angular app?

I am working on a form in Angular 14. I run into a problem while using deeply nested form groups. (It is not a choice to do so, it is a necessity).

In form.component.ts I have:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { FormService } from '../services/form.service';

@Component({
  selector: 'my-app',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css'],
})
export class FormComponent {
  public accountTypes!: any;
  public selectedAccountType: any;

  public form: FormGroup = new FormGroup({
    first_name: new FormControl('', Validators.required),
    last_name: new FormControl('', Validators.required),
    email: new FormControl('', [Validators.required, Validators.email]),
    phone: new FormControl('', Validators.required),
    accountEssentials: new FormGroup({
      accountInfo: new FormGroup({
        account_type: new FormControl(''),
      }),
    }),
  });

  constructor(private formService: FormService) {}

  ngOnInit(): void {
    this.getAccountTypes();
  }

  public getAccountTypes() {
    this.formService.getAccountTypes().subscribe((response) => {
      this.accountTypes = response;
      this.form.controls['accountEssentials.accountInfo'].patchValue({
        account_type: this.accountTypes[0].value,
      });
    });
  }

  public sendFormData() {
    console.log(this.form);
  }
}

The form’s template:

<form [formGroup]="form">
  <mat-form-field appearance="outline" floatLabel="always">
    <mat-label class="mat-label">Fast name:</mat-label>
    <input class="mat-input" matInput formControlName="first_name" />
  </mat-form-field>

  <mat-form-field appearance="outline" floatLabel="always">
    <mat-label class="mat-label">Last name:</mat-label>
    <input class="mat-input" matInput formControlName="last_name" />
  </mat-form-field>

  <mat-form-field appearance="outline" floatLabel="always">
    <mat-label class="mat-label">Email:</mat-label>
    <input class="mat-input" matInput formControlName="email" />
  </mat-form-field>

  <mat-form-field appearance="outline" floatLabel="always">
    <mat-label class="mat-label">Phone:</mat-label>
    <input class="mat-input" matInput formControlName="phone" />
  </mat-form-field>

  <div formGroupName="accountEssentials">
    <div formGroupName="accountInfo">
      <mat-radio-group
        formControlName="account_type"
        [(ngModel)]="this.selectedAccountType"
      >
        <mat-radio-button
          *ngFor="let accountType of accountTypes"
          [value]="accountType.value"
        >
          <span class="top-label">{{ accountType.label }}</span>
        </mat-radio-button>
      </mat-radio-group>
    </div>
  </div>
</form>

See this Stackblitz.

The problem

The patchValue method does not work on the account_type form control that I try to access with accountEssentials.accountInfo.

this.form.controls['accountEssentials.accountInfo'].patchValue({
    account_type: this.accountTypes[0].value,
});
What is the most reliable way to achieve the desired result?

React SWR mutate Array

I have been trying to mutate an array using swr and it has been giving me hadache… the data get to the database but it only shows after a refresh.

here is my code

const BookTicket = async (e) => {
e.preventDefault();

const booking = formData.map((item, index) => {
  const id = uuid();
  return {
    id: id.concat(index),
    ...formData[index],
    from: value,
    destination: destinations,
    pickup: pickup,
    startDate: startDate.toDateString(),
    trip: selectedTrip.name,
    totalAmount: sum,
    discount: currentValue,
    totalPaid: sum - currentValue,
    luggage: luggage,
    paymentMethod: payment,
  };
});



    const uploadMessageToUpstash = async () => {
      const data = await fetch("/api/addBookings", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          booking,
        }),
      }).then((res) => res.json());

      return [data.booking, ...seats?.takenSeats];
    };
    await mutate(uploadMessageToUpstash, {
      optimisticData: [booking, ...seats?.takenSeats],
      rollbackOnError: true,
    });
    setSelectedSeats([]);
  };

Best Red Black Tree package for Javascript

We need to have an essentially ordered dictionary, where we can

  • insert fast O(log n)
  • delete fast O(log n)
  • find all items fast, where the key starts with a string y.

Hence, we thought of a Red-Black Tree, which has all the properties.

However, on npm we just found tons of implementations. Hence we were wondering whether there is something you consider the best for starting.

Add JSON data to an array in JavaScript

Hello I am new to JavaScript and I have been trying to parse JSON data into a JavaScript array. I can load the local .json file and print it to the console. I want to print each ‘key’ and ‘value’ pair. Having come from a python background, this is new to me. This is a sample JSON data. The structure of the data I want to use is the same. I am mostly having trouble because of the strucure of the JSON data. I have to control to change the structure of the JSON data

{
    "emp_details":[
    {
        "emp_name":["abc"],
        "email":["[email protected]"],
        "job_profile":["Full time"]
    }
    
    ]
}

And here is what I have done. Which is just read the local file and print it to the console.

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

readTextFile("./data.json",function(text){
    var data = JSON.parse(text);
    var dataArray = []
    dataArray.push(data)    
    //alert(data);
    console.log(dataArray[0]);
});

Ideally I want the result to be like to display in an HTML table:

emp_name: abc

email: [email protected]

job_profile: Full time

Thank you!

How to implement csrf token into ssr application with express? Seems like csurf is deprecated

I want to implement a csrf token into my application’s server sider rendered web page but do not know how this process work and the package I found that tutorial’s use is deprecated (csurf). How would I go about implementing csrf? Really need help 🙁

I tried watching many tutorial’s so far and nothing that uses express and templates with a non-deprecated csrf package. So I’m really lost as this is my first time and I want to get it right.

Multiple printing with Javascript [duplicate]

I’ve been trying for a long time to launch the printing of a number x of copies contained in a variable. Let me explain: I have a small form that retrieves the number of copies desired by the user and then the JavaScript opens the print dialog box. But I can’t get the value entered by the user into the number of copies in the print dialog.

<script>
    function printTicket() {
        var number_copies = <?php echo $number_copies; ?>;
        for (var i = 0; i < number_copies; i++) {
            window.print();
        }
    }
</script>

This is where I am.

Textinput stops working in my entire android app

I have a textinput on a screen where users are required to entire their cvv inside, when the user press pay a web view modal opens with the gateway flow. After the flow on the webview is completed, the modal is closed and the user gets redirected back to the home screen.

On ios everything is working.

On android the modal closes and no redirection happens and also any text input inside my app stops working.

<View 
style={{
  borderRadius:5,
  borderWidth:1,
  height:30,
  marginTop:10,
  marginHorizontal:20
  }}>
<TextInput 
          placeholder={"CVV"}
          maxLength={3} 
          keyboardType={"numeric"}
          onChangeText={cvv => setCvv(cvv)}
          value={cvv.value}
          />
</View>

<AppButton title="Pay now" 
onPress={()=>{
  console.log(cvv.length)
  if(cvv.length!==3){
    return Alert.alert('Please enter your card security code (CVV).',"This can be found on the back of your card.")
  }
  handlePayment();
}}
/>

enter image description here

enter image description here

Nextjs Web app showing “untitled” in google search

I have deployed a nextjs web app in aws with ssl certificate added. It’s working fine when I browse directly to the app. But, when I search it in the google, it showing “untitled”,
“javascript not enabled” and showing http instead of https.

enter image description here

I’m sure I have added the title and all meta tags. I’m using next/image for render image. Is it will be the issue?

Comparing values of objects in array and making operation on them

I’m trying to compare same field elements in objects and restructuring them. I tried to use filter, sort methods but couldn’t achieve that. I have an array like this:

const data = [
  {
    id: 1,
    direction: "A",
    carry: 6,
    distance: 1.41,
  },
  {
    id: 2,
    direction: "B",
    carry: 5,
    distance: 2.83,
  },
  {
    id: 3,
    direction: "C",
    carry: 4,
    distance: 4.24,
  },
  {
    id: 4,
    direction: "D",
    carry: 3,
    distance: 5.66,
  },
];

For example: Let’s take distance field, they are 1.41, 2.83, 4.24, 5.66. The biggest value (5.66) will be 100%, and other values can be calculated like proportion.

5.66 -> 100%

1.41 -> 25%

2.83 -> 50%

4.24 -> 75%

The carry field follows this way as well. The final result should be like that:

const data = [
  {
    id: 1,
    direction: "A",
    carry: 6,
    carry_rating: 100,
    distance: 1.41,
    distance_rating: 25,
  },
  {
    id: 2,
    direction: "B",
    carry: 5,
    carry_rating: 84,
    distance: 2.83,
    distance_rating: 50,
  },
  {
    id: 3,
    direction: "C",
    carry: 4,
    carry_rating: 67,
    distance: 4.24,
    distance_rating: 75,
  },
  {
    id: 4,
    direction: "D",
    carry: 3,
    carry_rating: 50
    distance: 5.66,
    distance_rating: 100,
  },
];

I’m struggling for several days. Any support is much appreciated.

How to write a cypress test for vue js router-link?

Hi I’m new to cypress and trying to make test for vue js <router-link>. Following is the example

About.vue

<router-link data-cy="contactViewLink" :to="{name: 'ContactView'}">Click here</router-link>

About.cy.js

it('Then: User click on Contact View link', () => {

      // Do assertions
      cy.get('[data-cy="contactViewLink"]').click()

      cy.get('@routerPushStub').should('have.been.calledWith', {
        name: 'ContactView'
      })
    })

wix fetch (post) to qrmonkey api

I’m trying to fetch a qr code using qrmonkey’s api from (the frontend of) my wix page.

I’ve tried to adjust the code in the wix examples, along with variations suggested by posts on the wix forums and here without luck. (including trying to make it a form-data request given the number of parameters).

Can someone tell me whether or not I’m in the right ballpark with my code? I guess ultimately I’m trying to set the src of a placeholder image to the QR code, but i’m just trying to get anything back in my post request at this point.

thanks

import {fetch} from 'wix-fetch';

const apiURL = "https://api.qrcode-monkey.com/qr/custom";
const body = {
    "data":"https://www.qrcode-monkey.com",
    "config":{
    "body":"rounded-pointed",
    "eye":"frame14",
    "eyeBall":"ball16",
    "erf1":[],
    "erf2":["fh"],
    "erf3":["fv"],
    "brf1":[],
    "brf2":["fh"],
    "brf3":["fv"],
    "bodyColor":"#5C8B29",
    "bgColor":"#FFFFFF",
    "eye1Color":"#3F6B2B",
    "eye2Color":"#3F6B2B",
    "eye3Color":"#3F6B2B",
    "eyeBall1Color":"#60A541",
    "eyeBall2Color":"#60A541",
    "eyeBall3Color":"#60A541",
    "gradientColor1":"#5C8B29",
    "gradientColor2":"#25492F",
    "gradientType":"radial",
    "gradientOnEyes":false,
    "logo":""
    },
    "size":300,
    "download":false,
    "file":"svg"
    };

export function image1_click(event) {
    test3();
}

export function test3(){
    
    fetch( apiURL, {
    "method": "post",
    "headers": {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    "body": body
    } )
    .then( (httpResponse) => {
        if (httpResponse.ok) {
        return httpResponse.json();
        } else {
        return Promise.reject("Fetch did not succeed");
        }
    } )
    .then( (json) => console.log(json.someKey) )
    .catch(err => console.log(err));
}

I’ve tried adjusting the code/versions of the code for all the forum posts I could find on the subject without luck. I’m trying to get a qr code back using qrmonkey’s api. Ultimately it’d be nice to just know it’s possible so I know whether or not to keep trying.

Another version i’ve tried: How do I POST a x-www-form-urlencoded request using Fetch?

SvelteKit Dev Server + Auth.js – Cross-site POST form submissions are forbidden on sign in

I am using Auth.js for authentication in SvelteKit. I followed the instructions given by the documentation here, but when I tried to click my sign in button nothing happens and in the console I get a 403 error from /auth/signin/google? and Uncaught (in promise) SyntaxError: Unexpected token 'C', "Cross-site"... is not valid JSON, meaning that the POST request is returning an error of “Cross-site POST form submissions are forbidden”. I followed the exact instructions as in the documentation, but using the google provider instead.

// /src/hooks.server.ts
import { SvelteKitAuth } from "@auth/sveltekit"
import Google from "@auth/core/providers/google"
import { GOOGLE_ID, GOOGLE_SECRET } from "$env/static/private"

export const handle = SvelteKitAuth({
    //@ts-expect-error issue https://github.com/nextauthjs/next-auth/issues/6174
    providers: [Google({
        clientId: GOOGLE_ID,
        clientSecret: GOOGLE_SECRET,
    })]
});

// /src/routes/+layout.server.ts
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async (event) => {
  return {
    session: await event.locals.getSession()
  };
}; 
<!-- /src/routes/+layout.svelte -->
<script>
    import '../app.postcss';
    
  import { DarkMode } from 'flowbite-svelte';
    import { Navbar, NavBrand, NavLi, NavUl, NavHamburger, Button, Input, P } from 'flowbite-svelte';
    import { page } from "$app/stores";
    import { signIn, signOut } from "@auth/sveltekit/client"
</script>

<div>
    <Navbar let:hidden let:toggle>
  <NavBrand href="/">
    <img
      src="https://flowbite.com/docs/images/logo.svg"
      class="mr-3 h-6 sm:h-9"
      alt="Flowbite Logo"
    />
    <span class="self-center whitespace-nowrap text-xl font-semibold dark:text-white">
      AMC Trainer
    </span>
  </NavBrand>
  <div class="flex md:order-2">
        <DarkMode class="mr-3" />
        {#if $page.data.session}
            <P>Signed in as {$page.data.session.user?.name}</P>
        {:else}
<!--            <Button size="sm" href="/auth/signin" data-sveltekit-preload-data="off">Sign in</Button>     -->
            <Button size="sm" on:click={() => {signIn("google", {callbackUrl: "https://amc.grapecoder.repl.co/"})}}>Sign in</Button>
        {/if}
    <NavHamburger on:click={toggle} />
  </div>
  <NavUl {hidden} class="order-1">
    <NavLi href="/" active={$page.url.pathname == "/"}>Home</NavLi>
    <NavLi href="/about">About</NavLi>
    <NavLi href="/services">Services</NavLi>
    <NavLi href="/pricing">Pricing</NavLi>
    <NavLi href="/contact">Contact</NavLi>
  </NavUl>
</Navbar>
<!--text-slate-900 dark:text-slate-100  -->
<div class="my-5 lg:mx-40 md:mx-20 mx-10 ">
    <slot />
</div>

</div>

Here is my GitHub repo.

I tried to add the “callbackUrl” property to the sign in button. I wasn’t sure what was wrong with my code, though. I also went through the type definitions for the provider to see if there was anything I could add as an option to fix this. Expected behaviour would be that I get sent to the Google accounts sign in page and be able to log in normally.

Failed to access Wikipedia API

Hello I’m total beginner at JavaScript and I’m trying to use Wikipedia API to search the meaning of ‘topic’ through it, but I always get an error.

Error:

Access to fetch at ‘https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=love&explaintext=true&exintro=true’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Script:

fetch("https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=love&explaintext=true&exintro=true")
  .then(response => response.json())
  .then(data => {
    let page = data.query.pages[Object.keys(data.query.pages)[0]];
    let definition = page.extract;
    let p = document.createElement("p");
    p.innerHTML = definition;
    document.body.appendChild(p);
  })
  .catch(error => {console.log(error)})