Add a scrolling transition between components svelte

I have this svelte component that renders a dynamic component, what I want to do is: when the “this” on svelte:component changes I want to run a “scrolling-like” transition, so the current pages moves to the top of the screen and the next page comes from the bottom at the same time, so I came up with the fly animation reversed on in and out, but there is a problem: the first in transition succeeds, the first page does come from the bottom of the page, but when the component changes, only the out animation displays, the current page goes to the top of the screen, but the next in animation doesnt display, the next component just appears after a short time, it seems like the out animation is conflicting with the next in animation because they run at the same time, but that’s the behavior I want, how to achieve this ? Here is the code for my component:

<script lang="ts">
  import type { SvelteComponent } from 'svelte';
  import { fly } from 'svelte/transition';
  import Layout from './lib/components/layout.svelte';
  import { page } from './lib/stores';
  import { tick } from 'svelte';

  let pages = Object.entries(import.meta.glob('./lib/pages/*.svelte')).map(
    async ([path, page]) => ({
      path,
      component: (await page() as any).default as typeof SvelteComponent,
    })
  );

  page.subscribe((_) => pages = pages);
</script>

<Layout>
  {#await Promise.all(pages) then pages}
    {#each pages as { path, component }}
      {#if path === $page.path}
        <div class="page"
          in:fly={{ y: window.innerHeight, duration: 1000 }}
          out:fly={{ y: -window.innerHeight, duration: 1000 }}>
          <div id="header">
            <h1>{$page.title}</h1>
          </div>
          <div id="content">
            <svelte:component this={component} />
          </div>
        </div>
      {/if}
    {/each}
  {/await}
</Layout>

<style>
  .page {
    display: grid;
    grid-template-rows: 1.5fr 8.5fr;
    height: 100%;
    width: 100%;
  }

  #header {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-left: 20%;
    margin-right: 20%;
    border-bottom: 3px solid rgb(29, 215, 103);
  }

  #content {
    margin: 5%;
    font-size: x-large;
  }
</style>

Image overflow | HTML | CSS

I have an image gallery where each image is in the form of vertical columns that have some zooming effects when hovered over it. When clicked on, each image should pop for full screen with a caption.

The issue is, with the images of width less than the display device, it’s working fine. However for few images (x-pan images), the images keep overflowing horizontally, even after using overflow: hidden.

Can someone look into this code and help me understand where its going wrong.

In below code, the first 2 images in the stack are the ones that are overflowing. The rest are all displaying fine.

I tired overflow: hidden, set max-width: 100% or max-width: 100vw.
Nothing worked.

PS: The code might be little messy and there may be lot of redundant or unnecessary tags, please feel free to correct!

var today = new Date();
var bg = document.getElementById("dark-mode");
var words = document.getElementsByClassName("dark-mode-word");

if (today.getHours() > 17 || today.getHours() < 7) {
  console.log("Night time, Dark mode");
  bg.style.backgroundColor = "#34495E";
  for (let word of words) {
    word.style.color = "white";
  }
}

//-----------------------------Image gallery fn's ----------------------
var imagesContainer = document.querySelector('.scrollable-images');
var images = document.querySelectorAll('.scrollable-images img');
var modal = document.getElementById('myModal');
var modalImg = document.getElementById('modalImage');
var captionText = document.getElementById('caption');

var scrollPosition = 0;
var imageIndex = 0;

function openModal(src, alt) {
  modal.style.display = 'block';
  modalImg.src = src;
  captionText.innerHTML = alt;
}

function closeModal() {
  modal.style.display = 'none';
}

images.forEach(function(img, index) {
  img.onload = function() {
    updateImagePositions();
  };

  img.onclick = function() {
    openModal(this.src, this.alt);
    imageIndex = index;
  };
});

imagesContainer.addEventListener('wheel', function(e) {
  scrollPosition += e.deltaY;
  scrollPosition = Math.min(imagesContainer.scrollWidth - imagesContainer.clientWidth, Math.max(0, scrollPosition));
  imagesContainer.scrollLeft = scrollPosition;
  imageIndex = Math.round(scrollPosition / images[0].offsetWidth);
  e.preventDefault();
});

imagesContainer.addEventListener('mousewheel', function(e) {
  scrollPosition += e.deltaY;
  scrollPosition = Math.min(imagesContainer.scrollWidth - imagesContainer.clientWidth, Math.max(0, scrollPosition));
  imagesContainer.scrollLeft = scrollPosition;
  imageIndex = Math.round(scrollPosition / images[0].offsetWidth);
  e.preventDefault();
});

window.addEventListener('resize', updateImagePositions);

function updateImagePositions() {
  const centerIndex = Math.floor(images.length / 2);
  scrollPosition = centerIndex * images[0].offsetWidth - imagesContainer.offsetWidth / 2;
  scrollPosition = Math.min(imagesContainer.scrollWidth - imagesContainer.clientWidth, Math.max(0, scrollPosition));
  imagesContainer.scrollLeft = scrollPosition;
  imageIndex = centerIndex;
}
updateImagePositions();

const dockContainer = document.querySelector('.scrollable-images');
const dockItems = document.querySelectorAll('.scrollable-images img');
const defaultItemScale = 1;
const hoverItemScale = 1.3;
const defaultMargin = "5px";
const expandMargin = "10px";

const updateDockItems = (hoveredItemIndex) => {
  dockItems.forEach((item, index) => {
    let scale = defaultItemScale;
    let margin = defaultMargin;

    if (index === hoveredItemIndex) {
      scale = hoverItemScale;
      margin = expandMargin;
    }

    item.style.transform = `scale(${scale})`;
    item.style.margin = `0 ${margin}`;
  });
};
dockItems.forEach((item, index) => {
  item.addEventListener("mouseenter", () => {
    updateDockItems(index);
  });
});
dockContainer.addEventListener("mouseleave", () => {
  resetDockItems();
});
const resetDockItems = () => {
  dockItems.forEach((item) => {
    item.style.transform = "";
    item.style.margin = "";
  });
};
document.addEventListener('keydown', function(event) {
  if (event.keyCode === 27) {
    closeModal();
  }
});
html {
  scroll-behavior: smooth;
}

html::-webkit-scrollbar {
  display: none;
  /* for Chrome, Safari, and Opera */
}

body {
  background-color: #fafafa;
  font-family: 'Special Elite', cursive;
}

h1 {
  font-size: 55px;
}

.gallery {
  margin-top: 5%;
  padding-top: 60px;
  text-align: center;
}

.centered-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 50px;
  margin-bottom: 100px;
  margin-left: 10px;
  margin-right: 10px;
}

