Angular 15 downloading file from aws s3 url giving CORS Error

I have made downloading files from aws s3 url. It worked on my previous work on vue2 project. And I am cloning this function to Angular 15 project. But it gives CORS error when call api with httpclient get method.

I am calling s3 url file with httpclient with GET method.
And I set aws s3 cors config with belows.
[ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*", "http://localhost:4200/" ], "ExposeHeaders": [ "Content-Range", "Content-Length", "ETag" ], "MaxAgeSeconds": 3000 } ]

But it giving me error when calling aws s3 url with below codes.

`export class DownloadControllerService {
constructor(
private httpClient: HttpClient,
public cookieService: CookiesService
) {}

getBlobFile(url: string): Observable {
return this.httpClient.get(url, {
responseType: ‘blob’ as ‘json’,
});
}
}
`

enter image description here

Is it possible to get types in a dynamic array

I have the following code, where I can add anything into an array. Is it possible to get correctly typed paramteres inside the construct‘s anonymous function?

sandbox

const wrapper = <T>() => {
  const arr: T[] = [];

  const construct = (func: (...arr: T[]) => void) => {
    func(...arr);
  };
  const add = (x: T) => {
    arr.push(x);

    return { add, construct };
  };

  return { add };
};

const w = wrapper();

w.add(1)
  .add("2")
  .add({ a: 1 })
  .construct(
    // i need these to be correctly typed based on the types in add above  
    (a, b, c) => {
    //do something
  });

So far I just tried to used generict types, but doesnt seem to be working properly.

React.js – Cannot read properties of undefined (selectors)

Currently learning react ( and redux as well as redux-sagas) and I am basically making a loading screen while the client is connecting to the backend. However I am having the following error:”

ERROR

This error is related to this specific constant (in the app.js):

const isConnected = useSelector(Service.selectors.selectIsConnected)

which calls the following (in the file Service.js):”

_setSelectors (stateNamespace) {
    this.selectors = Object.freeze({
      selectIsConnected: (state) => state[stateNamespace][this.connectionStateProperty] === this.CONNECTION_STATES.CONNECTED,
      selectConnectionError: (state) => state[stateNamespace][this.connectionErrorProperty],
    })
  }

This is simply for knowing if the client is still connecting, is connected or disconnected from the actual back-end. So that by doing so I can implement the loading icon (app.js):

<div className={classes.wrapper}>
      
      {(() => {

        if( isConnected == CONNECTION_STATES.CONNECTING){
          return(
            <div className={classes.loading} > 
            <ClimbingBoxLoader
            size={60}
            color={"#36d7b7"}
            loading={loading}
            />
          <Typography className="welcome" variant="h2"> Welcome! </Typography>
        </div>
          )
        } else {
          return(
            <><AppBar className={classes.appBar} position="static" color="inherit">
            <Typography variant="h2" align="center">Lumos - SocialXR</Typography>
          </AppBar><CreationSelection /></>
          )
        }



      }) ()}
      
    </div>

However, the consoles gives me that error, and I nothing is showing up on the screen, besides the background itself… What can I do to fix this?

dynamicly change the content of a SPA using React?

I’m building my firt react app, a website for a portfolio.

In this website, I want different pages, “portfolio” (or the home page), “3D renders”, “CV” and “Contact”, for the sike of simplicity let’s focus only on porfolio and contact.

So, In this app I have a menu.jsx component, and I want it to redirect the user to the corresponding page on click.
It used to work just fine doing this:

./app.jsx:


import React from 'react';
import './App.css';
import './assets/layer1.svg';
import Menu from './components/menu';
import Portfolio from './components/portfolio';
import Contact from './components/contact';
import {BrowserRouter as Router, Route, Routes, redirect } from 'react-router-dom'


function App() {
  
 
  return (
  <div>
    <Menu/>
    
    <Router>
        <Routes>
        <Route path="/portfolio" element={<Portfolio />}/>
        <Route path="/contact" element={<Contact />}/>
        <Route exact path="/" element={<Portfolio />}/>
        </Routes>
    </Router>
    </div>
  );
}

export default App;

and
./component/menu/index.jsx :

const Menu=()=>{
    
    return(
      
        <div>
          <section class="menu">
          
            <div class="elem"  id="Portfolio">
                 <a href="http://localhost:5173/porfolio">Portfolio</a>
            </div>  
            //<div class="elem" id="CV">CV</div> 
            //<div class="elem" id="3D Models">3D Models</div> 
            <div class="elem" id="Contact">
                 <a href="http://localhost:5173/contact">Contact</a>
            </div> 
          
          </section>
          <hr/>
        </div>
    );
  
}

export default Menu;

But this had a major issue, in fact, This was reloading the webpage everytime I was clicking on said links,losing every interest of an SPA (quick white loading screen, having to re dl the whole page etc…)

So I had an other idea, using a state variable that would drive the shown page.
Here’s what I’ve tried (I had to move the menu.jsx into the app.jsx to call the functions, if you know how I can call them in the same configuration as above it would help me too)

/App.jsx


import React from 'react';
import './App.css';
import './assets/layer1.svg';
import Menu from './components/menu';
import Portfolio from './components/portfolio';
import Contact from './components/contact';
import { BrowserRouter as Router, Route, Routes, redirect } from 'react-router-dom'


let PageState = window.location.pathname;
let page;



function GoContact() {
  PageState = "/contact";
  page= <Contact/> //Second thing I tried
  console.log(PageState)
}
function GoPortfolio() {
  PageState = "/porfolio";
}

function App() {


  if (PageState == "/contact") {
    page = <Contact />
  }
  else {
    page = <Portfolio />
  }


  return (
    <div>
      <div>
        <section class="menu">

          <div class="elem" id="Portfolio" onClick={GoPortfolio} >Portfolio</div>
          //<div class="elem" id="CV" onClick={GoPortfolio}>CV</div>
          //<div class="elem" id="3D Models" onClick={GoPortfolio}>3D Models</div>
          <div class="elem" id="Contact" onClick={GoContact}>Contact</div>

        </section>
        <hr />
      </div>
      {page}

    </div>
  );
}

export default App;

The idea was:

  1. When opening the page, it would land you on whatever you placed in the path name (ex: website/cv would land you directly on the CV page) This Worked just fine
  2. When clicking on an element of the menu, it would change the “page state” Var to whatever you clicked on
  3. This would change what’s in {page} with the right component

Changing the content on screen, without reloading the page (in theory).

In fact, it was calling the function just right, and even changing the “PageState” var, (I could verify using console.log(PageState) but it would not change anything on screen, I even tried directly adding page=<contact/> but it doesn’t change either.

My guess is that, even tho my variables are in fact changing, nothing tells react to actualize the content, so App.jsx is not a “loop” that would dynamicaly check for changes (idk if you see what I mean)

Anyway, I hope that I am clear enough,
Thank you to anyone helping 🙂

Decode base64-encoded string(frontend reactnative) using multer in express

I picked a video file and upload it to the backend(Express) with base64-encoded string and in the backend, I used multer package to store it. But unfortunately I could decode the base64-encoded string which is from react-native. I request to check the Start Application Routes to help me.

Note: From the frontend, it successfully base64-encoded and I have checked it in online decoder, and I successfully got the video.

Upload a file from Frontend(Rect Native) with base64-encoded is given below,

const uploadVideo = async () => {
    console.log('Video Uploading Processing..!');

    try {
      const base64 = await RNFS.readFile(video, 'base64');
      const response = await axios.post('http://10.10.10.126:3000/', {
        video: base64,
        Headers: {
          'Content-Type': 'application/octet-stream',
        },
      });
      console.log(`Base64 Converted: ${base64}`);
      console.log(`Not Base64: ${video}`);
      console.log(response.data);
    } catch (error) {
      console.log(error);
    }
  return (
    
        <View style={{flex: 1}}>
          <TouchableOpacity style={styles.btnStyle} onPress={uploadVideo}>
            <Text style={styles.btnTextStyle}>Upload Video</Text>
          </TouchableOpacity>
       </View>
  );
};

Then I coded in Backend(Express) to store the uploaded file using multer is given below,

const express = require("express");
const multer = require("multer");
const path = require("path");

// File Upload Folder
const UPLOADS_FOLDER = "./uploads/";

// Define the Storage
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, UPLOADS_FOLDER);
  },
  filename: (req, file, cb) => {
    const fileExt = path.extname(file.originalname);
    const filename = file.originalname
      .replace(fileExt, "")
      .toLowerCase()
      .split(" ")
      .join("-" + "-" + Date.now());
    cb(null, filename + fileExt);
  },
});

