Need Help Urgently! Program unable to update user’s new address and display in textfields

I’m trying to make a user profiles page where user can see their address and allow them to edit and save a new address (not locally!). Program is able to fetch data from backend then after using componentDidMount() method the user’s address renders only once after reload. Then I used componentDidUpdate() to keep displaying the user’s address upon reloading page but the same thing is happening. I was trying to render the values through componentdidupdate but it didn’t work because the component is mounting before there is a user provided and I don’t know how to do that. componentdidupdate causes an infinite loop of updates. I’m really stuck on this issue.

Not really sure how to get my program to update the user’s address and keep displaying it upon refresh until user wants to edit? Please help

Note: deleted addressLine2, city, state, zipCode for convenience.

Address.jsx
**

 import React, {Component} from 'react';

 import {Button} from 'react-bootstrap';

 import axios from 'axios';

 class Address extends Component {

 constructor(props) {

 super(props)

 this.state ={

  userDetails: null,

 addressLine1: '',

 updatedAt: null } }

 handleFirstAddLineChange = (event) => {

 this.setState({addressLine1: event.target.value}) }

 setUserDetails = (user) => {

 this.setState({ userDetails: user}) }

 componentDidMount(){

 const user = this.props.currentUser

 if (user){const authResponse = user.getAuthResponse();

 axios .get(`http://127.0.0.1:8085/api/users?idToken=${authResponse.id_token}`) 
 .then(res => {this.setState(res.data.addresses[0]) this.setUserDetails(res.data) }); 
 }}

 onSubmit = (event) => {event.preventDefault();

 const insertAddress = (googleUser) => {

  const addressInfo = { addresses: [{addressLine1: this.state.addressLine1 }]};

  const authResponse = googleUser.getAuthResponse();

 const idToken = authResponse.id_token;

 const user = googleUser.profileObj;

 user.addresses = addressInfo.addresses; axios.put(`http://127.0.0.1:8085/api/users? 
idToken=${idToken}`, user) .then(authResponse => this.setState({updatedAt: 
 authResponse.data.updatedAt})); };

insertAddress(this.props.currentUser) }

 componentDidUpdate(prevProps) {

if (this.props.currentUser !== prevProps.currentUser) { this.setState({ curr: 
 this.props.currentUser}); console.log("changed")}}

render() {return (<form onSubmit={this.onSubmit}>

<h1 className="main-container">Address </h1>

<div className="main-container">

<label> Address Line 1: </label>

<input className="input" type='text' value={this.state.addressLine1} onChange= 
{this.handleFirstAddLineChange}/> </div>

</div> <Button className="btn" type="submit">Save Changes</Button>

</form> );}}

export default Address;

Unable to pass argument from outer scope in Node.js file system function?

I’ve noticed that arguments are not being recognized in Node.js filesystem when wrapped with (). Can anyone explain why this is happening please? My expectation was the even when wrapped in (), it will work just like forEach() function?

const fs = require('fs');
const path = require('path');
const root = path.resolve(__dirname);

fs.readdir(root, (error, filenames) => {
   filenames.forEach( filename => {
      const filePath = path.join(root, filename);
      fs.unlink( (filePath, err) => {
         // Throws error saying 'filePath' is not defined..?
      });
   });
});

Uncaught SyntaxError: Unexpected token ‘:’

I am having error when adding this code in my webpack.config.js Uncaught SyntaxError: Unexpected token ‘:’

const webpack = require('webpack');
const dotenv = require('dotenv');

dotenv.config();

module.exports = {
  //...
  plugins: [
    // ...
    new webpack.DefinePlugin({
       'process.env': JSON.stringify(process.env)
    })
    // ...
  ]
  //...
}

app.js

'use strict';
const dotenv = require('dotenv');
const config = dotenv.config();
const {API_KEYS} =config.parsed;

....

console.log("keys ",API_KEYS)

....

How to remove extra space in template literals?

When I create template literals, I would use the trim() to remove extra space. But I noticed when I do this inside a JS function, it still creates extra tabs or white space.

  function BottlesOfBeer()  {
    
        for (i = 99; i>=1; i--) {
    
            if (i === 1) {        
                var oneBottle = "1 bottle of beer on the wall, 1 bottle of beer.n" +
                                "Take one down and pass it around, no more bottles of beer on the wall.n" +
                                "No more bottles of beer on the wall, no more bottles of beer.n" +
                                "Go to the store and buy some more, 99 bottles of beer on the wall.";        
                
                console.log(oneBottle);
            } else {
                            
                var lineOne = `
                ${i} bottles of beer on the wall, ${i} bottles of beer.
                Take one down pass it around, ${i - 1} bottles of beer on the wall.
                `.trim();
    
                console.log(lineOne);        
            }
        }
    }
    
    BottlesOfBeer();