.image-container {
  width: 100%;
  text-align: center;
}

#myModal {
  z-index: 101;
}

.scrollable-images {
  display: flex;
  justify-content: center;
  overflow-x: auto;
  gap: 10px;
  transition: 700ms cubic-bezier(0.075, 0.02, 0.165, 1);
  transform-origin: center;
}

.scrollable-images::-webkit-scrollbar {
  display: none;
}

.scrollable-images img {
  width: 80px;
  max-width: 100%;
  height: 300px;
  object-fit: cover;
  cursor: pointer;
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
  filter: grayscale(100%);
}

.scrollable-images img:hover {
  filter: grayscale(0%);
}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
  background-color: rgba(0, 0, 0, 0.9);
}

.modal-content {
  margin: auto;
  display: block;
  width: auto;
  height: auto;
}

#caption {
  margin: auto;
  display: block;
  font-family: 'Hubballi', sans-serif;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

.modal-content,
#caption {
  animation-name: zoom;
  animation-duration: 0.6s;
}

.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

@keyframes zoom {
  from {
    transform: scale(0.1);
  }
  to {
    transform: scale(1);
  }
}

@keyframes typing {
  from {
    width: 0
  }
  to {
    width: 100%
  }
}

@media screen and (max-width:768px) {
  .modal-content {
    margin-top: 20%;
    width: 100%;
  }
}