//Prepare the final multer upload objects
let upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    console.log("File Uploaded");
    // cb(null, true);
    if (file.mimetype === "video/mp4") {
      cb(null, true);
    } else {
      cb(new Error("Only .mp4 format allowed!!!"));
    }
  },
});

const app = express();

//!---------> Start Application Routes
app.post("/", upload.array("video"), (req, res) => {
  // console.log("Before concrete the uploading....!");

  // Unfortunately I didn't get files and I don't find the error
  // const files = req.files; 
 // console.log(`Files: ${files}`);
 // ---------------------------->

  console.log("Server Hitted...!");
  // console.log(videoFile);
  res.send("Hello SuperStars");
});
//!---------> End Application Routes

//*---------> Start Default Error Handler
app.use((err, req, res, next) => {
  if (err) {
    if (err instanceof multer.MulterError) {
      // Multer error means: "avatar" type of
      res.status(500).send(err.message);
    } else {
      res.status(500).send(err.message);
    }
  } else {
    res.send("Success");
  }
});
//*---------> End Default Error Handler

app.listen(3000, () => {
  console.log("App Listening PORT on @3000!");
});

Laravel &AlpineJS Expert needed for strange Frontend issue.: A nested template is somehow always run twice, leading to 2 arrays being shown

I am running into a strange issue, using AlpineJS in my Blade Template. As the screenshot shows, you can see that the letterGroup in the modal is rendered twice, which makes no sense. I only want to have the letterGroup once in it. Does someone know what’s causing the issue?
It happens somehow randomly when clicking around.

Here are the screenshots.
This is what it should look like:
correct

But then this happens sometimes:
two letterGroups

and another bad one
and this happens with all keys..

