HydrationError when using next-i18n with Next.js and TypeScript

I am trying to implement internationalization using react-i18n in my frontend application.
The application uses TypeScript and Next.js.

I have set up two languages, English and Finnish, along with a language switcher.
When I refresh the page with English (default) selected, all is well, but when I refresh with Finnish selected, I get a HydrationError saying that Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used as shown below:

screenshot of the error

I assume this is because the i18n library modifies the language on the client side, disrupting the server-side rendering checks.

My i18n.ts is as follows:

"use client"

import i18next from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import resourcesToBackend from "i18next-resources-to-backend"
import enNs from "./public/locales/en.json";
import fiNs from "./public/locales/fi.json";

export const defaultNS = "ns1";

i18next
  .use(initReactI18next)
  .use(LanguageDetector)
  .use(resourcesToBackend((language: any, namespace: any) => import(`./public/locales/${language}.json`)))
  .init({
    debug: true,
    lng: undefined,
    fallbackLng: "en",
    defaultNS,
    resources: {
        en: {
          ns1: enNs
        },
        fi: {
          ns1: fiNs
        },
      },
  });

export default i18next;

The next-i18next library does not work since that is only for pages applications and I am using an app application.

How do I make it so that either the i18n library does the modifications on the server side, or otherwise so that the HydrationError is resolved?

Display list in several columns and keep the number of elements per column equal when their heights are different [duplicate]

I simply need to have an unordered list displayed in 3 columns, but without vertical alignment.

Is there a way to remove the gap between the list element no. 2 and no. 5 in this example?

I already tried flexbox, float, table, column and grid layout and can’t figure it out, although it looks simple at first glance.

A JS solution would also be OK, but i can’t alter the HTML output. And i don’t know the item’s heights, so i don’t need a solution with fixed pixel values.

If there is a solution for this, the following sorting would also be a nice gimmick, but i think i may figure that one out after i get a starting point:

1 3 5
2 4

ul { 
  list-style-type: none; 
  padding: 0;
  color: white; 
  text-align:center;
}

.small { 
  height: 30px
}

.large {
  height: 200px
}

li {
  background:red;
}

li:nth-child(2n) { 
  background:blue;
}

ul {
  display: grid; 
  grid-template-columns: repeat(3, minmax(0, 1fr));
}
<ul>
  <li class="large">1</li>
  <li class="small">2</li>
  <li class="small">3</li>
  <li class="small">4</li>
  <li class="small">5</li>
</ul>

Desired result:
enter image description here

Setting a default value on a dynamically generated selectlist

I’m working with an existing form that is HTML and Java. There is a single default selection available for “Transport Protocol” which is populated from an xml. I am wondering how to set the value of “Default” for that particular selectlist upon load or even set it and make the field hidden. This is my first post, so any help would be greatly appreciated.