@media (min-width: 769px) {
  .modal-content {
    max-width: none;
    max-height: 100%;
    width: auto;
  }
}
<div class="container-fluid gallery" id="gallery">
  <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6 dark-mode-word">
      <h1>Through the Lens</h1>
    </div>
    <div class="col-md-3"></div>
  </div>
</div>
<div class="centered-container">
  <div class="image-container">
    <div class="scrollable-images">
      <img src="https://images.squarespace-cdn.com/content/v1/58f8da6cd1758e3d9a000926/1590933405095-CS76QNG50PO0P07SE711/Hasselblad+Xpan+Cinestill+Portra-7.jpg" alt="Caption here">
      <img src="https://shreyas-phaniraj-ebcf30.netlify.app/gallery/night_city.jpg" alt="Caption here">
      <img src="https://shreyas-phaniraj-ebcf30.netlify.app/gallery/Kollam_beach_1.webp" alt="Caption here">
      <img src="https://images.squarespace-cdn.com/content/v1/58f8da6cd1758e3d9a000926/1590933647894-1QSII5LVB2ACDVC28FVK/Hasselblad+Xpan+Cinestill+Portra-42.jpg?format=1500w" alt="Caption here">
      <img src="https://shreyas-phaniraj-ebcf30.netlify.app/gallery/Clouds_river_atirapalley.webp" alt="Caption here">
      <img src="https://images.squarespace-cdn.com/content/v1/58f8da6cd1758e3d9a000926/1590933228672-9I1VDOZ5Z6E4TMOVIDQO/Hasselblad+Xpan+Cinestill+Portra-2.jpg?format=1500w" alt="Caption here">
    </div>
  </div>
</div>

<div id="myModal" class="modal">
  <span class="close" onclick="closeModal()">&times;</span>
  <img class="modal-content" id="modalImage">
  <div id="caption"></div>
</div>

Is there a more efficient way to call multiple apis using graphql and react

I am using GraphQL and react on my client side project but I am not using a state management system like Redux

I have organised my api calls into custom hook files like below

  const [getSomeData, { data: getSomeDataData, loading: getSomeDataLoading, error: getSomeDataError }] = useLazyQuery(
    GET_SOME_DATA2,
    {
      client: dataClient,
      fetchPolicy: "cache-and-network",
      nextFetchPolicy: "cache-first",
    }
  );
  return {
    getSomeData,
    getSomeDataData,
    getSomeDataLoading,
    getSomeDataError,
  };
}

export default function useGetSomeData() {
  const [getSomeData2, { data: getSomeData2, loading: getSomeDataLoading2, error: getSomeDataError2 }] = useLazyQuery(
    GET_SOME_DATA,
    {
      client: dataClient,
      fetchPolicy: "cache-and-network",
      nextFetchPolicy: "cache-first",
    }
  );
  return {
    getSomeData2,
    getSomeDataData2,
    getSomeDataLoading2,
    getSomeDataError2,
  };
}

when importing my data to the component im finding myself using a lot of useEffects in order to keep the api calls / state updated like so

useEffect(()=>{
getSomeData({
variables})
},[])
useEffect(()=>{
getSomeData2({
variables})
},[])

 useEffect(()=>{

if( getSomeDataData2 && !getSomeDataLoading2 && !getSomeDataError2){
setState(getSomeDataData2?.data)
}
},[getSomeDataData2 ,getSomeDataLoading2 ,getSomeDataError2])

useEffect(()=>{

if( getSomeDataData && !getSomeDataLoading && !getSomeDataError){
setState(getSomeDataData2?.data)
}
},[getSomeDataData ,getSomeDataLoading ,getSomeDataError])

i think im over using use effects and i want to limit the number of rerenders per component

does pulling each use effect into its own function and then calling each function in the one useEffect a better practice

getSomeData2({
variables})
}

const fetchData2 = () => {
getSomeData2({
variables})
}

useEffect(()=>{
fetchData()
fetchData2()
},[])

 useEffect(()=>{

if( getSomeDataData2 && !getSomeDataLoading2 && !getSomeDataError2){
setState(getSomeDataData2?.data)
}
},[getSomeDataData2 ,getSomeDataLoading2 ,getSomeDataError2])