This is what the blade template looks like:

    <div class="absolute flex flex-col items-center justify-center w-full max-w-xl" x-data="{ showOutgoingBrowserCallModal: '{{ $showOutgoingBrowserCallModal }}' }">

    <form @showBrowserCallModal="getAudioDevices" action="{{ route('dialer.twilio.gsm.outgoing') }}" enctype="multipart/formdata" method="POST" x-data="keypad('message')">

        <x-jet-input name="selected_caller_id" type="hidden" value="{{ $selectedCallerId }}" />
        <x-jet-input name="selected_call_type" type="hidden" value="{{ $selectedCallType }}" wire:model="selectedCallType" />
        <x-jet-input name="selected_twilio_number" type="hidden" value="{{ $selectedTwilioNumber }}" />
        @csrf
        <div class="flex flex-col items-center justify-center w-full" x-data="browserCall()">
            <x-jet-dialog-modal wire:model="showIncomingCall">
                <x-slot:title>
                    Incoming Call from <span ml-1 x-text="incomingCallFrom"></span>
                </x-slot:title>
                <x-slot:content>

                    <x-jet-button class="" id="mute-active-call-buttton" type="button">
                        Mute
                    </x-jet-button>
                    <x-jet-secondary-button id="accept-incoming-call-button" type="button" x-show="showIncomingCall">
                        Accept
                    </x-jet-secondary-button>
                    <x-jet-secondary-button id="hangup-active-call-buttton" x-show="showIncomingCallHangup">
                        Hangup
                    </x-jet-secondary-button>

                    <x-jet-secondary-button id="reject-incoming-call-button" x-show="showIncomingCall">
                        Reject
                    </x-jet-secondary-button>
                    <div x-text="formattedCallDuration"></div>
                </x-slot:content>

                <x-slot:footer>
                    <x-jet-secondary-button @click="show=false">
                        {{ __('Close') }}
                    </x-jet-secondary-button>
                </x-slot:footer>
            </x-jet-dialog-modal>
            <div class="relative flex flex-col items-center justify-center w-full px-3">
                <div @touchstart.prevent="closeModal" class="fixed inset-0 w-full transition-all transform" x-on:click.prevent="closeModal" x-show="show" x-transition:enter-end="opacity-100" x-transition:enter-start="opacity-0" x-transition:enter="ease-out duration-300" x-transition:leave-end="opacity-0" x-transition:leave-start="opacity-100" x-transition:leave="ease-in duration-200">
                    <div class="absolute inset-0 z-50 w-full bg-gray-500 opacity-75"></div>
                </div>

                <div class="flex flex-col items-start justify-center w-full" x-data="{ numberForBrowserCall: @entangle('numberForBrowserCall') }">
                    <div class="relative flex justify-between w-full flex-col">

                        <x-jet-input @change.prevent="validateInput" class='z-0 h-10 text-xl font-bold text-center rounded focus:shadow focus:outline-none' name='number' placeholder='Number..' type='text' wire:model="number" x-model='value' />

                        <div class="absolute right-2">
                            <button @click.prevent="deleteLetterFromInput" @touchstart.prevent="deleteLetterFromInput" class="content-end w-10 h-10 text-gray-500 bg-red-500 rounded-lg material-icons hover:bg-red-600" type="button">
                                backspace
                            </button>
                        </div>

                    </div>
                    <div x-show="true" class="w-full flex justify-center mt-4"><x-alert /></div>
                    @if(session('caller')&&session('caller')===$selectedTwilioNumber) <div class="bg-green-500 text-whote">Just dial another number and go back to the "VOIP Call Via Browser" - Modal to add another participant</div>@endif
                    @include('components.error', [
                    'isCurrentActiveForm' => true,
                    'propertyName' => 'number',
                    ])

                </div>

                <div class="flex items-center justify-center mt-8 w-80">

                    <div class="grid w-full grid-cols-3 gap-1 place-items-center">

                        <template :key="'number-'+index" x-for="(key, index) in phoneKeys">

                            <div class="flex items-center justify-center w-24 h-24">
                                <div class="relative flex items-center justify-center w-full h-full">
                                    <button @mousedown.prevent="setHoldAfterTimeout(index)" @mouseup.prevent="decideWhetherLongClickOrhideKey(index)" @touchend.prevent="decideWhetherLongClickOrhideKey(index)" @touchstart.prevent="setHoldAfterTimeout(index)" class="absolute inset-0 z-0 w-full h-full text-4xl font-bold bg-red-500 rounded-lg hover:bg-red-600 text-red hover:bg-gray-200" type="button">

                                        <div class="flex flex-col" x-show="!key.hideKey" x-text="key.number">
                                        </div>
                                        <div class="text-sm font-bold text-gray-500" x-show="!key.hideKey" x-text="key.letterGroup.toString()">
                                        </div>

                                    </button>

                                    <div x-show="show && key.longClick" class="inset-0 z-50 flex items-center justify-center jetstream-modal sm:px-0" x-on:close.stop="show = false;key.longClick=false" x-on:keydown.escape.window="show = false;key.longClick=false">

                                        <div :class="[width, key.letterGroup.length === 3 ? ' h-16 w-32' : ' h-28 w-24']" class="overflow-hidden transition-all transform bg-white rounded-lg shadow-xl" x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100" x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" x-transition:enter="ease-out duration-300" x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100" x-transition:leave="ease-in duration-200" x-trap.inert.noscroll="show && key.longClick">
                                            <div class="absolute w-full flex flex-wrap items-center justify-center h-full">


                                                <template :class="width" x-for="(letter,idx) in letterGroup" :key="idx+'-letterGroup'">

                                                    <button id="yop" @click.prevent="addLetterToInput(idx,letter)" @touchend.prevent="addLetterToInput(idx,letter)" class="flex items-center justify-center w-8 h-8 p-1 m-1 text-2xl font-bold transition bg-gray-200 bg-red-500 rounded-lg shadow outline-none text-red hover:bg-gray-500" type="button" x-text="letter"></button>
                                                </template>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </template>

                    </div>

                </div>

                @if ($toggleBrowserModal)
                <x-jet-button type="button" wire:click="$set('showOutgoingBrowserCallModal',true)">Toggle
                    Browser Modal
                </x-jet-button>
                @endif
            </div>
            <div class="z-0 flex flex-col items-start justify-start w-full mb-20" x-data="{
                    selectedCallerId: @entangle('selectedCallerId'),
                    selectedCallType: @entangle('selectedCallType'),
                    selectedTwilioNumber: @entangle('selectedTwilioNumber'),
            }">

                <div x-data="{ to: @entangle('number'), dialFrom: @entangle('selectedTwilioNumber'),showCallerId:'{{$selectedTwilioNumber}}' }">
                    <div x-show="!showError && to">
                        <div class="flex items-center justify-between w-full px-3 py-3 border-t-2 border-gray-200">
                            <div class="flex flex-col items-start justify-between w-full">
                                <div class="flex justify-start">
                                    <div class="mx-2 material-icons">smartphone</div>
                                    <div class="mx-2 text-xl font-bold">Dial From</div>
                                </div>

                                @include('components.error', [
                                'isCurrentActiveForm' => true,
                                'propertyName' => 'selectedTwilioNumber',
                                ])
                            </div>
                            <x-jet-dropdown width="w-[90vw] sm:w-[20rem]">
                                <x-slot name="trigger">
                                    <div @click.prevent="showNumbers=!showNumbers" class="flex items-center justify-center text-xl dropdown-trigger">
                                        <div class="text-red"> {{ $selectedTwilioNumber }}</div>
                                        <span class="text-4xl cursor-pointer material-icons" x-show="!showNumbers">keyboard_arrow_right</span>
                                        <span class="text-4xl cursor-pointer material-icons" x-show="showNumbers">expand_more</span>

                                    </div>

                                </x-slot>
                                <x-slot name="content">
                                    <div class="w-full dropdown">
                                        <ul class="dropdown-menu">
                                            <div class="px-2 text-xl font-semibold text-gray-500 bg-gray-100 y-1">Select a
                                                Twilio Number </div>
                                            <div class="mx-4 my-4">
                                                <x-jet-label class="my-2">Search</x-jet-label>
                                                <x-jet-input onclick="event.stopPropagation();" wire:model="twilioNumberSearchTerm" />
                                            </div>
                                            @foreach ($twilioNumbers as $twilioNumber)
                                            <div class="flex items-center justify-between px-2 py-2 my-2 transition-all duration-500 cursor-pointer hover:bg-gray-100" wire:click.prevent="$set('selectedTwilioNumber','{{ $twilioNumber->phone_number }}')">
                                                <span>{{ $twilioNumber->friendly_name }}</span>
                                                {{ $twilioNumber->phone_number }}
                                            </div>
                                            @endforeach
                                        </ul>
                                    </div>
                        </div>
                        </x-slot>

                        </x-jet-dropdown>

                        <x-jet-dialog-modal wire:model="showGsmNumberModal">
                            <x-slot:title>
                                Please provide your GSM Number
                            </x-slot:title>
                            <x-slot:content>
                                <div class="flex flex-col">
                                    <x-jet-label for="gsm_number" value="{{ $gsmNumber }}" />
                                    <x-jet-input autofocus class="block w-full mt-1" id="gsm_number" name="gsm_number" name="gsm_number" type="text" value="{{ $gsmNumber }}" wire:model="gsmNumber" />

                                    @include('components.error', [
                                    'isCurrentActiveForm' => true,
                                    'propertyName' => 'gsmNumber',
                                    ])
                                </div>

                            </x-slot:content>
                            <x-slot:footer>

                                <x-jet-button :disabled="$errors->has('gsmNumber') || !$gsmNumber" class="ml-2" type="button" wire:click.prevent="closeGsmNumberModal">
                                    {{ __('Save') }}
                                </x-jet-button>
                            </x-slot:footer>
                        </x-jet-dialog-modal>

                        @if($selectedTwilioNumber) <div class="flex items-center justify-between w-full px-3 py-3 border-t-2 border-gray-200">
                            <div class="flex items-center justify-between">
                                <div class="mx-2 material-icons">image</div>
                                <div class="mx-2 text-xl font-bold">Caller ID</div>
                            </div>
                            <x-jet-dropdown>
                                <x-slot:trigger>
                                    <div @click.prevent="showCallerIds=!showCallerIds" class="flex items-center justify-center text-xl">
                                        <div class="text-red"> {{ $selectedCallerId }}</div>
                                        <span class="text-4xl cursor-pointer material-icons" x-show="showCallerIds">expand_more</span>
                                        <span class="text-4xl cursor-pointer material-icons" x-show="!showCallerIds">keyboard_arrow_right</span>
                                    </div>
                                </x-slot:trigger>

                                <x-slot:content>
                                    <div class="z-[100]">

                                        <div class="px-2 text-gray-500 bg-gray-100 y-1">Verified GSM Numbers </div>
                                        @forelse ($verifiedGsmNumbers as $index => $verifiedCallerId)
                                        <div class="px-1 py-2 my-2 transition-all duration-500 cursor-pointer hover:bg-gray-100" wire:click.prevent="$set('selectedCallerId','{{ $verifiedCallerId['phoneNumber'] }}')" wire:key="{{ $index . '-' . $verifiedCallerId['phoneNumber'] }}">
                                            {{ $verifiedCallerId['phoneNumber'] }}
                                        </div>
                                        @empty <div class="">No verified GSM Numbers</div>
                                        @endforelse
                                        <div class="px-2 text-gray-500 bg-gray-100 y-1">Twilio Numbers </div>
                                        @forelse($twilioNumbers as $index => $twilioNumber)
                                        <div class="px-1 py-2 my-2 transition-all duration-500 cursor-pointer hover:bg-gray-100" wire:click.prevent="$set('selectedCallerId','{{ $twilioNumber->phone_number }}')" wire:key="{{ $index . '-' . $twilioNumber->phone_number }}">
                                            {{ $twilioNumber->phone_number }}
                                        </div>

                                        @empty <div class="">No Twilio Numbers</div>
                                        @endforelse
                                    </div>

                                </x-slot:content>

                            </x-jet-dropdown>
                        </div>
                        @endif

                        <div x-show="showCallerId" class="flex items-center justify-between w-full px-3 py-3 border-t-2 border-gray-200">
                            <div class="flex flex-col items-start justify-between">
                                <div class="flex items-center justify-center">
                                    <div class="mx-2 material-icons">phone</div>
                                    <div class="mx-2 text-xl font-bold">Call via</div>

                                </div>
                                @include('components.error', [
                                'isCurrentActiveForm' => true,
                                'propertyName' => 'gsmNumber',
                                ])
                            </div>
                            <x-jet-dropdown>
                                <x-slot name="trigger">
                                    <div @click.prevent="showCallTypes=!showCallTypes" class="flex items-center justify-center text-xl">
                                        <div class="text-red"> {{ $selectedCallType }}</div>
                                        <div class="text-red">
                                            {{ $validatedGsmNumber ? '(' . $validatedGsmNumber . ')' : '' }}
                                        </div>
                                        <span class="text-4xl cursor-pointer material-icons" x-show="!showCallTypes">keyboard_arrow_right</span>
                                        <span class="text-4xl cursor-pointer material-icons" x-show="showCallTypes">expand_more</span>
                                    </div>

                                </x-slot>
                                <x-slot name="content">
                                    <div>
                                        <ul>
                                            <div class="px-2 text-gray-500 bg-gray-100 y-1">Select a Twilio Number: </div>

                                            @foreach ($callTypes as $index => $callType)
                                            <div class="px-1 py-2 my-2 transition-all duration-500 cursor-pointer hover:bg-gray-100" wire:click.prevent="setSelectedCallType('{{ $callType }}')">
                                                {{ $callType }}
                                            </div>
                                            @endforeach
                                    </div>
                                    </ul>
                                </x-slot>

                            </x-jet-dropdown>

                        </div>

                        <x-jet-dialog-modal wire:model="showOutgoingBrowserCallModal">
                            <x-slot:title>

                                VOIP Call Via Browser
                            </x-slot:title>
                            <x-slot:content>
                                <div>
                                    <div class="p-2 bg-gray-100 rounded">
                                        <div> To: {{ $number }}</div>
                                        <div>Dial From: {{ $selectedTwilioNumber }}</div>
                                        <div>Caller Id: {{ $selectedCallerId }}</div>
                                    </div>

                                    <main class="flex flex-col" id="controls">
                                        <section class="border-none rounded" id="info">

                                            <div class="flex flex-wrap w-full hide" id="output-selection">
                                                <x-jet-label class="mt-4 mb-1">Ringtone Devices</x-jet-label>
                                                <select @change="updateOutputDevice" class="block w-full overflow-auto rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-red focus:ring-red dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-red dark:focus:ring-red" id="ringtone-devices" multiple></select>
                                                <x-jet-label class="mt-4 mb-1">Speaker Devices</x-jet-label>
                                                <select @change="updateRingtoneDevice" class="block w-full overflow-auto rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-red focus:ring-red dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-red dark:focus:ring-red" id="speaker-devices" multiple></select><br />
                                                <x-jet-secondary-button class="my-4" @click.prevent="getAudioDevices" id="get-devices">Seeing "Unknown"
                                                    devices?
                                                </x-jet-secondary-button>
                                            </div>
                                        </section>
                                        <section class="center-column">

                                            <x-jet-button class="" id="mute-active-call-buttton" type="button">
                                                Mute
                                            </x-jet-button>

                                            <x-jet-secondary-button @click.prevent="outgoingCallHangup" id="hangup-active-call-buttton" x-show="showIncomingCallHangup">
                                                Hangup
                                            </x-jet-secondary-button>
                                            <div class="hide" id="call-controls">


                                                <div class="hide w-[10rem]" id="volume-indicators" x-show="showVolumeIndicators">
                                                    <x-jet-label>Mic Volume</x-jet-label>
                                                    <div class="w-0 h-5" id="input-volume"></div>
                                                    <br /><br />
                                                    <x-jet-label>Speaker Volume</x-jet-label>
                                                    <div class="w-0 h-5" id="output-volume"></div>
                                                </div>

                                            </div>

                                        </section>
                                        <x-jet-button @click.prevent="makeBrowserCall" class="my-0 mr-4 max-w-[10rem]" type="button" x-bind:disabled="disableCallButton">
                                            Call</x-jet-button>
                                    </main>
                                </div>
                            </x-slot:content>
                            <x-slot:footer>
                                <div class="flex justify-end w-full">

                                    <x-jet-secondary-button @click="show=!show" type="button">
                                        {{ __('Cancel') }}
                                    </x-jet-secondary-button>
                                </div>

                            </x-slot:footer>

                        </x-jet-dialog-modal>





                        <div class="flex items-end justify-end w-full px-3 py-3 border-t-2 border-b-2 border-gray-200">
                            <div class="flex items-center justify-between basis-2/3">
                                <div class="mx-2 material-icons">mic_external_on</div>
                                <div class="flex flex-col flex-wrap justify-center mx-2 text-xl font-bold itemse-center">
                                    <div class="text-xl">Record Call?</div>
                                    <p class="text-sm">
                                        You may be required by law to notify the recipient
                                    </p>
                                </div>
                            </div>
                            <div class="flex items-center justify-end text-xl basis-1/3">

                                <x-jet-input class="block w-6 h-6 bg-white border-4 rounded-full cursor-pointer a" name="isCallRecorded" type="checkbox" wire:change.default="$set('isCallRecorded', true)" wire:model="isCallRecorded" />

                            </div>
                        </div>



                        @if ($selectedTwilioNumber && $selectedCallerId)
                        <div class="flex w-[20rem] items-center justify-center md:w-[40rem]" x-show="!showError &&value">
                            <x-jet-button type="submit"> Place Call</x-jet-button>

                        </div>
                        @endif

                    </div>
                </div>
            </div>

        </div>


    </form>




    <script>
        let device;
        let interval
        const inputVolumeBar = document.getElementById("input-volume");

        const outputVolumeBar = document.getElementById("output-volume");

        const speakerDevices = document.getElementById("speaker-devices");

        const ringtoneDevices = document.getElementById("ringtone-devices");
        const volumeSlider = document.getElementById("volume-slider");
        const ringtoneVolumeSlider = document.getElementById("ringtone-volume-slider");
        const acceptIncomingCallButton = document.getElementById("accept-incoming-call-button");
        const muteActiveCallButton = document.getElementById("mute-active-call-buttton");
        const rejectIncomingCallButton = document.getElementById("reject-incoming-call-button");
        const hangupActiveCallButton = document.getElementById("hangup-active-call-buttton");
    </script>