<script language="javascript">
            $(document).ready(function () {
    
                /* Location Search */
                $("#locationsTextSearch").on("input", GetTableData);
                $("#locationsTextSearch").on("focus", function () {
                    $("#icon-search").addClass("icon-search-blue");
                });
                $("#locationsTextSearch").on("focusout", function () {
                    $("#icon-search").removeClass("icon-search-blue");
                });
    
                // default warning to NotWarned in xamarin
                if (!CefSharpEnabled) {
                    $("#transportationwarning").val("NotWarned");
                }
    
                // Clicking procced is the same as submit
                $("#proceedButton").click(function () {
                    $("#Form").submit();
                });
                
                //Set up Tab control
                $('.tabs').tabs();
    
                //handle form submition
                $("#Form").submit(function () {
                    if (ValidateLocationForms() && $(this)[0].checkValidity() == true) {
    
                        // Show confim if needed
                        ShowConfirm($(this));
                    }
    
                    ValidateRequiredSingleSelectOnly($("#transportationprotocol"));
                    ValidateRequiredSingleSelectOnly($("#transportationpriority"));
    
                    return false;
                });
    
                //focus on registration id field
                $("#currentodometer").focus();
    
            });
    
            function decimalCheck(input, event) {
                var str = input.value;
                if (event.keyCode == 69) {
                    return false;
                }
                else if (str.includes(".") && !isNaN(event.key)) {
                    var index = str.indexOf(".");
                    if (str.length - index > 1) {
                        return false;
                    }
                }
                return true;
            }
    
            function lengthCheck(input) {
                if (input.value.includes(".")) {
                    if (input.value.length > input.maxLength + 2) {
                        input.value = input.value.slice(0, input.maxLength);
                    }
                }
                else {
                    if (input.value.length > input.maxLength) {
                        input.value = input.value.slice(0, input.maxLength);
                    }
                }
                return input;
            }
    
            function AfterFillForm() {
    
                GenerateSelectBox("transportationprotocol", "transportprotocol.xml",                      "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
                    $("#protocolvals").prepend(result);
                    SetSelectBoxFromParameters($("#transportationprotocol"));
                    $("#transportationprotocol").prop("required", true);
                    $("#transportationprotocol").change(function () {
                        ValidateRequiredSingleSelectOnly($(this));
    
                        // Reload divert panel when changing protocol
                        LoadDiverts();
                    });
    
                    // Load diverts on initial load when diverts are passed in. Wait till this time so that the protocol has been set and the list is filtered correctly
                    LoadDiverts();
    
                    GenerateSelectBox("transportationpriority", "transportpriority.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
                        $("#priorityvals").prepend(result);
                        SetSelectBoxFromParameters($("#transportationpriority"));
                        $("#transportationpriority").prop("required", true);
                        $("#transportationpriority").change(function () {
                            ValidateRequiredSingleSelectOnly($(this));
                        });
                        
                        GenerateSelectBox("gender", "Gender.xml", "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
                            $("#gendervals").prepend(result);
                            SetSelectBoxFromParameters($("#gender"));
                            GenerateSelectBox("transportstate", "state.xml", "genericselectvalue.xsl", false, false, false, 1, false, false).then(function (result) {
                                $("#statevals").prepend(result);
                                SetSelectBoxFromParameters($("#transportstate"));
                                setVerifiedAddress();
                                AfterAllControlsInitialized(); // must go after last select intialized
    
                                //GenerateSelectBox("Race", "Race.xml",   "genericselect.xsl", false, false, false, 1, false, false).then(function (result) {
                                //    $("#racevals").prepend(result);
                                //    SetSelectBoxFromParameters($("#Race"));
                                //});
                            });
                        });
                    });
                });
    
                // initialze modal
                if (!CefSharpEnabled)//xamarin only
                {
                    $('.modal').modal();
                }
    
                setDefaultLocation();
                SetCurrentTab();
            }
    
            function SetCurrentTab() {
                var selectedAddressTab = $("#SelectedAddressTab").val();
                if (selectedAddressTab == "locationtab") {
                    $("#tab1").children()[0].click();
                }
                else {
                    $("#tab2").children()[0].click();
                    $("#SelectedAddressTab").val(selectedAddressTab);
                }
            }
    
            function GetCurrentTab() {
    
                var selectedAddressTab = $("#SelectedAddressTab").val();
                if (selectedAddressTab == "locationtab") {
                    return "locationtab";
                }
                else {
                    return "addresstab";
                }
            }
    
            function GetFacilityDiverts(locationName) {
                // request facility divert for location
                if (!CefSharpEnabled) { // Xamarin only
                    var param = {
                        _method: 'getFacilityDiverts',
                        _locationName: locationName
                    }
                    invokeCSharp(JSON.stringify(param));
                }
            }
    
            // called by c# whenthe facility divert request returns
            function FacilityDivertReturn(diverts) {
    
                if (diverts) {
    
                    var response = JSON.parse(diverts);
                    var currentTab = GetCurrentTab();
    
                    // if the user has selected another location or changed the tab since this facility divert status was requested just throw away the response
                    if (response.locationName == $("#Form").data("lastQueriedLocation") && currentTab == $("#Form").data("selectedTabForLastQuery")) {
    
                        LoadDiverts(response.diverts);
                    }
                }
            }
    
            // call by c# when loading the transport form from a status error with divert information already contained
            function SetDiverts(diverts) {
    
                diverts = JSON.parse(diverts);
    
                var currentTab = GetCurrentTab();
                $("#" + currentTab).data("diverts", diverts);
            }
    
            function LoadDiverts(diverts) {
    
                if (!diverts) {
                    diverts = $("#" + GetCurrentTab()).data("diverts")
                }
    
                // clear diver panel if there are no diverts 
                if (diverts && diverts.length > 0) {
                    BuildDiverts(diverts);
                }
                else {
                    ClearDiverts();
                }
            }
    
            function BuildDiverts(diverts) {
    
                // cache diverts to current tab
                var currentTab = GetCurrentTab();
                $("#" + currentTab).data("diverts", diverts);
    
                // clear DOM
                $("#divertListRow,#divertChipList,#divert_modal_reasons").empty();
    
                var allReasons = [];
                var visibleDiverts = 0;
                var currentProtocol = $("#protocolvals .dropdown-trigger").val();
    
                // process all diverts
                for (var i = 0; i < diverts.length; i++) {
                    var divert = diverts[i];
    
                    // find if current divert matches selected protocol
                    var divertReasons = "";
                    for (var j = 0; j < divert.Reason.length; j++) {
    
                        var reason = divert.Reason[j];
                        if (!currentProtocol || !reason.Protocols || reason.Protocols.split(",").includes(currentProtocol)) {
                            
                            divertReasons += reason.Name + " u2014 "; // add dash character
                            if (!allReasons.includes(reason.Name)) {
                                allReasons.push(reason.Name); // keep list of unique reasons so we dont duplicate chips also used by modal
    
                                // Add chip for each reason
                                var $chip = $('<div class="chip">' + reason.Name + '</div>');
                                $chip.click((e) => {
    
                                    var $e = $(e.currentTarget);
                                    $("#divertListRow div:contains(" + $e.text() + ")")[0].scrollIntoView();
                                })
    
                                $("#divertChipList").append($chip);
                            }
                        }
                    }
    
                    // Build card for divert if it has matching reasons
                    if (divertReasons) {
    
                        visibleDiverts++;
                        $("#divertLocationName").text(divert.LocationName.toUpperCase());
                        divertReasons = divertReasons.substring(0, divertReasons.length - 3);
    
                        if (!divert.EndDate) {
                            divert.EndDate = "N/A";
                        }
    
                        var $divertRow = $('<div class="row"></div>');
    
                        $divertRow.append('<div class="row divertHeader">' + divertReasons + '<div>');
    
                        var $timeRow = $('<div class="row"></div>');
                        $timeRow.append('<div class="col s6"><i class="icon-clock icon-18"></i><span class="divertLabel">Starts:</span><span class="divertValue">' + divert.StartDate + '</span></div>');
                        $timeRow.append('<div class="col s6"><span class="divertLabel">Ends:</span><span class="divertValue">' + divert.EndDate + '</span></div>');
                        $divertRow.append($timeRow);
    
                        if (divert.Comments) {
                            $divertRow.append('<div class="row divertComments">' + divert.Comments + '<div>');
                        }
        
                        $("#divertListRow").append($divertRow);
                    }
                }
    
                // if we have divert that matches selected protocol show divert panel
                if (visibleDiverts > 0) {
    
                    // Show chips
                    if (visibleDiverts > 1) {
                        $("#divertChipsRow").show();
                    }
                    else {
                        $("#divertChipsRow").hide();
                    }
    
                    // Update modal
                    $("#divert_modal_msg").text("You will procced to " + divert.LocationName + ", which has the follow diverts:");
                    for (var k = 0; k < allReasons.length; k++) {
    
                        if (k % 2 == 0) {
                            var $modalRow = $('<div class="row"></div>');
                            $("#divert_modal_reasons").append($modalRow);
                        }
    
                        $modalRow.append('<div class="col s6">- ' + allReasons[k] + '</div>');
                    }
    
                    ShowDivertPanel();
                }
                else {
                    HideDivertPanel();
                }
            }
    
            function ClearDiverts() {
    
                // clear cached diverts
                var currentTab = GetCurrentTab();
                $("#" + currentTab).removeData("diverts");
                HideDivertPanel();
            }
    
            function ShowDivertPanel() {
    
                // Update html to not shrink when divert panel is shown
                $(".Flex-Form-Diverts").show();
                $(".Flex-Form-MainContent > div").css("margin-right", "20px");
                $(".Flex-Form-MainContent > .col > .row > .s2").removeClass("s2").addClass("s4");
                $(".Flex-Form-MainContent > .col > .row > .s6").removeClass("s6").addClass("s12");
                $(".Flex-Form-MainContent > .col > .row > .row .s8").removeClass("s8").addClass("s12");
                $(".Flex-Form-MainContent .tab.s2").removeClass("s2").addClass("s4");
                $("#addresstab .input-field.s2").removeClass("s2").addClass("s3");
                $("#addresstab .input-field.s4").removeClass("s4").addClass("s6");
                $('.tabs').tabs();
            }
    
            function HideDivertPanel() {
    
                // Update html to not grow when divert panel is hidden
                $(".Flex-Form-Diverts").hide();
                $(".Flex-Form-MainContent > div").css("margin-right", "41px");
                $(".Flex-Form-MainContent > .col > .row > .s4").removeClass("s4").addClass("s2");
                $(".Flex-Form-MainContent > .col > .row > .s12").removeClass("s12").addClass("s6");
                $(".Flex-Form-MainContent > .col > .row > .row .s12").removeClass("s12").addClass("s8");
                $(".Flex-Form-MainContent .tab.s4").removeClass("s4").addClass("s2");
                $("#addresstab .input-field.s3").removeClass("s3").addClass("s2");
                $("#addresstab .input-field.s6").removeClass("s6").addClass("s4");
                $('.tabs').tabs();
            }
    
            function LocationSelected(value) {
    
                if (value) {
                    // if a different location is selected rerun query
                    if (value != $("#Form").data("lastQueriedLocation")) {
                        GetFacilityDiverts(value);
                        $("#Form").data("selectedTabForLastQuery", GetCurrentTab());
    
                        // always clear diverts when requesting diverts for a new location
                        ClearDiverts();
                    }    
                }
    
                // if selecting an address without a value we still want to invalidate previous queries
                $("#Form").data("lastQueriedLocation", value);            
            }
    
            function LocationCleared() {
    
                // clear last queried location when clearing location so that outstanding divert request are ignored
                $("#Form").data("lastQueriedLocation", "");
                ClearDiverts();
            }
    
            function AfterTabChanged(value) {
    
                // each tab can have different cached set of diverts for the location selected under that address.
                // reload panel after changing tab
                LoadDiverts();
            }
    
            async function ShowConfirm($form) {
    
                // if divert panel is visible show modal for confirmation
                var allowSubmit = true;
                if ($(".Flex-Form-Diverts").is(":visible")) {
                    allowSubmit = await openModal('PROCEED TO LOCATION?');
                    if (allowSubmit) {
                        // if the select confim then updat this flag to allow the server to bypass validation of divert status
                        $("#transportationwarning").val("Warned");
                    }
                }
    
                if (allowSubmit) {
    
                    $(':disabled').each(function (e) {
                        $(this).removeAttr('disabled');
                    })
    
                    // If we are submitting with the address tab selected dont submit a location.
                    // This can cause a bug were the wrong location is passed to the business layer
                    var currentTab = GetCurrentTab();
                    if (currentTab != "locationtab") {
                        $("#location").val("");
                    }
    
                    var values = $form.serialize();
                    SubmitQuery(values, $form.attr('action'));
                }
            }