useEffect(()=>{

if( getSomeDataData && !getSomeDataLoading && !getSomeDataError){
setState(getSomeDataData2?.data)
}
},[getSomeDataData ,getSomeDataLoading ,getSomeDataError])

Generate dynamic column using server side code response

This is my Server side code and its response

$response = array(
    "draw" => intval($draw),
    "iTotalRecords" => $records,
    "iTotalDisplayRecords" => $totalRecords,
    "aaData" => $data_arr,
    "dayFirstHeadingdynamic" => $monthallDates
);

return response()->json($response);

{
    "draw": 1,
    "iTotalRecords": 11,
    "iTotalDisplayRecords": 11,
    "aaData": [
    {
    "Recruiter": "person name",
    "Day0": 0,
    "Day1": 0,
    "Day2": 0,
    "Day3": 0,
    "Day4": 0,
    "Day5": 0,
    "Day6": 0,
    "Day7": 0,
    "Day8": 0,
    "Day9": 0,
    "Day10": 0,
    "Day11": 0,
    "Day12": 0,
    "Day13": 0,
    "Day14": 0,
    "Day15": 0,
    "Day16": 0,
    "Day17": 0,
    "Day18": 0,
    "Day19": 0,
    "Day20": 0,
    "Day21": 0,
    "Day22": 0,
    "Day23": 0,
    "Day24": 0,
    "Day25": 0,
    "Day26": 0,
    "Day27": 0,
    "Day28": 0,
    "Day29": 0,
    "Day30": 0,
    "Total": 0
    }
    ],
    "dayFirstHeadingdynamic": [
        "2023-12-01",
        "2023-12-02",
        "2023-12-03",
        "2023-12-04",
        "2023-12-05",
        "2023-12-06",
        "2023-12-07",
        "2023-12-08",
        "2023-12-09",
        "2023-12-10",
        "2023-12-11",
        "2023-12-12",
        "2023-12-13",
        "2023-12-14",
        "2023-12-15",
        "2023-12-16",
        "2023-12-17",
        "2023-12-18",
        "2023-12-19",
        "2023-12-20",
        "2023-12-21",
        "2023-12-22",
        "2023-12-23",
        "2023-12-24",
        "2023-12-25",
        "2023-12-26",
        "2023-12-27",
        "2023-12-28",
        "2023-12-29",
        "2023-12-30",
        "2023-12-31"
    ]
}

I want to generate dynamic column by looping “dayFirstHeadingdynamic” => $monthallDates from server side code $response array, because dates in “dayFirstHeadingdynamic” response can be increase and decrease, below is my client side code

