I am attempting to add a return to “top” button/function for a side-scrolling page, but it isn’t reappearing as usual. Is this possible to do?

First off, I did find a similar question, but it didn’t help with what I am trying to do. I am attempting to add a return to “top” button on a page that is a side-scrolling page. The axis are just inverted, so I would assume it would still function the same as a normal return to top button, as it is essentially scrolling the same axis. The button displays properly until I set display: none. After that, I have been unable to make it reappear after scrolling the page. Currently have it set to display > 30. I have included the html, css, and js below that I have tried thus far.

HTML and js (located inside body)

<button onclick="returnToStartFunction()" id="toStart" title="Return to Start">&#8656;</button>

<script>
    let startButton = document.getElementById("toStart");

    window.onscroll = function() {scrollFunction()};

    function scrollFunction() {
        if (document.body.scrollTop > 30 || document.documentElement.scrollTop > 30) {
            startButton.style.display = "block";
        } else {
            startButton.style.display = "none";
        }
    }

    function returnToStartFunction() {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    }
</script>

CSS

/*
Start styling for return to start arrow.
*/

#toStart {
    display: none;
    position: fixed;
    bottom: 0;
    right: 0;
    padding: 0.5rem;
    font-size: 65px;
    color: rgba(255,255,255,.9);
    background: rgba(255,255,255,.25);
    backdrop-filter: blur(5px);
    border: none;
    border-radius: 8px 0 0 8px;
    outline: none;
    z-index: 999;
}

#toStart:hover {
    background-color: rgba(30,101,49);
}

/*
End styling for return to start arrow.
*/

How to prevent scroll event overlap with scrollIntoView() scroll- behavior: smooth?

I’m relying on a very basic use of scrollIntoView() scroll-behavior:smooth to ensure the current line of a multi-line text is scrolled along with a user’s typing in a different input.

The issue is if a user types very fast or types short phrases, scrollIntoView() can be called multiple times before the previous scrollIntoView() action completes. This results in a jittery visual scrolling effect due to the easing of the scroll-behavior:smooth.

How can I repeatedly call scrollIntoView() scroll-behavior:smooth but have it only engage if the previous scroll has completed and is no longer in action?

JavaScript How to init TPDCard in Tappay

I want to write a TapPay Library Web version.

I want to test a function that can use hardcore number to getPrime,

but every sample is create fields waiting user to input cardNumber.

I dont want to create any fields.

Just like this Kotlin sample. Is there has similar code in JavaScript?

    val cardNumber= StringBuffer(cardNumber)
    val dueMonth= StringBuffer(dueMonth)
    val dueYear= StringBuffer(dueYear)
    val ccv= StringBuffer(ccv)
    val card = TPDCard(context, cardNumber, dueMonth, dueYear, ccv).onSuccessCallback { prime, _, _, _ ->
                onSuccess(prime)
            }.onFailureCallback { status, errorMessage ->
                onFailure(errorMessage )
            }
            card.createToken(/* geoLocation = */ "Unknown")

How Can I Make This Car Rotate Properly With or Without Merging Meshes(Three.js)?

The problem that I have here is that I’m trying to make a car game here but the problem is that as you can see the wheel’s are rotating but not along with the car, here is the code I have in my car.js file:


export function createCar(x, y, z, color) {
  const geometry = new THREE.BoxGeometry(0, 0, 0);
  const material = new THREE.MeshBasicMaterial();
  const carCenter = new THREE.Mesh(geometry, material);
  carCenter.position.set(x + 2.5, y, z + 1.25)
  let objects = [carCenter];

  function createWheel(x, y, z) {
    createTorus(0.5, 0.25, "#36353a", x, y, z);
    createTorus(0.25, 0.25, "gray", x, y, z);
  }

  function createBody() {
    createRectangle(5.5, 3, 1, color, x + 2.5, y + 1, z + 1.25);
    createRectangle(2.5, 3, 1, "#e1ebe3", x + 1.75, y + 2, z + 1.25)
  }
  
  function createTorus(radius, innerRadius, color, x, y, z) {
    const geometry = new THREE.TorusGeometry(radius, innerRadius, 16, 100);
    const material = new THREE.MeshLambertMaterial({ color: color });
    const torus = new THREE.Mesh(geometry, material);
    torus.position.set(x, y, z);
    
    objects.push(torus);
    return torus;
  }

  function createRectangle(length, width, height, color, x, y, z) {
    const geometry = new THREE.BoxGeometry(length, height, width);
    const material = new THREE.MeshLambertMaterial({ color: color });
    const rect = new THREE.Mesh(geometry, material);
    rect.position.set(x, y, z);
    
    objects.push(rect);
    return rect;
  }

  function createCylinder(radius, height, color, x, y, z) {
    const geometry = new THREE.CylinderGeometry(radius, radius, height, 32);
    const material = new THREE.MeshLambertMaterial({color: color});
    const cylinder = new THREE.Mesh(geometry, material);
    cylinder.position.set(x, y, z);
    
    objects.push(cylinder);
    return cylinder
  }

  createWheel(x, y, z);
  createWheel(x + 5, y, z);
  createWheel(x, y, z + 2.5);
  createWheel(x + 5, y, z + 2.5);
  createBody();

  function turnRight() {
    objects.forEach(part => {
      part.rotation.y += 0.1;
    })
  }
  
  return {
    objects,
    turnRight,
  }
}

I don’t care if it uses sin or cosine or combining meshes(which I couldn’t find a method that would work). I tried for hours and still couldn’t find an answer for how to make the wheels kind of swing along with the corner of the car. I also tried to find a way to get the position in the corner of a box so I could set the wheel position to that. Is there another way to do it

How to setState after the page reloads

On mobile screen, the drop down navigation menu stays open even after a user has been directed to a page. I want it to close after any page reloads.

This is what i’ve tried in my navigation.jsx:

useEffect(() => {
    console.log("Open? ", open);
  }, [open]);

  useEffect(() => {
    if (window.performance.getEntriesByType) {
      if (
        window.performance.getEntriesByType("navigation")[0].type === "reload"
      ) {
        console.log("reloaded");
        setOpen(false);
      }
    }
  }, []);

I expected this to render every time the navigation pane re-renders but since its outsider of the browser router Navigation.jsx only renders once in the app unless there is a change in authentication etc because menu items change.

App.js