99 bottles of beer on the wall, 99 bottles of beer.
            Take one down pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.

You can see how the first line appears normally, but the second one has all the necessary tabs.

How can add my burger.price to my Item.price to create the Total?

I am looking to have my burger.price (if there is a custom burger in the cart) to be added to the total with the item.price. Any help would be great! I am new to using vue and vuex.

<template>
<div>
  <b-button v-b-modal.modal-1>Cart({{numInCart}})</b-button>
  <b-modal id="modal-1" size="xl" title="Shopping Cart" ok-title="Checkout" cancel-title="Continue Shopping">
    <table class="table">
      <tbody>
      <!-- replace in cart with custom burger -->
      <tr v-for="(item, index) in cart" :key="item.id">
        <td>{{ item.name }}</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td>{{ item.price | dollars }}</td>
        <td>
          <button class="btn btn-sm btn-danger" @click="removeFromCart(index)">&times;</button>
        </td>
      </tr>
        <tr>
        <th>Name</th>
        <th>Bun Type</th>
        <th>Cooked Style</th>
        <th>Cheese Type</th>
        <th>Toppings</th>
      </tr>
      <tr v-for="(burger) in customBurger" :key="burger">
        <td>{{burger.name = "Custom Burger"}}</td>
        <td>{{burger.bun}}</td>
        <td>{{burger.cookedStyle}}</td>
        <td>{{burger.cheese}}</td>
        <td>{{burger.toppings}}</td>
        <td>{{burger.price | dollars }}</td>
        <td>
          <button class="btn btn-sm btn-danger" @click="removeCustomBurger(customBurger)">&times;</button>
        </td>
      </tr>
      <tr>
        <th></th>
        <th>{{ total | dollars }}</th>
        <th></th>
      </tr>
      </tbody>
    </table>
  </b-modal>
</div>
</template>

<script>
import { dollars } from '../models/filters'

export default {
  name: 'ShoppingCart',
  computed: {
    customBurger() {
      return this.$store.getters.customBurger;
    },
    inCart() { return this.$store.getters.inCart; },
    numInCart() { return this.inCart.length; },
    cart() {
      return this.$store.getters.inCart.map((cartItem) => {
        return this.$store.getters.forSale.find((forSaleItem) => {
          return cartItem === forSaleItem.invId;
        });
      });
    },
    total() {
      return this.cart.reduce((acc, cur) => acc + cur.price, 0);
    },
  },
  filters: {
    dollars,
  },
  methods: {
    removeFromCart(index) { this.$store.dispatch('removeFromCart', index); },
    removeCustomBurger(){this.$store.dispatch('removeCustomBurger');},
  },
};
</script>

I’ve been meaning to learn C# and wanted sto write something like this Javascript code. How would i go about doing it

An example of what I’m trying to do:
Adding the first and last numbers until only two digits remain:

num = 1234567:

1+7 = 8

2+6 = 8

3+5 = 8

4 remains

So the first result is: 8884. Now everything is added again:

8+8 = 16

8+4 = 12

The result is 1612. Again everything is summed up:

1+2 = 3

6+1 = 7

The result is 37 – which is also the final result.

The Javascript code:

function sum(num) {
    var numString = num.toString();
    var newString = "";
    while (numString.length > 1) {
        newString += (parseInt(numString[0]) + parseInt(numString[numString.length - 1])).toString();
        numString = numString.substring(1, numString.length - 1);
    }
    newString += numString;

    if (newString.length > 2) {
        console.log(newString)
        return sum(newString);
    }  else {
         return newString;
      }
}

How to correctly apply global scripts with Nextjs

I’m trying to apply a global fade-in animation to all components in my application. I’ve added the classname fadeIn to all the elements and set the opacity to 0 by default. I then use js to change that to 1 when the element comes into view.

Below is how I am applying this so far. It does work but there is a major issue and I’m sure it’s not the best method and firstly would love to know any better methods.

The major issue is that it only works on the first render. But if I navigate to another page and then come back, all elements are hidden with the opacity 0 and the script does not execute.