</div>

To find the correct places, search for the AlpineJS Keyword template. I basically have one template nested into another one. Via one template I loop over the keys from 1-0 etc and then within this template I loop basically over each letterGroup to display each letter as an button with a click listener.

For more information, please have a look in my keypad.js file, which is responsible for handling all the logic in the blade template:

I also have an AlpineJS Chrome extension installed but everything seems to be OK. Also, there are zero errors in the console. Everything works fine but I don’t want to have the lettergroup rendered twice within the modal:(

Thank yo so much for any of your responses:)

dollar sign identifier in redux saga

I want to send a paginated get request in the saga with Axios get but in the first approach it returns undefined and in the second one it works. in the first one, I used a dollar sign identifier in the URL.
what is happening under the hood

first:

payload directly used in URL as dollar sign identifier

second

payload undirectly used in URL

I want to know what is happening and what is the difference between the first and second approaches

How to click on multiple links(onclick events) and extract content and append them to a div

consider few links in the selector of .bdView > .row > div a[onclick] , when clicked on each link relevant content will be loaded on both #amendinfo0 , #amendinfo1 div tags on a onclick event. How do i extract the content and append them in to a div

example for a tag:

<a href="javascript:void(0);" onclick="amendinfoBtn('art1', 'art')">Article 1</a>