$(document).ready(function(){
    var month_year = "";
    var duration_date_from = "";
    var duration_date_to = "";
    var sortByRecruiterIncharge = [];
    var customSearch = "";
    
    rolesList = $('#day_qualifiedleads_report').DataTable({
        "deferRender": true,
        "processing": true,
        "serverSide": true,
        "searching": false,
        "ordering" : false,
        lengthMenu: [20, 50, 100, 200, 500],
        ajax: {
            url: "<?php echo url('qualified-leads-reporting-dayWise-Filter');?>",
            data: function (data) {
                $('input[type="checkbox"]').click(function(){
                    var status = $(this).val();
                    var title = $(this).closest('label').attr('title');

                    if(title === "sortByRecruiterIncharge"){
                        if(status === "All"){
                            if($(this).prop('checked')){
                                $('.btn-group.show input[type="checkbox"]').prop('checked', true);
                                $('.btn-group.show input[type="checkbox"]').each(function(){
                                    sortByRecruiterIncharge.push($(this).val());
                                });
                            }else{
                                $('.btn-group.show input[type="checkbox"]').prop('checked', false);
                                sortByRecruiterIncharge = [];
                            }
                        }else{
                            if($(this).prop('checked')){
                                sortByRecruiterIncharge.push(status);
                            }else{
                                sortByRecruiterIncharge = sortByRecruiterIncharge.filter(function (value) {
                                    return value !== status;
                                });
                            }
                            sortByRecruiterIncharge = removeDuplicatesFromArray(sortByRecruiterIncharge);
                        }
                    }
                });

                function removeDuplicatesFromArray(array){
                    return array.filter((value, index) => array.indexOf(value) === index);
                }
                
                data.month_yearoption = month_year;
                data.durationdatefrom = duration_date_from;
                data.durationdateto = duration_date_to;
                data.sortByRecruiterIncharge = sortByRecruiterIncharge;
                data.customSearch = customSearch;
            }
        },
        "columns": [
            { data: 'Recruiter' },
            <?php for($i=0; $i<sizeof($monthallDates); $i++){?>
            { data: '<?php echo "Day$i";?>' },
            <?php } ?>
            { data: 'Total' }
        ],
        select: {
            style: 'multi'
        },
    });

    $('#month_year').change(function () {
        month_year = $(this).val();
        reloadTable('month_year',month_year)
    });

    $('#duration_date_from').change(function () {
        duration_date_from = $(this).val();
        reloadTable('duration_date_from',duration_date_from)
    });
    
    $('#duration_date_to').change(function () {
        duration_date_to = $(this).val();
        reloadTable('duration_date_to',duration_date_to)
    });

    $('#sortByRecruiterIncharge').change(function () {
        rolesList.draw();
        reloadTable('sortByRecruiterIncharge',sortByRecruiterIncharge)
    });

    $('#customSearch').keyup(function () {
        customSearch = $(this).val();
        reloadTable('customSearch',customSearch)
    });

    function reloadTable(field_name, value){
        var month_year = $("#month_year").val();

        var dateArray = month_year.split('-');
        var year = dateArray[0];
        var month = dateArray[1];

        var durationdateTo = $("#duration_date_to").val();
        var durationdateFrom = $("#duration_date_from").val();
        
        $('#day_qualifiedleads_report').DataTable().clear();
        $('#day_qualifiedleads_report').DataTable().destroy();
        
        $('#day_qualifiedleads_report').DataTable({
            "deferRender": true,
            "processing": true,
            "serverSide": true,
            "searching": false,
            "ordering" : false,
            lengthMenu: [20, 50, 100, 200, 500],
            "columnDefs": [
                { "orderable": false, "targets": "_all" }
            ],
            ajax: {
                url: "<?php echo url('qualified-leads-reporting-dayWise-Filter');?>",
                data: function (data) {
                    data.month_yearoption = month_year;
                    data.durationdatefrom = duration_date_from;
                    data.durationdateto = duration_date_to;
                    data.sortByRecruiterIncharge = sortByRecruiterIncharge;
                    data.customSearch = customSearch;
                }
            },
            Instead of this columns code, I want to generate column dynamically as per response of server side code.
            "columns": [
                { data: 'Recruiter' },
                <?php for($i=0; $i<sizeof($monthallDates); $i++){?>
                { data: '<?php echo "Day$i";?>' },
                <?php } ?>
                { data: 'Total' }
            ],
            "initComplete": function (settings, json) {
                if (month_year != null || durationdateTo!='' || durationdateFrom!='') {
                    $("#tablerowdaywise2").empty();
                    var dayFirstHeadingdynamic = json.dayFirstHeadingdynamic;
                                            
                    $("#tablerowdaywise2").append("<th>Recruiters</th>");
                    for (var i = 0; i < dayFirstHeadingdynamic.length; i++) {
                        $("#tablerowdaywise2").append("<th>" + dayFirstHeadingdynamic[i] + "</th>");
                    }
                    $("#tablerowdaywise2").append("<th>Total</th>");
                }
            },
            select: {
                style: 'multi'
            },
        });
    }
});

Since 3 days I am stuck up with this issue, In client side code I have tried so many solution to get desired result but unable, In function reloadTable(field_name, value) I have tried to change

"columns": [
    { data: 'Recruiter' },
    <?php for($i=0; $i<sizeof($monthallDates); $i++){?>
    { data: '<?php echo "Day$i";?>' },
    <?php } ?>
    { data: 'Total' }
],

to this, but unable to get desires result