Appreciate any advice on how to either solve the current issue, or a better way to execute it.

_app.js

function MyApp({ Component, pageProps }) {

  return <Provider store={store}>
    <Layout>
      <PersistGate persistor={persistor}>
        <Component {...pageProps} />
      </PersistGate>
      <FadeIn />
    </Layout>
  </Provider>
}

export default MyApp

FadeIn component

import React, { useEffect, useState } from 'react'
import Script from 'next/script'
import ReactDOM from 'react-dom';

export default function FadeIn() {

  const myScript = (
    <Script src='/utils/scripts/appearOnScroll.js' strategy="afterInteractive" />
  )

  return ReactDOM.createPortal(myScript, document.getElementById('doc-root'));

}

appearOnScroll.js

(function () {
  const faders = document.querySelectorAll('.fade-in');
  const faderOptions = {
    threshold: 1
  };
  const appearOnScroll = new IntersectionObserver(function (
    entries,
    appearOnScroll
  ) {
    entries.forEach(entry => {
      if (!entry.isIntersecting) {
        return;
      } else {
        entry.target.classList.add('appear');
        appearOnScroll.unobserve(entry.target);
      }
    })
  }, faderOptions);

  faders.forEach(fader => {
    appearOnScroll.observer(fader);
  });
})();

how to show a Blog detail link in Angular

I want to show the Detail of a Blog in a different link in Angular. I already have a Blog file (blog.component.ts) and an Angular service where I can get all the blogs data from an API backend made with Strapi. There is one button in every single blog, which allows you to view the detail or complete Blog in a different link calling the unique ID, that is named ‘pagina.component.ts’.
For that purpose, I think I must call the ID of every single Blog.

Here is my blog.component.html, where I already have the list of my blogs:

<section class="articles">

  <article class="blue-article" *ngFor="let data of datas; index as i">
    <div class="articles-header">
      <time>{{ data.fecha }}</time>
      <span class="articles-header-tag-blue">{{ data.relevante }}</span>
      <span class="articles-header-category">
        <a href="#" class="blue" title="">{{ data.category.name }}</a>
      </span>
    </div>
    <div class="articles-content">
      <h1><a title="">{{ data.title }}</a></h1>
      <!--<img *ngIf="!data.image" class="foto" [src]="data.image.name" alt="foto">-->
      <div *ngIf="data.image">
        <img
          src="http://localhost:1337{{ data.image.url }}"
          alt="foto"
          width="100%"
        />
      </div>
      <p>
        {{ data.content }}
      </p>
      <h3>{{ data.description }}</h3>
    </div>
    <div class="articles-footer">
      <ul class="articles-footer-info">
        <li><a href="#" class="light-link" title=""><i class="pe-7s-comment"></i> 7 Respuestas</a>
        </li>
        <li><a href="#" class="light-link" title=""><i class="pe-7s-like"></i> 1221</a></li>
      </ul>

      <a [routerLink]="['./pagina',i]" class="btn">Leer más</a>

    </div>
  </article>
</section>

Here is my blog.component.ts file


import { Component, OnInit } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { StrapiService } from '../../../services/strapi.service';

import { Router } from '@angular/router';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {

  datas:any=[];
  errores:string="";

  constructor(
    public strapiserv:StrapiService,
    private router: Router
  ) { }

  ngOnInit(): void {

    this.title.setTitle('Blog');

    this.strapiserv.getData().subscribe(res=>{

        this.datas= res as string[];

    }, error =>{
      console.log(error);
        if(error.status == 0){
            this.errores="Código del error: "+error.status+" n Ha ocurrido un error del lado del cliente o un error de red.";
        }else{
            this.errores="Código del error: "+error.status+"nn"+error.statusText;
        }
    })

  }


}

Here is my Angular service named ‘strapi.service.ts’


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class StrapiService {

  REST_API: string ='http://localhost:1337/articles';
  //https://strapi-dot-gmal-api-313723.uc.r.appspot.com/
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(private httpClient: HttpClient) { }


  getData():Observable<any>{
    console.log();
    let API=this.REST_API;
    return this.httpClient.get(API,{headers:this.httpHeaders}) .pipe(
      map((data:any) => { 
      
        return data;
      }), catchError( error => {
        return throwError(error);
      })
    )
    
  }

  /*getItem( idx:number ){
    return this.data[idx];
  }*/
 
 
}