Below is what i tried:

var links = $('.bdView >.row > div a[onclick]');

var combinedContentDiv = $('<div>');

links.each(function() {
  var onclickAttr = $(this).attr('onclick');
  
  var content = onclickAttr.match(/'#amendinfod+'/g).map(function(selector) {
    return $(selector).html();
  }).join('');
  combinedContentDiv.append(content);
});

$('body').append(combinedContentDiv);

ReactJs: How to update the pagination and content list items every time I search/filter a content in the search bar

First I’m not sure if the functionality of my filter/search bar are correct.

Here are my concern, we have the words ‘dolor’ and ‘dolorum’ in the items of 25pages.

You can view it here.

Try to search the word “dolor” in the searchbar, the 25pages pagination is now 18pages. Then click the third pagination links and update your search to ‘dolorum’ in the searchbar, see the message says ‘No Posts Found!‘ and the pagination is now 2pages. But we have ‘dolorum’ content in the items but it is only up to two pages of the pagination, and I think that is the reason why I got an error of ‘No Posts Found!‘, because I clicked the third pagination items.

Is my code/functionality right? Is there any suggestions to avoid that bug in my code? maybe update the pagination/content items everytime I search?

Below is my code and to better understand here is the complete sandbox code https://codesandbox.io/. Full view here codesandbox. It’s free to fork it!