"columns": (function (json) {
    var dynamicColumns = [];
    var columnsFromServer = json.dayFirstHeadingdynamic;
    for (var i = 0; i < columnsFromServer.length; i++) {
        dynamicColumns.push({ data: columnsFromServer[i] });
    }
    return dynamicColumns;
})(),

I have tried below code also, but still unable to get desired result.

"columns": function (settings, json) {
    var dayFirstHeadingdynamic = json.dayFirstHeadingdynamic;
    var dynamicColumns = [
        { data: 'Recruiter' },
    ];    
    for (var i = 0; i < dayFirstHeadingdynamic.length; i++) {
        dynamicColumns.push({ data: '<?php echo "Day$i";?>' });
    }  
    dynamicColumns.push({ data: 'Total' });
    return dynamicColumns;
},

How to update expo app block after getting data from database?

I’m trying to connect database with my expo app. I used react redux to get data from database and when data is loaded i need to update my furniture block with data i got. But when i’m getting data nothing happens. What i’m doing wrong?

const dispatch = useDispatch()
const furniture = useSelector((state) => state.furniture.furniture)

const isFurnitureLoading = furniture.status == 'loading'

React.useEffect(() => {
  dispatch(fetchFurniture())
 }, [])
{isFurnitureLoading ? null : furniture.items.map((obj, index) =>
 {
  <FurnitureBox
  name = {obj.name}
  price = {obj.price}
  imgsrc = {require("../assets/img-main-page/computer_table.png")}
  navigation={navigation} 
  navigation_page="Product_page_1"
 />
 } 
)}

I haven’t found any information about this problem.

What order to use for serverless.yml plugins?

What should be the correct order of arranging these plugins for serverless.yml? I am using serverless to deploy my exoress app to AWS lambda

Plugins:

  • serverless-plugin-common-excludes
  • serverless-plugin-include-dependencies
  • serverless-esbuild
  • serverless-plugin-package-size
  • serverless-bundle
  • serverless-offline
  • serverless-dynamodb-local
  • serverless-dotenv-plugin

I have found order for serverless-plugin-common-excludes and
serverless-plugin-include-dependencies plugins on serverless website.

Firebase Auth token to test it in Postman in Javascript and & Angualar

I have written the code for firebase auth. I want the firebase auth token to test it in my Postman. but I don’t know how to get it.
Here is the code:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { Router } from '@angular/router';
import { GoogleAuthProvider, user }  from "@angular/fire/auth";
import { getIdToken } from 'firebase/auth';
import { User } from 'firebase/auth';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor( private fireAuth: AngularFireAuth, private router: Router ) { }

  //login Method
  login(email: string, password: string) {
    var credientials = this.fireAuth.signInWithEmailAndPassword(email,password).then( () => {
      localStorage.setItem('token', 'true');


      //i think this is the funciton which should accept the arguments for the token but don't know how to made this possibe.
      // getIdToken();

      this.router.navigate(['dashboard'])
    }, err => {
      alert('Something went wrong');
      this.router.navigate(['/login']);
    })
  }

Please tell me what should i write or what changes should i make. I have attached the reference image for a better understanding of what token I want.
enter image description here

Create a div with 6 element in it

I have an array of data that I want to programmatically put 6 of them in a div.

in other words I want each of my divs to have 6 items in them.

by the way im using next js , tailwindcss and i need this for styling purpose.

i tried to use for loop but it didn’t work.

Expo-doctor –fix-dependencies not working deprecationWarning: The `punycode` module is deprecated

trying with npm install Punycode –save I get:

enter image description here

Here is my package JSON file seems like there is issues with my dependencies

{
  "name": "calendar_app_f",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "1.17.11",
    "@react-native-community/async-storage": "^1.12.1",
    "@react-native-community/datetimepicker": "6.7.3",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-native-firebase/app": "^17.4.2",
    "@react-navigation/native": "^6.1.9",
    "@react-navigation/native-stack": "^6.9.17",
    "@react-navigation/stack": "^6.3.20",
    "expo": "^49.0.21",
    "expo-status-bar": "~1.4.4",
    "firebase": "^10.6.0",
    "gradlew": "^0.0.1-security",
    "nvm": "^0.0.4",
    "punycode":"^2.3.1",
    "react": "18.2.0",
    "react-native": "0.71.14",
    "react-native-date-picker": "^4.3.3",
    "react-native-gesture-handler": "~2.9.0",
    "react-native-reanimated": "~2.14.4",
    "react-native-safe-area-context": "4.5.0",
    "react-native-screens": "~3.20.0",
    "react-native-share": "^10.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0"
  },
  "private": true
}