function App() {
  return (
    <>
      <BrowserRouter>
        <Navigation />
        <Routes>
//Bunch of code
        </Routes>
        <Footer />
      </BrowserRouter>
    </>
  );

I’m trying to figure out which dependencies to add or just how to go about ensuring that when there is a page reload(doesn’t matter which page) then setOpen(false).

I’m trying to create a pinia store to store my userId when I log in so when I submit updates or reload the page it doesn’t lose the userId

Hi I’m trying to create an update page so that a user can update their data in a firestore database but the problem I am having is once the form is submitted to update or the page is reloaded the userId is no longer there so I am trying to use pinia to store the userId so when the form is submitted for update it can retrieve the userId from there and update the data in the database.
The problem is I’m still learning and I’m not sure how to actually save the userId in the store and am having trouble figuring it out, I’ve stored a count before for a simple counter and I’ll put that in below as well as what I’ve currently got for the update page so you can know where I’m at.

The counter vue

<script setup>
defineProps({
  msg: String,
})

import { useCounterStore } from '../store/counter'
import { storeToRefs } from 'pinia'
import { ref } from 'vue'


const store = useCounterStore()

const { count, doubleCount } = storeToRefs(store)
// the increment action can just be destructured
const { increment, clearCount } = store

const show = ref(false)

</script>

<template>
  <h1>{{ msg }}</h1>

  <div class="card">
    <button type="button" @click="increment">count is {{ count }}</button>
    <button type="button" >double count is {{ doubleCount }}</button>
    <button type="button" @click="clearCount">Clear count</button>
    <p>
      Edit
      <code>components/HelloWorld.vue</code> to test HMR
    </p>
  </div>
</template>

The javascript pinia store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'


export const useCounterStore = defineStore('counter', () => {
    const count = ref(0)
    const doubleCount = computed(() => count.value * 2)
    function increment() {
        count.value++
    }
    function clearCount() {
        count.value = 0
    }

    return { count, doubleCount, increment, clearCount }
},
    {
        persist: true,
    },
)

And here is my update page.vue with no store attched

<script>

import getCollection from '../Composables/getCollection';
import getUser from '../Composables/getUser';
import getPremium from "../Composables/getPremium.js";
import { ref } from "vue";
import  useDocument from '../Composables/useDocument';

const {Premium, error, load} = getPremium();
load();





export default{
   
 
    
  setup() {
    

 const Name = ref('')
    const detail1 = ref('')
    const detail2 = ref('')
    const detail3 = ref('')
    const detail4 = ref('')
    const detail5 = ref('')
    const details = ref('')
    const detail6 = ref('')
    const detail7 = ref('')
    const detail8 = ref('')
    const detail9 = ref('')
  

    


    const { user } = getUser()
    const { documents: Premium } = getCollection(
      'Premium', 
      ['userId', '==', user.value.uid]
    )
   const { updateDoc } = useDocument('Premium', Premium.id)

const createProfile = async () => {
const res = await updateDoc({
      
        
        Name: Name,
        detail1: detail1,
        detail2: detail2,
        detail3: detail3,
        detail4: detail4,
        detail5: detail5,
        details: details,
        detail6: detail6,
        detail7: detail7,
        detail8: detail8,
        detail9: detail9,

        
      
      
    
      })
    


    }
    return { Name, detail1, detail2, detail3, detail4, detail5, details, detail6, detail7,
        detail8, detail9,
        createProfile, Premium }
  }
}


</script>


<template>
<br><br>
<div v-if="error">{{ error }}</div>

<div v-if="Premium" class="Profile">
 
  
<div v-for =" Premium in Premium" :key="Premium.id">
<p class="text-5xl text-red-700 font-serif">Your Profile</p>
<p class="text-5xl text-red-700 font-serif">{{ Premium.Name }}</p>
<br><br>


        
    
     <br><br>
     <router-link :to="{ name: 'Premium_Edit', params: { id: Premium.id }}">
    <p class="bg-neutral-800 hover:bg-neutral-900 active:bg-neutral-800 hover:text-neutral-400 hover:scale-105 text-red-700 w-64 p-4 rounded-xl shadow cursor-pointer inline-block m-10 transition ease-in-out duration-300 drop-shadow-2xl"></p>
    </router-link>
    <p class="text-3xl text-red-700 font-serif text-left mx-4 md:mx-36 lg:mx-36 xl:mx-36 2xl:mx-36">Details</p>
    <hr><br>
    <div class="grid gap-4 grid-cols-2 grid-rows-fit md:grid md:gap-4 md:grid-cols-4 md:grid-rows-4">
        <p class="font-bold">Location:<br>{{ Premium.Location }}</p>
        
        <p class="font-bold">details:<br></p>
        
        <p class="font-bold">detail4:<br>{{ Premium.detail4 }}</p>
       
        <p class="font-bold">detail2:<br>{{ Premium.detail2 }}</p>
        
        <p class="font-bold">detail7:<br>{{ Premium.detail7 }}</p>
        
        <p class="font-bold">detail6:<br>{{ Premium.detail6 }}</p>
        
        <p class="font-bold">detail8:<br>{{ Premium.detail8}}</p>
        
        <p class="font-bold">detail5:<br>{{ Premium.detail5 }}</p>
        
        <p class="font-bold">detail1:<br>{{ Premium.detail1 }}</p>
       
        <p class="font-bold">detail3:<br>{{ Premium.detail3 }}</p>
        
       
    </div><hr>
    
     
     </div><hr><br><br><br><br>


<p class="text-5xl text-red-700 font-serif">Edit Your Profile</p>
 
   <br>
 <form @submit.prevent="createProfile">
<div id= "app">
 <div class="mx-20 grid gap-y-4 grid-cols-1 grid-rows-fit md:mx-80 md:grid md:gap-x-60 md:gap-y-4 md:grid-cols-2 md:grid-rows-fit md:justify-center lg:mx-80 lg:grid lg:gap-x-60 lg:gap-y-4 lg:grid-cols-2 lg:grid-rows-fit lg:justify-center xl:mx-80 xl:grid xl:gap-x-60 xl:gap-y-4 xl:grid-cols-2 xl:grid-rows-fit xl:justify-center 2xl:mx-80 2xl:grid 2xl:gap-x-60 2xl:gap-y-4 2xl:grid-cols-2 2xl:grid-rows-fit 2xl:justify-center">
    
    
 <input v-model="Name" required type="text" placeholder="Name" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow">
 
            <input id="detail1" v-model="detail1" required type="text" placeholder="detail1" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow ">
            <input id="detail2" v-model="detail2" required type="text" placeholder="detail2" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow">
            <input id="detail3" v-model="detail3" type="text" required placeholder="detail3" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow ">
            <input id="detail4" v-model="detail4" type="text" required placeholder="detail4" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow">
           <input id="detail5" v-model="detail5" type="text" required placeholder="detail5" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow">
           <input id="details" v-model="details" type="text" required placeholder="details" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow">
           <input id="detail6" v-model="detail6" required type="text" placeholder="detail6" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow">
           <input id="detail7" v-model="detail7" required type="text" placeholder="detail7" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow">
           <input id="detail8" v-model="detail8" required type="text" placeholder="detail8" class="h-8 w-fit bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow">
            </div>
           <br>
            
 <p class="text-2xl text-red-700 font-serif">Location</p><br>
            <select id="location" v-model="Location" class="h-8 w-30 bg-neutral-300 active:bg-neutral-500 focus:bg-neutral-500 rounded shadow ">
                <option>Sydney</option>
                <option>Melbourne</option>
                <option>Canberra</option>
                <option>Brisbane</option>
              
            </select><br><br>
            
           
           
           
            
            <p class="text-2xl text-red-700 font-serif">Photos</p> <br> <br>
            
            <input type="file" v-on="Pic1" @change="handleChange" class="file:bg-neutral-800 file:hover:bg-neutral-900 file:active:bg-neutral-800 file:text-red-700 file:hover:text-neutral-400 file:hover:scale-105 file:text-lg file:w-36 file:p-1 file:rounded-xl file:shadow file:cursor-pointer inline-block file:transition ease-in-out duration-300 drop-shadow-2xl"><br> <br>
            <div class="error">{{ fileError }}</div>
            </div>                
            <button class="bg-neutral-800 hover:bg-neutral-900 active:bg-neutral-800 hover:scale-105 text-red-700 hover:text-neutral-400 text-xl w-64 p-4 rounded-xl shadow cursor-pointer inline-block m-10 transition ease-in-out duration-300">Update your Profile</button>
            <br><br><br></form>
            
  

  

<br><br>
</div>

  <div v-else>
      <div class="spin"></div>
     </div>
            </template>

I don’t have a store in Javascript for this yet as I said I’m a little unsure and to be honest a bit confused about what to do the user from getUser is just this

import { ref } from 'vue'
import { projectAuth } from '../firebase/config'

// refs
const user = ref(projectAuth.currentUser)

// auth changes
projectAuth.onAuthStateChanged(_user => {
  console.log('User state change. Current user is:', _user)
  user.value = _user
});

const getUser = () => {
  return { user } 
}

export default getUser

Main.js for counter

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedState from "pinia-plugin-persistedstate"
const pinia = createPinia()
pinia.use(piniaPluginPersistedState)

createApp(App).use(pinia).mount('#app')

Main.js for database user update

import { createApp } from 'vue'
import app from './App.vue'
import './style/index.css'
import router from '../src/router/index'
import { createPinia } from 'pinia'
import InstantSearch from 'vue-instantsearch/vue3/es';




createApp(app).use(router).use(createPinia()).use(InstantSearch).mount('#app')

I know thats a lot to read through and I’m sorry but as I said I’m just really confused about how to do it and how to make the profile page then get that userId from the store when it needs to as well as setting the whole thing up, if anyone could show me how or leave some links of examples in documentation that show you how to store a userId in pinia and then retrieve it that would be great thanks.

Adding content from API response to new image uploads

I’m trying to use the Astica API to get content for my new attachment uploads. While I have no problem using the API outside WordPress, I can’t seem to get it working inside WordPress.

Intend:

  1. Trigger function when a new attachment image is uploaded
  2. Send $image_url to the API
  3. Extract “caption > text” from the response
  4. Add the text to the post_content field.

Astica documentation

The function:

function cwpai_add_content_to_new_attachment( $attachment_id ) {
    // Get the attachment post object
    $attachment = get_post( $attachment_id );
    $image_url = wp_get_attachment_url( $attachment_id );
    
    // Make sure the attachment is an image
    if ( 'image' === substr( $attachment->post_mime_type, 0, 5 ) ) {
        // Get the current content of the attachment
        $content = $attachment->post_content;
        
        // Add image URL to the caption
        $new_content = $content ? "{$content}<br>{$image_url}" : $image_url;
        
        // Update the attachment post with the new content
       
        
        //Add Astica API script
        wp_enqueue_script( 'asticaAPI', 'https://www.astica.org/endpoint/ml/javascript/2023-04-10/astica.core.js' );
        
        //Add custom script
        wp_add_inline_script( 'asticaAPI', '
            function your_astica_CallBack(data) {   
                if(typeof data.error != "undefined") { alert(data.error); }         
                console.log(data); //view all data
                //Update the attachment post with the Astica response
                wp_update_post( array(
                    "ID" => '.$attachment_id.',
                    "post_content" => json_encode(data)
                ) );
            }
            asticaAPI_start("KEY");

            asticaVision(
                "2.0_full", //modelVersion: 1.0_full, 2.0_full
                "'.$image_url.'", //Input Image
                "description, tags,", //or "all"
                your_astica_CallBack, //Your Custom Callback function
            ); 
           
        ' );
    }
}
add_action( 'add_attachment', 'cwpai_add_content_to_new_attachment' )

Testing inside and outside WordPress, tried with rest API as-well without no luck. Also tried to load it with jQuery and no conflict. Can’t seem to figure it out.

I’m trying to find prime numbers; what’s wrong with my code?

let check_prime = 2
let end = 15
let counter = 2

while (check_prime <= end) {

    if (check_prime % counter == 0 && check_prime !== counter) {
    
    check_prime == (check_prime / counter);

    } else if (check_prime % counter == 0 && check_prime == counter) {
    console.log(check_prime)
    
    } else if (check_prime % counter !== 0) {
        for (new_counter = counter; new_counter <= check_prime; new_counter++) {

            if (check_prime % new_counter == 0) {
            console.log(new_counter)

            } else {
            continue
            }
        }
    }
check_prime++
}

Run >
2
3
5
7
3
9
11
13
3
5
15

I want to eliminate the 9, extra 3, and 15, using only for and while loops, and if statements.

Angular 15 Google Maps updating marker positions in real time

Using @angular/google-maps to create a real time map of public transport using transport for NSW openData.

I can successfully create the initial map, and put markers onto the map (in this example ferry locations) but updating the array of markers does not update the marker positions on the map.

It DOES, however, update data in the view when I output to text via an *ngFor loop in the component.

My question: how to update the marker positions in the Angular Google Map when the array of markers updates?

Angular 15 code:

livedata-map-content.component.html

<div class="live-transport-map">
    <div *ngIf="apiLoaded" class="google-maps-container">
        <google-map width="100%" height="100%" [options]="options">
              <map-marker  *ngFor="let marker of markers"
              [position]="marker.position"
              [label]="marker.label"
              [title]="marker.title"
              [options]="marker.options">
          </map-marker>
            
  <span *ngFor="let marker of markers">NAME:  {{marker.title}} LAT: {{marker.position.lat}} LNG: {{marker.position.lng}}!!!! </span>
        </google-map>
    </div>
</div>

livedata-map-content.component.ts

import { ChangeDetectorRef, Component, AfterViewInit } from '@angular/core';
import { MapService} from '../../../services/map.service';

@Component({
  selector: 'app-livedata-map-content',
  templateUrl: './livedata-map-content.component.html',
  styleUrls: ['./livedata-map-content.component.scss']
})
export class LivedataMapContentComponent implements AfterViewInit {
  
  public apiLoaded: any = false;
  public markers: Array<any> = [];
  public period = 10000;
  public iconStr = "http://maps.google.com/mapfiles/ms/icons/green-dot.png";

  public options: google.maps.MapOptions = {
    center: {lat: -33.853759, lng: 151.212803}, // Sydney Harbour center
    zoom: 14,
  };

  constructor(
      private mapService: MapService
    ) { }

  ngAfterViewInit(): void {
    
    // Load the maps API after view is init
    this.mapService.loadGoogleMapsAPI().subscribe(data => {
      
      this.apiLoaded = data;

      if(this.apiLoaded === true) {
        // Once it's loaded start getting live data
        setInterval(this.updateMarkers, this.period);
      }
    });

    // Initial marker setup on map
    this.mapService.getLivePositionData('ferry').subscribe(positionData => {

      let transportEntitiesArray = positionData.data.entity;

      transportEntitiesArray.forEach((transportEntity: any) => {

        this.markers.push({
          tripId: transportEntity.vehicle.trip.tripId,
          position: {
            lat: transportEntity.vehicle.position.latitude,
            lng: transportEntity.vehicle.position.longitude,
          },
          title: transportEntity.vehicle.vehicle.id + 'n' + transportEntity.vehicle.vehicle.label,
          options: {
            icon: this.iconStr,
          }
        });
      });

      this.cd.detectChanges();
    });
  }
    
  updateMarkers = () => {

    this.mapService.getLivePositionData('ferry').subscribe(positionData => {

      positionData.data.entity.forEach(positionDataItem => {
        
        this.markers.forEach(marker => {
          // Only update markers with new positions
          if(marker.tripId === positionDataItem.vehicle.trip.tripId && (marker.position.lat !== positionDataItem.vehicle.position.latitude || marker.position.lng !== positionDataItem.vehicle.position.longitude)){
            marker.position.lat = positionDataItem.vehicle.position.latitude;
            marker.position.lng = positionDataItem.vehicle.position.longitude;
          }
        });
      });

      this.cd.detectChanges();

    });
  }
}

map.service.ts

...

  public loadGoogleMapsAPI = () => {

    const mapsAPIURL = `https://maps.googleapis.com/maps/api/js?key=${environment.tempGoogleMapsID}`
    console.log('mapsAPIURL ',mapsAPIURL);

    return this.http.jsonp<any>(mapsAPIURL, 'callback').pipe(
      map((data) => {
        console.log('DATA ',data);
        return true}),
      catchError((error) => {
        console.log('error ',error);
        return of(false)}),
    );

  }

...

  getLivePositionData = (transportMode: any) => {

    const getLivePositionDataObject = {
      transportMode: transportMode
    }
    
    const getLivePositionDataDataURL = this.openDataAPI + 'positiondata';

    return this.http.post<any>(getLivePositionDataDataURL, getLivePositionDataObject);
  }
...

This draws the map and populates the array as expected, but does not update marker positions on the map.

IMAGE: the Angular 15 Material Google Maps with ferry position markers working

Multiple calls to api endpoints having issues with asynchronous data

I’m writing some code that will be put into a pdf files. Once these pdf files are created, they are merged into one document.

I have some code that, calls out to different api endpoints, and am having problems with data not being populated correctly. I suspect this is due to the asynchronous nature of the api calls and how the pdf is being generated.

getdata(){
    let docnos = this.cb
    
    docnos.forEach(docno => {
        this.ns=false;
        let thisvue = this;
        let url = this.$store.state.url;
        
        const params = new URLSearchParams();
        params.append('ty', 'getmailpdf');
        params.append('prikey', docno);
        
        axios({
            method:"post",
            url:url,
            data:params
        })
        .then(function(response){
            thisvue.maildata=response.data;
           
        })
        .then(function(){
            thisvue.maildata.pay=JSON.parse(thisvue.maildata.pay);
            thisvue.maildata.deductions=JSON.parse(thisvue.maildata.deductions);
            thisvue.maildata.exemptions=JSON.parse(thisvue.maildata.exemptions);
            thisvue.maildata.explanations=JSON.parse(thisvue.maildata.explanations);
        }).then(function(){
            thisvue.newTaxRate();
        }).then(function(){
           // thisvue.getaddress();
           // let thisvue = this;
            let url = thisvue.$store.state.url;
            let prikey=thisvue.maildata.companyprikey;
            
            const params = new URLSearchParams();
            params.append('ty', 'acntAddress');
            params.append('prikey' , prikey);
            
            axios({
                method:"post",
                url:url,
                data:params
            })
            .then(function(response){
                thisvue.mailaddress=response.data;
            })
            .then(function(){
                thisvue.formataddress();
            })
            .then(function(){
                thisvue.premakepdf();
            });
        });//.then(function(){thisvue.premakepdf();})
    });
    doc.save('taxes.pdf', {returnPromise:true}).then(this.donemessage());
    this.clearcb();
   
}

this.cb is data gathered from checkboxes on the front end. Then this cb data is looped through, passed as a data parameter into my api call.

thisvue.maildata.pay=JSON.parse(thisvue.maildata.pay);
thisvue.maildata.deductions=JSON.parse(thisvue.maildata.deductions);
thisvue.maildata.exemptions=JSON.parse(thisvue.maildata.exemptions);
thisvue.maildata.explanations=JSON.parse(thisvue.maildata.explanations);

These fields are not being populated correctly. In some forms, previous customer data (pay, deductions, exemptions, explanations) is being populated into the new pdf form with new name and address data being populated. While some pages are left blank.

I’m really at a loss, I’ve tried to refactor some of this code and use async/await, but still getting the same behavior. I’m not quite sure if I can accomplish what I need with this code.

Just looking for suggestions.

Does preconnecting to our own host effect loading speed?

I was reading about preconnecting scripts in order to speed up site loading. I had this question which I searched for and found nothing. Maybe because it doesn’t make any sense. Anyway, here’s the question:

Does this effect load speed?

<link rel="preconnect" href="/images/">

By /images/ I mean the images folder in the same host that the index.html file exists in.

Alternatively, I can explain like this:
Imagine example.com is the same host that hosts the index.html file which has this piece of code in its header tag:

<link rel="preconnect" href="example.com/images/">

And of course, any image in the site is in the images folder. Now, does that work?

How to model a json object with dynamic keys in typescript

Our backend is returning most string data as json object strings where each key represents a language code that may or may not exist on a particular database record. For example, it will come down as:

{
 "id": "4788fb8d-fb63-4189-a9e8-68624180852e",
 "description": "{"en":"description of co","es":"descripción de la co"}", "options": "[{}]"
}

Or:

{
    "id": "4788fb8d-fb63-4189-a9e8-68624180852e",
    "description": "{"en":"description of company"}",
    "options": [{"en":"english text"},{"en":"english text","es":"spanish text"},{"en":""}]
}
etc..

What is an appropriate way to represent this type across our whole web app so all our objects can be safely worked with? I’m sure this is probably a bit naive:

  interface StringType {
    en: string | undefined;
    es: string | undefined;
    de: string | undefined;

  }
interface Customer {
   id: string; 
   description: StringType;
   options: StringType[]; //
}

And how would I narrow the keys to only be our supported language codes, for example ‘en’ or ‘es’ or ‘de’ instead of any string?