Movielist.js

import { React, useState, useEffect } from "react";
import MovieListPagination from "./MovieListPagination";
import SearchBar from "./SearchBar";

const MovieList = () => {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  const [searchResults, setSearchResults] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          setSearchResults(result);
          //console.log(result);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return <div className="p-3">Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div className="p-3">Loading...</div>;
  } else {
    return (
      <>
        <SearchBar items={items} setSearchResults={setSearchResults} />
        <MovieListPagination dataProps={searchResults} itemsPerPage={4} />
      </>
    );
  }
};

export default MovieList;

MovielistPagination.js

import { React, useState } from "react";
import { Row, Alert } from "react-bootstrap";
import ReactPaginate from "react-paginate";
import MovieListItems from "./MovieListItems";

const MovieListPagination = ({ itemsPerPage, dataProps }) => {
  const [itemOffset, setItemOffset] = useState(0);
  const endOffset = itemOffset + itemsPerPage;
  const currentItems = dataProps.slice(itemOffset, endOffset);
  const pageCount = Math.ceil(dataProps.length / itemsPerPage);
  const handlePageClick = (event) => {
    const newOffset = (event.selected * itemsPerPage) % dataProps.length;
    setItemOffset(newOffset);
  };

  const results = currentItems.map((item) => (
    <MovieListItems key={item.id} items={item} />
  ));

  const content = results?.length ? (
    results
  ) : (
    <Alert variant="primary">No Posts Found!</Alert>
  );

  return (
    <>
      <Row className="justify-content-center">{content}</Row>

      <ReactPaginate
        breakLabel="..."
        nextLabel="›"
        onPageChange={handlePageClick}
        pageRangeDisplayed={3}
        marginPagesDisplayed={1}
        pageCount={pageCount}
        previousLabel="‹"
        renderOnZeroPageCount={null}
        containerClassName="justify-content-center pagination"
        previousClassName="page-item"
        previousLinkClassName="page-link"
        nextClassName="page-item"
        nextLinkClassName="page-link"
        pageClassName="page-item"
        pageLinkClassName="page-link"
        breakClassName="page-item"
        breakLinkClassName="page-link"
        activeClassName="active"
        disabledClassName="disabled"
      />
    </>
  );
};