I am doing this because npx expo-doctor -fix-dependencies is throwing me :

(node:4980) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created

Appending a value to FormData does not work and I’ve tired everything

The purpose of my code is to change a profile picture. That’s why I need the users ID to be sent along side with the picture itself. In the PHP file the picture gets recieved but not the user ID. I don’t know why this is because I’ve tried all sorts of solutions to this issue but I can not understand why the appended value does not exsist in $_FILES at all.

document.querySelector(".profilePictureButton").addEventListener("click",e=>
        { 
            popup(`
        <div class="exitPopup">x</div>
        <form id="profilePictureForm" method="POST" enctype="multipart/form-data">
            <label for="fileInput">Change profile picture</label>
            <input class="changePicture" type="file" id="fileInput" name="pfp">
            <button type="submit" class="profilePictureFormButton">Change profile Picture</button>
        </form>
        `); 
            document.getElementById("profilePictureForm").addEventListener("submit", async function(event){
                event.preventDefault();
                let fileForm = document.getElementById("profilePictureForm");
                const formData = new FormData(fileForm);
                formData.append("id", userData.userId);
                console.log(formData);
                
                try {

                    const response = await fetch("PHP/settings.php", {
                        method: "POST",
                        body: formData,
                    });
            
                    if (!response.ok) {
                        console.error("Error in response:", response);

                        const data = await response.json();
                        console.error("Server error:", data.error);
                        document.querySelector(".settingsErrorMessage").textContent = data.error;
                    } else {
                        const data = await response.json();
                        console.log("Change successful:", data);
                        document.querySelector(".popup").style.display = 'none';
                        renderProfilePage();
                    }
                } catch (error) {
                    console.error("Error during change:", error);
                }
                
            });
        });

I’ve done a console log before fetching making sure the value has appended, it has. I have done a var_dump($_FILES) to see if it is there, it is not.

I’ve tried
formData.append(“id”, userData.userId);
and
formData.set(“id”, userData.userId);

This is how the var_dump looks like:

{“pfp”:{“name”:”Molly.jpg”,”full_path”:”Molly.jpg”,”type”:”image/jpeg”,”tmp_name”:”C:UsersmeAppDataLocalTempphp9B38.tmp”,”error”:0,”size”:37924}}

Controlling volume state of multiple audio sliders

This creates sliders that control the volume of each individual audio:

import React, { useState, useEffect, useRef } from 'react';

function NoiseSlider({ noiseSrc }) {
  const [volume, setVolume] = useState(0.5);
  const audioRef = useRef(new Audio(noiseSrc));

  useEffect(() => {
    const audio = audioRef.current;
    audio.volume = volume;
    audio.loop = true;
    audio.play();

    return () => audio.pause();
  }, [volume]);

  return (
    <input
      type="range"
      min="0"
      max="1"
      step="0.01"
      value={volume}
      onChange={(e) => setVolume(parseFloat(e.target.value))}
    />
  );
}

export function App() {
  return (
    <div className="slider-container">
      <NoiseSlider noiseSrc="https://onlinetestcase.com/wp-content/uploads/2023/06/100-KB-MP3.mp3" />
      <NoiseSlider noiseSrc="https://onlinetestcase.com/wp-content/uploads/2023/06/500-KB-MP3.mp3" />
    </div>
  );
}

How to affect the volume state of all NoiseSliders at once? For example, resetting all of them to 0.5 with a single button?

Live code at StackBlitz.

why does async function behaves differently when using with addEventListener and calling it manually [duplicate]

I was trying to understand async and await keywords. I wrote a simple HTML file along with a JS file to demonstrate it.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise1 resolved");
  }, 10000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise2 resolved");
  }, 5000)
})