</head>
<body class="FlexBody">
    <div class="header">
        <div class="row">
            <div class="s12">
                <div class="valign-wrapper">
                    <h5 style="margin-left: 20px;">TRANSPORT</h5>
                </div>
            </div>
        </div>
    </div>
    <form class="Flex-Form" action="TransportQuery.aspx?queryfile=person.qry" method="post" id="Form" name="Form">
        <div class="Flex-Form-MainContent">
            <div class="col m8" style="margin-top:20px">
                <div class="row">
                    <div class="input-field col s2">
                        <input name="currentodometer" id="currentodometer" type="number" step=".1" maxlength="9" placeholder=""
                               oninput="return lengthCheck(this)"
                               onkeydown="return decimalCheck(this, event)" required>
                        <label for="currentodometer" class="active">Current Odometer</label>
                    </div>
                    <div class="input-field col s2" type="selectlist" id="protocolvals" name="protocolvals">
                        <label for="transportationprotocol">Transport Protocol</label>
                    </div>
                    <div class="input-field col s2" type="selectlist" id="priorityvals" name="priorityvals">
                        <label for="transportationpriority">Transport Priority</label>
                    </div>
                </div>
                <div class="row">
                    <div class="input-field col s2">
                        <input name="PatientsTransported" id="PatientsTransported" type="number" value="1" min="1" maxlength="10" placeholder="" class="input-validate-transported"
                               oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">
                        <label for="PatientsTransported" class="active">Number Transported</label>
                    </div>