export default MovieListPagination;

SearchBar.js

import { Form, Button } from "react-bootstrap";

const SearchBar = ({ items, setSearchResults }) => {
  const handleSubmit = (e) => e.preventDefault();

  const handleSearchChange = (e) => {
    if (!e.target.value) return setSearchResults(items);

    const resultsArray = items.filter(
      (item) =>
        item.title.includes(e.target.value.toLowerCase()) ||
        item.body.includes(e.target.value.toLowerCase())
    );

    setSearchResults(resultsArray);
  };

  return (
    <>
      <Form onSubmit={handleSubmit}>
        <Form.Group className="my-3">
          <Form.Control
            type="text"
            id="search"
            placeholder="Search here..."
            onChange={handleSearchChange}
          />
        </Form.Group>
        <Button className="d-none" variant="primary" type="submit">
          Search
        </Button>
      </Form>
    </>
  );
};
export default SearchBar;

Alpine js getting the error can’t find store and the object inside the store

I’m trying to make a for loop inside the Alpine component from a store, but I’m getting the error “Uncaught TypeError: Cannot read properties of undefined (reading ‘items’)”. Even though I’m doing the for loop inside the template tag and passing the values correctly I think. What might be the problem ? Or do I need the import the store inside the html file ?

// index.html
<div class="content__mid" x-data="">
  <template x-for="item in $store.products.items" :key="item.id">
    <p class="content__mid-item" x-text="item.title"></p>
  </template>
</div>

//script.js

import Alpine from 'alpinejs'
 
Alpine.store('products', {
  items: [
    {
      id: 1,
      title: 'Aspirin',
      country: 'USA',
      manufacturer: 'Bangladesh',
      price: '120',
      validDate: '02.10.2024'
    },
    {
      id: 2,
      title: 'Aspirin',
      country: 'Italy',
      manufacturer: 'Bangladesh',
      price: '120',
      validDate: '02.10.2024'
    }
  ]
})
 
Alpine.start()

How to post the label of option selected to WEBAPI from html form

here’s my html form in Visual Studio code:

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initialscale=1.0">
        <h1>CAR SERVICE CENTRE</h1>
        <link rel="stylesheet" href="design.css">
    </head> 
    <body>

        <form name="CarServ" id="myForm">
            <div>
                <label>CarModel:</label>
                <input type="text" id="model" size="65" name="carmodel" placeholder="Enter Car Model" required>
            </div>
            <div>
                <label>Car Number:</label>
                <input type="text" size="65" id="num" name="carnum" placeholder="Enter Car Number" required >
            </div>
            <div>
                <label>Contact number:</label>
                <input type="text" size="65" id="cnum" name="contactnum" placeholder="Enter your contact number" required>
            </div>
            <div id="service" class="opt">
                <label>Type of service:</label>
                <input type="radio" name="typeofservice" id="t1" value="Waterwash"required>
                <label for="t1">Waterwash</label>
                <input type="radio" name="typeofservice" id="t2" value="Fullservice" required>
                <label for="t1">Fullservice</label>
    
    
            </div>
            <br/>
            <div class="check">
    
                <label>Addons:</label>
                
                <label><input type="checkbox" name ="checkk" value="10%off First service visit" class="checkin" id="mycheck1">10%off First service visit</label>
    
                <label><input type="checkbox" name="checkk" value="10%off Waterwash" class="checkin" id="mycheck2">10%off Waterwash</label>
    
                <label><input type="checkbox" name ="checkk" value="Free AC Inspection" class="checkin" id="mycheck3">Free AC Inspection</label>
    
            </div>  
    
            <div class="dropd">
                <label>Select State:</label>
                    <select class="form-control" name ="selectstate" id="select1">
                        <option value="0" selected="" disabled="">--SELECT--</option>
                        <option value="" selected="selected">Select State</option>
                        <option value="option1">Tamilnadu</option>
                        <option value="option2">Kerala</option>
                        <option value="option3">Karnataka</option>
                        <option value="option4">Maharastra</option>
                    </select>   
            </div>
            
            <div class="dropdcontent">
                <label>Select City:</label>
                    <select class="form-control" name ="selectcity" id="select2">
                        <option value="option1">Select State</option>
                        <option value="option1">Chennai</option>
                        <option value="option1">Coimbatore</option>
                        <option value="option1">Madurai</option>
                        <option value="option2">Select State</option>
                        <option value="option2">Trivandrum</option>
                        <option value="option2">Kochi</option>
                        <option value="option2">Kollam</option>
                        <option value="option3">Select State</option>
                        <option value="option3">Bangalore</option>
                        <option value="option3">Mysore</option>
                        <option value="option4">Select State</option>
                        <option value="option4">Mumbai<option>
                        <option value="option4">Pune<option>
                  </select>     
            </div>
            <br/>
                
            <button type="submit">Submit</button>
        
    
        </form>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
        <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
        <script src="carservice.js"></script>
        <script src="formtoapi.js"></script>
    
    
    </body>