async function handlePromises() {
  const result1 = await promise1;
  console.log(result1);
  const result2 = await promise2;
  console.log(result2);
}

handlePromises();

// const myButton = document.getElementById("myButton");
// myButton.addEventListener("click", handlePromises);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width = device-width, initial-scale = 1.0">
  <title>Document</title>
  <script defer src="script.js"></script>
</head>

<body>
  <button id="myButton">Click me</button>
</body>

</html>

The console shows both

Promise1 resolved
Promised2 resolved

10 seconds after reloading the page(which is expected) But if I uncomment the last 2 lines and comment handlePromises() function and clicked the button, the console shows both

Promise1 resolved
Promise2 resolved

after 5 seconds. I thought it would behave the same way as the first case.

And If I click the button once more without reloading the page, the console prints

Promise1 resolved
Promise2 resolved

instantly.

Why is the same function behaving differently in different sceneraios.

Looking for a better way to find first duplicated number in an array

Hope you’re well.

So, I’m doing everyday challenge of Adventjs

This is my function for the first day: To find the first repeated number in an array.
It works. But I would like to find some other ways to do it.

function findFirstRepeated(gifts) {
  let indexOfDup = null;
  let duplicated = -1;

  for (let i = 0; i < gifts.length; i++) {
        for (let j = i + 1; j < gifts.length; j++) {
          if (gifts[i] == gifts[j]) {
            if (indexOfDup == null || indexOfDup > j) {
              indexOfDup = j;
              duplicated = gifts[i];
            }
          }            
        }
  }
  return duplicated;
}

**Here the instructions
**
In the toy factory of the North Pole, each toy has a unique identification number. However, due to an error in the toy machine, some numbers have been assigned to more than one toy. Find the first identification number that has been repeated, where the second occurrence has the smallest index! In other words, if there is more than one repeated number, you must return the number whose second occurrence appears first in the list. If there are no repeated numbers, return -1.

And some codes to try it out:

const giftIds = [2, 1, 3, 5, 3, 2]
const firstRepeatedId = findFirstRepeated(giftIds)
console.log(firstRepeatedId) // 3
// Even though 2 and 3 are repeated
// 3 appears second time first

const giftIds2 = [1, 2, 3, 4]
const firstRepeatedId2 = findFirstRepeated(giftIds2)
console.log(firstRepeatedId2) // -1
// It is -1 since no number is repeated

const giftIds3 = [5, 1, 5, 1]
const firstRepeatedId3 = findFirstRepeated(giftIds3)
console.log(firstRepeatedId3) // 5

Other way to try your code is to enter directly into Adventjs and go to day 1 challenge. This way, you can check a few tests more.

Thank you in advance 🙂

My code works but I want to find ways to improve it.

Error when clicking on the app menu item Electron

When I click on a menu item I get an error:

A JavaScript error occurred in the main process

How can I fix this?

Code:

Main.js

const { Menu } = require('electron')
const { createNewFile } = require('./js/createNewFile.js')

const menu = [
{
    label: 'File',
    submenu: [
    {
        label: 'New',
        click: () => {
            createNewFile()
        },
    }
}];

createNewFile.js

function createNewFile() {
    document.getElementById('newFileWindow').classList.remove('hiddenFileWindow')
}
module.exports = createNewFile

When using console.log(...) nothing works in the function either.

Could it be because I have a node_modules folder that is not read-only?

no such file or directory, stat ‘/vercel/path0/.vercel/output/functions/n/[[…index]].func’

I don’t know what is the problem here enter image description here

Running build in Washington, D.C., USA (East) – iad1
Retrieving list of deployment files…
Skipping build cache, deployment was triggered without cache.
Downloading 1448 deployment files…
Using prebuilt build artifacts…
[Error: ENOENT: no such file or directory, stat ‘/vercel/path0/.vercel/output/functions/n/[[…index]].func’] {
errno: -2,
code: ‘ENOENT’,
syscall: ‘stat’,
path: ‘/vercel/path0/.vercel/output/functions/n/[[…index]].func’
}

I am tri