I’ve tried looking for solutions, unfortunately all i can find are solutions where the values are laid out in the html and set as selected there. The form is not complete due to the character limit, but i attempted to include the relevant sections

How to pass an asynchronous handler function to a route

I am coding an express API and I want to use asynchronous functions in app.use() and app.get() methods. When I do so I get an error.

My router:

   import { Router } from "express";
   import { register } from "../controllers/auth";
   const authRouter = Router();

   authRouter.post("/register", register);

   export default authRouter;

The error:

    No overload matches this call.
    The last overload gave the following error.
    Argument of type '(req: Request<ParamsDictionary, any, any, ParsedQs,     Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction)     => Promise<...>' is not assignable to parameter of type 'Application<Record<string,     any>>'.
    Type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>,     res: Response<any, Record<string, any>>, next: NextFunction) => Promise<...>' is     missing the following properties from type 'Application<Record<string, any>>':     init, defaultConfiguration, engine, set, and 63 more.ts(2769)
    index.d.ts(168, 5): The last overload is declared here.

I found a way to manage it by wrapping my async handler in a normal function but I am not sure if it is the right way to do :

   authRouter.post("/register", (req, res, next) => {
   register(req, res, next);
});

In my memory I never add problems passing async methods as handler for my routes or as middleware.

How to check if class exists after page load?