</html>

carservice.js – javascript file for dependent dropdowns:


var $select1 = $( '#select1' ),
    $select2 = $( '#select2' ),
    $options = $select2.find('option');

    
$select1.on( 'change', function() {
    var selectedStateText = $(this).find("option:selected").text();
    $select2.html($options.filter('[value="' +this.value + '"]') );
}).trigger('change');

$select2.on( 'change', function() {
    var selectedCityText = $(this).find("option:selected").text();
}); 


formtoapi.js : posting form to web-api in Visual Studio 2022:


document.getElementById("myForm").addEventListener("submit",submitForm);
function submitForm(event){
  event.preventDefault();
  var formData=new FormData(event.target);
  fetch("http://localhost:5239/api/Forms/submit-form",{
    mode:"cors",
    method:"POST",
    body:formData
  })
  .then(response =>{
    if(!response.ok){
      throw new Error("HTTP error"+respsonse.status);
    }
    return response.json();
  })
  .then(data=>{
    console.log("Success:",data);
  })
  .catch(error=>{
    console.error("Error:",error);
  });

}

In API I got a controller
FormsController.cs :



using CarFormApi.Models;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace CarFormApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FormsController : ControllerBase
    {
        private static List<FormsDataModel> formsDataList = new List<FormsDataModel>();

        [HttpPost("submit-form")]
        public IActionResult SubmitForm([FromForm] FormsDataModel formsData)
        {
            // process the form data
            string carmodel = formsData.Carmodel;
            string carnum = formsData.Carnum;
            string contactnum = formsData.Contactnum;
            string typeofservice = formsData.Typeofservice;
            string selectstate = formsData.Selectstate;
            string selectcity = formsData.Selectcity;



            // validate the form data
            if (string.IsNullOrWhiteSpace(carmodel) || string.IsNullOrWhiteSpace(carnum) || string.IsNullOrWhiteSpace(contactnum) || string.IsNullOrWhiteSpace(typeofservice) || string.IsNullOrWhiteSpace(selectstate) || string.IsNullOrWhiteSpace(selectcity))
            {
                return BadRequest(new { Message = " Enter the required fields." });
            }
            formsDataList.Add(formsData);


            return Ok(formsData);

        }

    }
}

and also created a FormsDataModel :

namespace CarFormApi.Models
{
    public class FormsDataModel
    {
        public string Carmodel { get; set; }
        public string Carnum { get; set; }
        public string Contactnum { get; set; }
        public string Typeofservice { get; set; }
        public string Checkk { get; set; }
        public string Selectstate { get; set; }
        public string Selectcity { get; set; }

    }
}

Everything is working fine except those dropdowns. The input values of my html form are being posted back to the console. Yes, I can see the values of the options selected being posted but not the actual name/label of the options selected. I want the options(like “Karnataka”) to be displayed in the console instead of values (like “option1”).

Can someone tell me how to make it happen, please help me understand what am I doing wrong.

Why the mouse up event is triggered twice?

Here is my code.

The code is that when the user mouse down on table cell, the state variable minX will be updated,
and when the mouse button is up, the endSelect function will be called. The endSelect function just prints the state variable.

The problem is why the endSelect function is called twice when I click the table cell.
I have removed the <StrictMode> tag from the index.js, but the problem still exists.

Data not posted Correctly on submit

I am trying to save the form data on click of save changes button. On click of input field I wanted to save the value in some other input field but not able to do so. Can someone please help..

date get appended correctly in both the input boxes ‘input field’ and ‘another input field’ but get saved in ‘input field’ text box only upon save.

function code(){
        var p = '03/02/2022';
        $("#input_field").val(p);  // data saved on click of submit
        $("#another_input_field").val(p);  // data not saved on click of submit
} 
$(window).load(function () {
    var lat = document.getElementById('input_field');
    lat.addEventListener('click',function(){
        alert("in");
        code();
    });
});

How should multiple rendering of React Transition Group children be handled in NextJS?

Currently have a JSX component that has a useEffect that triggers an API call on mount. However, I’ve noticed that the API runs twice and traced that the cause for this is with the react-transition-group library wrapping it.

Showing a simple overview of my code.

import React, { useRef } from 'react';
import { TransitionGroup, Transition } from 'react-transition-group';

export default function TransitionLayout({ location, children }) {
  const nodeRef = useRef(null);

  return (
    <div>
      <TransitionGroup>
        <Transition nodeRef={nodeRef} mountOnEnter key={location}>
          {(status) => (
            <div
              styles={
                {
                  /*some styles here based on status*/
                }
              }
            >
              {/*children components here would somehow render twice*/}
              {children}
            </div>
          )}
        </Transition>
      </TransitionGroup>
    </div>
  );
}

I’ve seen related issues to this, and the common fix is to update the implementation of React Router Switch. But how do you handle this in NextJS?