And Here is my pagina.component.ts file where I want to show the complete detailed Blog


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';

import { StrapiService } from '../../../../services/strapi.service';

@Component({
  selector: 'app-pagina',
  templateUrl: './pagina.component.html',
  styleUrls: ['./pagina.component.scss']
})
export class PaginaComponent implements OnInit {

  data:any = {};


  constructor( private activatedRoute: ActivatedRoute,
           private router: Router,
           public strapiserv:StrapiService
    ){ 

    this.activatedRoute.params.subscribe( params => {
      this.data = this.strapiserv.getData( params['id'] );
    });

  }

  ngOnInit(): void {
  }

}
 

My routes are:

const routes: Routes = [
    { path: 'blog', component: BlogComponent },
    { path: 'pagina/:id', component: PaginaComponent },
];

Is there an another way to get date instead of getting it from user’s device

I want to make an application that will only open at a specific date. I use new date() to do that, but new date() get time from the user’s device and the the user can open it by changing the time on its own device.

Example:

  let setdate = new Date('2021-12-10')
   let currentdate = new Date()
   console.log(setdate)
   if(setdate.getDate() == currentdate.getDate()){
    document.getElementById("result").style.display = 'revert'
   }
<div id=result style="display:none">Open now!!!</div>

If I don’t do anything with the time of my device, it won’t do anything. But if I change the date on my device to the specific date, then the area could open.

Could anyone suggests me a better way that could prevent this situation or is there an another way to get date instead of getting it from user’s device

Thanks for any responds!!!

Colores :root dinamicos desde sass al cargar pagina

Necesito de su ayuda para resolver la siguiente inquietud
quisiera cambiar los colores del :root del css desde los datos cargados de mi servidor (DB).Tengo una sass con los estilos `
$color-primary: #56b4d8;

$theme-colors: (
primary: $color-primary,
secondary: #56b4d8,
success: #0ebd65,
info: #198ae3,
warning: #fed713,
danger: #e64b4b,
light: #f8f9fa,
dark: #1a1a1a);`

mi requerimiento es necesito cambiar estos colores desde el servidor al cargar la imagen, quizas exista alguna manera de pasarle datos a las varibales de sass $

الجمال واللياقة البدنية

الجمال واللياقة البدنية

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

Javascript Object Structure Without Key

I am trying to generate an object structure like so:

{nums: {500: 0, 600: 0}}

I have a function that loops and returns numbers as shown in object: 500 & 600. However,

No matter what I try to create an object structure like the above, it does not work.

This is what I have an array of object as follows :

 const scores = [ {score: 500}, {variant_id: 600} ]

How can I loop through the scores array of object and get a structure like:
Number 0 in this example as a value that will be applicable to all scores.

 {nums: {500: 0, 600: 0}}

What I have done is:

  let filteredScores = [];
  for (let i = 0; i < scores.length; i++) {
            const element = scores[i];
            filteredScores.push(element);
  }

However, this does not lead to the desired results.

Any insights or input is much appreciated!

Convert this JavaScript to Jquery [closed]

Here is what I need to convert. Any help would be greatly appreciated! TIA!

document.getElementById("color1").addEventListener("click",
            function() {
                document.getElementById("JS1").style.backgroundColor = 
                    document.getElementById("color1").value;
            });

Here is what I’ve tried so far.

$('#color1').on('click',function(){
            $('#JS1').css('background-color',$('#color1').val());
                });
            

Cant enable button java script [closed]

I want to make an input bar and search button where the search button is only enabled if there is any character in the input bar. So the button is disabled but when I type in the input, it doesn’t get enabled as it should.

    <!DOCTYPE html>
        <html lang="en">
        <head>
           <meta charset="UTF-8">
           <meta http-equiv="X-UA-Compatible" content="IE=edge">
           <meta name="viewport" content="width=device-width, initial-scale=1.0">
           <title>Document</title>
           <script>
              document.addEventListener('DOMContentLoaded', function(){
                 // by default search button is disabbled
                 document.querySelector('#search-button').disabled=true;
                 
                 documnet.querySelector('#search-bar').onkeyup = () => {
                    document.querySelector('#search-button').disabled = false;
                 }
              })
           </script>
        </head>
        <body>
           <form>
              <input id='search-bar'>
              <button id='search-button'>submit</button>
           </form>
        
        </body>
        </html>