I want to target sdf-carousel-item that has an ID of “first” and only when class of “active” is present. However this is a carousel – so when the first slide is showing, the class of “active” is added. when someone goes to slide 2 for example, the “active” gets removed on the first slide, and added to the second slide.

To start I just want to target the “active” and this is what so far (check code snippet).

const carouselModal = document.querySelector("sdf-carousel-item");
if(carouselModal.matches("#first.active")){
  console.log("carousel one is active");

  }
<sdf-carousel-item id="first" style="height: auto; display: block; width: 50%;" role="group" aria-roledescription="slide" aria-label="1 of 2" class="first-in-page last-in-page active">test one</sdf-carousel-item>

Yes on the code snippet it works great. but I think the problem is that this class of “active” is added AFTER page load, so it’s not working when i try it inside the actual page.

SO the, I tried to wrap the entire function around window.addEventListener("load", function(){} but that didn’t do anything. Any reason why that didn’t work? Is there a better alternative?

Error en la solicitud Matrix: cURL error 60: SSL certificate problem: unable to get local issuer certificate

good afternoon. I’m having a problem, as described in the title. Well, when I try to make a request, sometimes when I perform a composer update or other actions… I get error curl 60. SSL issues.

I’ve reviewed many posts about this problem and tried several solutions. None of them worked for me, except for one. It is: Add this line in the request: withOptions([‘verify’ => false])

I mean, I haven’t found a solution for Composer update. So, it only works as an emergency measure for requests. Now, what I’ve tried:

Change the certificate cacert.pem

I made sure the php.ini file had the correct path.

I attach photos of the folder directory, in addition to the php.ini

You had it like this in php.ini, but I promise you I’ve put 20 different paths, all pointing to the file. And nothing.

curl.cainfo = "C:laragonbinphpphp-8.3.7-Win32-vs16-x64extrassslcacert.pem"
[openssl]
; The location of a Certificate Authority (CA) file on the local filesystem
; to use when verifying the identity of SSL/TLS peers. Most users should
; not specify a value for this directive as PHP will attempt to use the
; OS-managed cert stores in its absence. If specified, this value may still
; be overridden on a per-stream basis via the "cafile" SSL stream context
; option.
;openssl.cafile

; If openssl.cafile is not specified or if the CA file is not found, the
; directory pointed to by openssl.capath is searched for a suitable
; certificate. This value must be a correctly hashed certificate directory.
; Most users should not specify a value for this directive as PHP will
; attempt to use the OS-managed cert stores in its absence. If specified,
; this value may still be overridden on a per-stream basis via the "capath"
; SSL stream context option.
;openssl.capath=


The openssl.cafile, which I mentioned before the problem arose, was commented out. I tried uncommenting it, adding the path, and testing whether adding the same path worked, and it didn’t work either. I also tried some commands disabling composer verification in an SSL project, which I honestly don’t remember which commands they were.

What do you read, or if you need any other files, I can provide them without any problem. The truth is that this problem is affecting me a lot and if you could help me, I would appreciate it.

How to fix curl error 60

How to override styles of an overlay (.ui-widget-overlay) generated by PrimeNG outside the component?

I need to apply specific opacity and background color to a p-sidebar component from PrimeNG. I can achieve this globally by adding the following to styles.scss:

body .ui-widget-overlay {
  opacity: 0.5 !important;
  background-color: #333 !important;
}

However, this approach affects every p-sidebar in the application, which is not what I want. I need to apply these styles only to a specific component.

I’ve already tried several approaches, such as:

Using ::ng-deep to target the overlay.

Using :host to scope the styles to the component.

Applying IDs and classes to the p-sidebar.

The issue seems to be that whenever I open the p-sidebar, a new div with the class .ui-widget-overlay is rendered at the body level, outside my component’s DOM. This makes it impossible for the component to directly control or style this overlay.

html of the body of the app

Should I just create a custom component specifically for this, or is there a solution?

How to embed gtag GA4 event in a div when loaded?

We use GTM for our GA4 config tag and events.
However, the CRM site doesn’t integrate with GA4. While we have our GTM container installed on it, it hasn’t been super reliable to look for the visibility of a thank you message after submitting an important form. The DBA configures the thank you messages and I recently learned that we can include javascript and html in those thank you messages, which would be more reliable.

How would I get a GA4 event to fire when the message is displayed on the page (whether or not the user scrolls to see it))? Do I just embed the gtag(‘event’,’eventname’); code in tags within the message ? Does it need any other code to trigger it? Could there be timing issues if the GA4 config tag isn’t fired first from the GTM container (it’s set to trigger on Initialization)?

I’m not a webdev or programmer, so looking for basic info.

To test it out, I edited a test page on our wordpress site and added:
<script> gtag('event', 'test_inline_ga_event'); </script>
into a random content . But in the console it says “Uncaught ReferenceError: gtag is not defined.” Timing issue with the GA4 config tag?
Because I see other GTAG commands (from gtm) firing just fine afterwards. How can I be sure to only fire the command after the GA4 config tag has run?

Thanks!
Jannette

Why is my JavaScript Promise not resolving as expected?

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data received');
        }, 1000);
    });
}

const result = fetchData();
console.log(result); // Why does this log a Promise instead of 'Data received'?

result.then(data => {
    console.log(data); // Why is this delayed?
});

Why does console.log(result); log a Promise instead of the actual data?
Why is the .then() block executed later instead of immediately?
How can I properly handle the resolved data in a synchronous-like manner?
What I tried:

Logging result immediately after calling fetchData()
Wrapping fetchData() inside an async function and using await

Function doesn’t sort [closed]

Trying to see if fn function will sort inside filter function.
It is print out out for me the whole array.

// Exampel data
const numbs = [7, 100, 107, 4000, 6, 73];

// Main function
var filter = function (arr) {
  let fill = [];
  for (let i = 0; i < arr.length; i++) {
    if (fn(arr[i])) {
      console.log("Before pushing to fill: "+arr[i])
      fill.push(arr[i])
      console.log("After pushing to fill: ")
    }
  }
  
  return fill;
};

console.log("From the filter function: "+filter(numbs));

// Sub function
function fn (number_from_arr) {
  let res=[];
  for (let i = 0; i < number_from_arr.length; i++) {
    if (number_from_arr[i] > 100) {
      res = number_from_arr[i] 
    }
  }

  return res;
}

React Children.map replace svg

I would like to create a generic component that replaces the svgs inside a Button (shadcn) with a LoaderIcon (lucid-react). So sometimes it works, but sometimes not.

When it doesn’t work, it is mostly because child.type resolves to this :

error message

Here is my current component :

export function ConfirmedActionButton<T>({
  action,
  actionParams,
  children,
  confirmOptions = {},
  onSuccess,
  ...props
}: ButtonProps & {
  action: (data: T) => Promise<FormActionState>
  actionParams: T
  confirmOptions?: ConfirmOptions
  onSuccess?: () => void
}) {
  const [isPending, startTransition] = useTransition()

  const onConfirm = async () => {
    const { ok } = await safeConfirm(confirmOptions)

    if (ok) {
      startTransition(async () => {
        const res = await action(actionParams)
        if (res?.error) {
          toast.error("Une erreur est survenue.", { description: res.error })
        }

        if (res?.success) {
          toast.success(res?.success)
          onSuccess?.()
        }
      })
    }
  }

  const filteredChildren = useMemo(
    () =>
      Children.map(children, (child) => {
        if (isValidElement(child) && child.type === "svg") {
          return isPending ? <Loader2Icon className="animate-spin" /> : child
        }

        return child
      }),
    [children, isPending]
  )

  return (
    <Button {...props} onClick={onConfirm} disabled={isPending}>
      {filteredChildren}
    </Button>
  )
}

the components usage :

<ConfirmedActionButton
  className="absolute top-1.5 right-1.5 text-destructive rounded-full p-1"
  size={"icon"}
  variant={"ghost"}
  action={deleteAction}
  actionParams={asset.id}
>
  <span className="sr-only">Delete asset</span>
  <TrashIcon className="duration-200 ease-in-out" />
</ConfirmedActionButton>

Svelte: Expected behavior on change in phone orientation?

I have an app that uses element.ScrollIntoView(). I’ve been using the browser developer tools to see what it looks like on a phone. Unfortunately, I’ve just noticed that when I change phone orientation, the app navigates to the top of the current page–losing your current position on the page.

Is this the expected behavior, or have I done something wrong?

How to target ID on a specific tag in JS?

I am trying to target a specific ID on the sdf-carousel-item tag but it’s giving me an error for some reason. Here is the code:

    const carouselModal = document.querySelector("sdf-carousel-item");
    const carouselSlideOne = carouselModal.querySelector("#first");
    if (carouselSlideOne){
      console.log("carousel slide one is here");
    } else {console.log("carousel slide one not here.")}
<sdf-carousel-item id="first" style="height: auto; display: block; width: 50%;" role="group" aria-roledescription="slide" aria-label="1 of 2" class="first-in-page last-in-page active">test one</sdf-carousel-item>

Here is what I tried:

const carouselModal = document.querySelector("sdf-carousel-item");
const carouselSlideOne = carouselModal.querySelector("#first");
if (carouselSlideOne){
  console.log("carousel slide one is here");
} else {console.log("carousel slide one not here.")}

I keep getting the “I’m not here” messaging which I can’t understand why, since it’s on the same div tag as carouselModal. I’m new to JS so maybe I missed something obvious?

What cookies are set by Google Maps?

I am working on integrating the Google Maps JavaScript API into our website and need to understand which cookies (if any) are set by the API. This is important for configuring our privacy settings and ensuring proper cookie consent management.

What We’ve Observed So Far:

  • We see multiple Google-related cookies (NID, SID, APISID, SAPISID, etc.) appearing in DevTools → Application → Cookies after a user interacts with the map (e.g., searching for a location).

  • Our site also uses Google reCAPTCHA, which loads from google.com, making it unclear whether these cookies are set by Google Maps JavaScript API or reCAPTCHA.

  • In Incognito mode, these cookies do not appear, suggesting they might be third-party cookies.

Questions:

  1. Which specific cookies are set by the Google Maps JavaScript API?

  2. Under what conditions are these cookies created (e.g., map load, user interaction, API feature usage like Places API)?