Selectize won’t open when focus

I tried to make a simple Select with selectize plugin, with some custom functionality with images on dropdown, but it’s effect default behavior when i click the select it wont open the dropdown before i type something on it, i’ve been tried to use openOnFocus: true but still wont open. This is my whole code for the selectize:

 $(document).ready(function() {
        let courierList = @json($brandList);
        var imgPath_brand = "{{ asset('images/pos_brand') }}";
        let selectizeControl = $('#couriers').selectize({
           valueField: 'brand_code',
           labelField: 'brand_name',
           searchField: 'brand_name',
           options: courierList,
           placeholder: 'Select a brand...',
           allowEmptyOption: true,
           openOnFocus: true,
           render: {
              option: function(item, escape) {
                 return '<div class="px-2 my-2">' +
                    '<img class="selectize-image" src="' + imgPath_brand + '/' + escape(item.logo) + '" alt="' + escape(item.brand_name) + '"' +
                    '<span>' + escape(item.brand_name) + '</span>' +
                    '</div>';
              },
              item: function(item, escape) {
                 return '<div class="px-2">' +
                    '<img class="selectize-image" src="' + imgPath_brand + '/' + escape(item.logo) + '" alt="' + escape(item.brand_name) + '"' +
                    '<span>' + escape(item.brand_name) + '</span>' +
                    '</div>';
              }
           }
        });
     });

Fyi, there is no error on console log

How to Efficiently Fetch All NPM Packages from the NPM Registry API Without Timeout Issues?

I am trying to fetch all the packages from the npm package manager, specifically all the JavaScript dependencies available. I discovered the following API:

https://skimdb.npmjs.com/registry/_all_docs

This API returns all the npm packages in a single response. However, given the enormous size of the dataset (over 3.4 million packages as of now), I encounter a timeout error before receiving a response.

To handle this, I tried fetching the data in chunks, which worked initially. However, after retrieving about 1.3 million packages, I encountered the error:

“Response Ended Prematurely.”

I also attempted using the limit and skip parameters, like this:

https://skimdb.npmjs.com/registry/_all_docs?skip=10&limit=1000

But this method is quite slow, and the skip parameter seems unreliable. Based on my testing, after skipping around 60,000 to 65,000 packages, the API starts to fail and eventually results in a gateway timeout error.

Is there any efficient way to fetch all the npm packages without running into these timeout issues? Any help or guidance would be greatly appreciated.

Supabase Local Function on JWT creation

I have a supabase project that is being used for Auth management as well as some simple storage scenarios. I have a hook that runs when a JWT is created and it grabs the user role (from the user_roles table, matched on user uuid) and adds it to the JWT payload. This is read on the frontend JS to for dynamic access control based on what the user role is. This has been working fine on the production supabase application but when I try and set this up on my local supabase instance the JWT is empty.

The database migration grabs the schema and I seed the local db with some data. I can see my custom_access_token_hook function in my local instance. Is there a way to have the hook in my local so that it runs when a JWT is created and I can get my user roles?

Here is the custom_access_token_hook:


  declare
    claims jsonb;
    user_role public.app_role;
  begin
    -- Check if the user is marked as admin in the profiles table
    select role into user_role from public.user_roles where user_id = (event->>'user_id')::uuid;

    claims := event->'claims';

    if user_role is not null then
      -- Set the claim
      claims := jsonb_set(claims, '{user_role}', to_jsonb(user_role));
    else
      claims := jsonb_set(claims, '{user_role}', 'null');
    end if;

    -- Update the 'claims' object in the original event
    event := jsonb_set(event, '{claims}', claims);

    -- Return the modified or original event
    return event;
  end;

Combine object in JSON array based on date range

I am writing a tool for my non-tech users. They are not familiar with JSON so I build this tool so that they can easily interact with from the UI. The generated JSON will be used to processing the business from backend code.

The JSON array structure is as follow:

[
  {
    "groupCode": "Minimalism",
    "dateRangeFrom": "01/09/2024",
    "dateRangeTo": "30/09/2024",
    "fulfillment": {
      "slotNames": [
        "10:00",
        "20:00",
      ],
      "slotIds": [1,2,3]
    }
  }
]

I got a problem when I want to optimize the array from many object like above. dateRangeFrom and dateRangeTo will initiate a range. I don’t want to have any range that overlaps each other. E.g:
If original JSON is as above, and via my UI I provide them, they added a new JSON object as follow:

  {
    "groupCode": "Minimalism",
    "dateRangeFrom": "01/09/2024",
    "dateRangeTo": "30/10/2024",
    "fulfillment": {
      "slotNames": [
        "10:00",
        "20:00",
        "21:00"
      ],
      "slotIds": [4]
    }
  }

I want the output as follow:

[
  {
    "groupCode": "Minimalism",
    "dateRangeFrom": "01/09/2024",
    "dateRangeTo": "30/09/2024",
    "fulfillment": {
      "slotNames": [
        "10:00",
        "20:00",
        "21:00" //Added one from 2nd object
      ],
      "slotIds": [1,2,3,4] //Added 4 from 2nd object
    }
  },
  {
    "groupCode": "Minimalism",
    "dateRangeFrom": "01/10/2024",
    "dateRangeTo": "30/10/2024",
    "fulfillment": {
      "slotNames": [
        "10:00",
        "20:00",
        "21:00"
      ],
      "slotIds": [4]
    }
  }
]

Any idea how can I do that?

The current code creates segments when data is removed from a date range. However, it doesn’t detect overlaps when a new object is added, so it can’t combine or extract data into segments properly. I need to ensure no overlapping date ranges to avoid issues when the client modifies data.

I want to add a function that checks the entire JSON array. If a newly added object has overlapping date ranges with existing ones, it should:

  • Add the “fulfillment” data from the new object to the existing one with the overlapping date range.

  • Remove the overlapping date range from the new object, keeping only the non-overlapping dates.

//Optimize & Organize JSON data
function optimizeJSONData(inputJSON) {
    const { parse, isAfter, addDays, format } = dateFns;

    //Remove empty slot Range (No Fulfillment SlotNames and SlotIds)
    let filteredArray = inputJSON.filter(item =>
        item.fulfillment.slotNames.length > 0 || item.fulfillment.slotIds.length > 0
    );

    // Remove Duplicated SlotNames & Duplicated SlotIds
    filteredArray = filteredArray.map(item => ({
        ...item,
        fulfillment: {
            slotNames: [...new Set(item.fulfillment.slotNames)].sort((a, b) => {
    const convertToMinutes = time => {
        const [hours, minutes] = time.split(':').map(Number);
        return hours * 60 + minutes;
    };

    return convertToMinutes(a) - convertToMinutes(b);
}),
            slotIds: [...new Set(item.fulfillment.slotIds)].sort((a, b) => a - b)
        }
    }));

    //Combine JSON
    console.log("Removed Empty: ", filteredArray);
    // Convert date strings to Date objects
    const processedData = filteredArray.map(item => ({
        ...item,
        dateRangeFrom: parse(item.dateRangeFrom, 'dd/MM/yyyy', new Date()),
        dateRangeTo: parse(item.dateRangeTo, 'dd/MM/yyyy', new Date())
    }));

    // Group by 'groupCode' and 'fulfillment'
    const grouped = _.groupBy(processedData, item => `${item.groupCode}-${JSON.stringify(item.fulfillment)}`);

    const result = _.flatMap(grouped, (group) => {
        const sortedGroup = _.sortBy(group, ['dateRangeFrom']);

        // Create a shifted start date array
        const shiftedStartDate = sortedGroup.map((d, i) => i === 0 ? null : addDays(sortedGroup[i - 1].dateRangeTo, 1));

        // Calculate condition for merging intervals
        const condition = sortedGroup.map((d, i) => i === 0 ? true : isAfter(d.dateRangeFrom, shiftedStartDate[i]) === false);

        // Calculate cumulative sum (group ID)
        const cumsum = condition.reduce((acc, val) => {
            acc.push((acc[acc.length - 1] || 0) + (val ? 0 : 1));
            return acc;
        }, []);

        // Add 'group' to the sortedGroup
        const groupedByCumsum = _.groupBy(sortedGroup.map((d, i) => ({ ...d, group: cumsum[i] })), 'group');

        // Aggregate start_date and end_date
        return _.map(groupedByCumsum, (items) => ({
            groupCode: items[0].groupCode,
            fulfillment: items[0].fulfillment,
            dateRangeFrom: format(_.minBy(items, 'dateRangeFrom').dateRangeFrom, 'dd/MM/yyyy'),
            dateRangeTo: format(_.maxBy(items, 'dateRangeTo').dateRangeTo, 'dd/MM/yyyy')
        }));
    });
    console.log("Optimized Result: ", result);
    return result;
}

React Hook Form: form.reset works but form.resetField doesn’t

asset.attributes can change externally, so I need to let the React Hook Form know:

useEffect(() => {
  if (asset) {
    const initialAttrs = Object.entries(asset.attributes || {}).map(
      ([key, value]) => ({
        key,
        value: value ? String(value) : '',
      }),
    );

    setAttrs(initialAttrs);

    form.reset({
      name: asset.name || '',
      description: asset.description || '',
      fields: asset.fields?.[0]?.id || '',
      persons: asset.persons?.[0]?.id || '',
      attributes: asset.attributes || {},
      tags: asset.tags || [],
      contentAssets: asset.contentAssets || [],
      files: [], // Reset files if necessary
    });
  }
}, [asset, form]);

This effectively resets the form. However, this way I’m repeating the default values twice (I’m setting the default values before the useEffect()). So I thought I should just reset asset.attributes:

form.resetField('attributes', {
  defaultValue: asset.attributes || {},
});

However, for some reason, asset.attributes is not being reset like it was with form.reset(). What could be the issue here?

How to put JavaScript files somewhere other than /static for a Flask app running on IIS?

I am trying to run a Flask server using IIS and load JavaScript files from somewhere other than /static since I want to organize my project on a per-page basis rather than dumping everything into /static and /templates. Previous questions such as this one don’t solve my question as they deal with just loading the JavaScript from /static, which is not what I am looking for. Neither this or this worked for me.

I am not using jQuery and my index.html is in /, not /templates

The index.html and index.js files contain the same information for both the server run by Flask directly and the one run with IIS. The IIS server is running on 192.168.1.87:80, the host machine’s IP address.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div style="width: 300px; height: 300px; background-color: red;" id="testDiv"></div>

    <!--<script src="index.js"></script>-->
    <!-- <script src="/static/index.js"></script> -->
    <!-- <script src="/stuff/index.js"></script> -->
    <!-- <script src="{{ url_for('static', filename='index.js') }}"></script> -->
    <!-- <script src="/index.js"></script> -->
     <!--<script src="../stuff/index.js"></script> -->
    <script src="../index.js"></script>
</body>
</html>

index.js

document.getElementById("testDiv").style.backgroundColor = "blue";

app.py run with just Flask

from flask import Flask, send_from_directory

app = Flask(__name__, static_folder="stuff")
#app = Flask(__name__, static_folder="")
#app = Flask(__name__)

@app.route("/")
def index():
    return send_from_directory("", "index.html")

if __name__ == '__main__':
    app.run()

app.py run with the IIS server

from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route("/")
def index():
   return send_from_directory("", "index.html")

if __name__ == '__main__':
   app.run(host="192.168.1.87", port=80)

All errors returned by website run by IIS are GET http://192.168.1.87/index.js net::ERR_ABORTED 404 (NOT FOUND) and all error from the standalone Flask server are 404s. All errors relate to the script call in index.html.

I have not gotten send_from_directory or url_for to work with the JavaScript on either the Flask or IIS servers, which were recommended here (in both cases, the server returns a 404).

On the standalone Flask server, having static_folder="stuff" and the script call in index.html be <script src="/stuff/index.js"></script> correctly loads the JavaScript from /stuff and having static_folder be anything other than “stuff” with a script call in index.html be <script src="/static/index.js"></script> correctly loads the JavaScript from /static, but having static_folder="stuff" and the script call be <script src="/static/index.js"></script> and vice versa causes a 404 error.

Using <script src="/static/index.js"></script> with static_folder not set to “stuff” on the IIS server correctly loads the JavaScript from /static, but does not work when the same setup as above is done with /stuff.

Unable to save Tag name on Laravel and Vue Js Project

working with Laravel 10 and Vue Js 3 and I need save Tag Name on the table. I have following AdminController

 public function addTag(Request $request){
       return Tag::create([
            'tagName' => $request->tagName
        ]);
    }

web.php

Route::post('app/create_tag', [AdminController::class, 'addTag']);

and tags.vue file is

<Modal v-model="addModal" title="Add Tag" :mask-closable="false" :closable="false">
                <Input v-model="data.tagName" placeholder="Add Tag Name" style="width: 300px" />

                <div slot="footer">
                    <Button type="default" @click="addModal=false">Close</Button>
                    <Button type="primary" @click="addTag" :disabled="isAdding" :loading="isAdding">{{ isAdding ? 'Adding..' : 'Add tag' }}</Button>
                </div>
            </Modal>

<script>
methods : {
        async addTag(){
            if(this.data.tagName.trim()=='') return this.e('Tag name is required')
            const res = await this.callApi('post', 'app/create_tag', this.data)
            if(res.status===200){
                
                this.tags.unshift(res.data)
                this.s('Tag has been added sucessfully!')
                this.addModal = false
                this.data.tagName = ''
            } else {
                this.swr()
            }
        }
    },

</script>

but when I try to save tag name on the table I got following error msg on the inspect of the browser

[Vue warn]: Unhandled error during execution of component event handler 
  at <Button type="primary" onClick=fn<bound addTag> disabled=false  ... > 
  at <BaseTransition onAfterLeave=fn<bound animationFinish> appear=false persisted=false  ... > 
  at <Transition name="ease" onAfterLeave=fn<bound animationFinish> > 
  at <Modal modelValue=true onUpdate:modelValue=fn title="Add Tag"  ... > 
  at <Tags onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< 

how could I fix this problem?

my common.js

export default {
    data(){
        return {

        }
    },

    methods:{
         async callApi(method, url, dataObj ){
            try {
              return await axios({
                    method: method,
                    url: url,
                    data: dataObj
                });
            } catch (e) {
                
                return e.response
            }
        }
}

Parallax effect in hero section (CSS)

I am trying apply parallax effect on website what I am currently working, but it does not work for me. I have uploaded project here: https://motorew-web.vercel.app/ , please check.
Look .hero section on website, I want apply parallax effect for moving motorbike (.hero .after).
Code what I tried :

main {
height: 100vh;
  perspective: 1px;
  transform-style: preserve-3d;
  overflow-x: hidden;
  overflow-y: auto;
}


.hero {
transform-style: preserve-3d;
}


.hero .after {
transform: translateZ(-1px) scale(2);
}

how to tell kafka client to consume messages in order they arrived?

I use kafka client 2.4.4 to consume messages

const { Kafka, logLevel } = require("kafkajs")
const kafka = new Kafka(config)
const consumer = kafka.consumer({ groupId: "Default" })

await consumer.connect()
await consumer.subscribe({ topic, fromBeginning: true })

await consumer.run({
    autoCommitThreshold: 10,
    eachMessage: async ({ topic, partition, message, heartbeat, pause }) => {
       await processMessage(message)
    .....

but looks like consumer picks messages in random order not the order they arrived.
Is there any client/consumer option to tell client read it in proper order?

Looks like I can use following method:

eachBatch: async ({ batch

then extract each message and sort them by timestamp but it’s not really right approach

How to stop showing inactive slides in vue swiper?

I’m trying to make this https://stories-slider.uiinitiative.com/ slider for stories, but it doesn’t work.

The first problem is that after changing the parent slide, the child slider, the previous parent, everything works smoothly and when I go back, the slides actively change instead of pausing after I go back to the parent slide.

The second problem is that I can’t understand how, when returning back to the previous parent slide in the StoriesWrapper.vue component, reload the active slide in the child StoriesIten.vue

And the third problem, I can’t figure out how, after moving to the last element of the child slider or the first, after clicking again, go to either the previous parent slide or the next parent slide

StoriesWrapper.vue

<script setup>
import { ref } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Pagination, Autoplay, EffectCube } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/effect-cube';

const mainSwiperRef = ref(null);

const activeMainSlideIndex = ref(1);

const handleMainSwiperSlideChange = (swiper) => {
  activeMainSlideIndex.value = swiper.activeIndex + 1;
};

const handleSwiperEndSlide = (parentIndex, swiper) => {
  if (activeMainSlideIndex.value === parentIndex) {
    const mainSwiper = mainSwiperRef.value?.swiper;

    if (swiper.isEnd && !mainSwiper.isEnd) {
      mainSwiper.slideNext();
    } else if (swiper.isBeginning) {
      mainSwiper.slidePrev();
    }
    console.log(`Swiper ${parentIndex} ended slide change`, swiper);
  }
};

const handleMainSwiperInit = (swiper) => {
  mainSwiperRef.value = { swiper };
};
</script>

<template>
  <swiper
    ref="mainSwiperRef"
    :effect="'cube'"
    :cube-effect="{
      shadow: false,
      slideShadows: false,
      shadowOffset: 0,
      shadowScale: 0,
    }"
    :slides-per-view="1"
    :space-between="0"
    :loop="false"
    :modules="[Pagination, Autoplay, EffectCube]"
    class="!h-full main-swiper"
    @swiper="handleMainSwiperInit"
    @slide-change="handleMainSwiperSlideChange"
  >
    <swiper-slide
      v-for="mainIndex in 2"
      :key="mainIndex"
      v-slot="{ isActive }"
      class="relative !h-[60vh]"
    >
      <StoriesItem
        :parent-index="mainIndex"
        :on-swiper-end="
          (parentIndex, swiper) => handleSwiperEndSlide(parentIndex, swiper)
        "
        :is-active="isActive"
      />
    </swiper-slide>
  </swiper>
</template>

StoriesItem.vue

<script setup lang="ts">
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Pagination, Autoplay, Navigation } from 'swiper/modules';
import 'swiper/css';

const props = defineProps<{
  parentIndex: number;
  onSwiperEnd: Function;
  isActive: boolean;
}>();

const swiperRef = ref();

const isFirstItem = ref(false);

const handleSwiperSlideChange = (swiper) => {
  if (props.isActive && typeof props.onSwiperEnd === 'function') {
    if (swiper.isEnd) {
      swiper.autoplay.stop();
      setTimeout(() => {
        console.log('Время показа последнего слайда закончилось');
        props.onSwiperEnd(props.parentIndex, swiper);
      }, swiper.params.autoplay.delay);
    }

    if (swiper.isBeginning && swiper.activeIndex === 0 && !isFirstItem.value) {
      isFirstItem.value = true;
      swiper.autoplay.start();
    } else if (
      swiper.isBeginning &&
      swiper.activeIndex === 0 &&
      isFirstItem.value
    ) {
      isFirstItem.value = false;
      props.onSwiperEnd(props.parentIndex, swiper);
    }
  }
};

const handleMainSwiperInit = (swiper) => {
  swiperRef.value = { swiper };
};

watch(
  () => [props.isActive, swiperRef.value],
  (newIsActive) => {
    if (swiperRef.value?.swiper) {
      if (newIsActive) {
        swiperRef.value?.swiper.autoplay.stop();
        swiperRef.value?.swiper.slideTo(swiperRef.value?.swiper.activeIndex, 0);
        swiperRef.value?.swiper.autoplay.start();
      } else {
        swiperRef.value?.swiper.autoplay.stop();
      }
    }
  },
  {
    immediate: true
  }
);
</script>

<template>
  <div class="relative w-full h-full">
    <div
      class="absolute right-0 inset-y-0 w-1/2 cursor-pointer z-[3]"
      :class="`story__next_${props.parentIndex}`"
    ></div>
    <div
      class="absolute left-0 inset-y-0 w-1/2 cursor-pointer z-[3]"
      :class="`story__prev_${props.parentIndex}`"
    ></div>

    <div
      class="absolute top-4 flex w-full gap-6 px-6 z-[4]"
      :class="`story__pagination_${props.parentIndex}`"
    ></div>

    <swiper
      ref="swiperRef"
      :slides-per-view="1"
      :space-between="0"
      :watch-slides-progress="false"
      :modules="[Pagination, Autoplay, Navigation]"
      :autoplay="{
        delay: 3900,
        disableOnInteraction: false,
      }"
      :loop="false"
      class="sub-swiper !h-full"
      :navigation="{
        nextEl: `.story__next_${props.parentIndex}`,
        prevEl: `.story__prev_${props.parentIndex}`,
      }"
      :pagination="{
        el: `.story__pagination_${props.parentIndex}`,
        type: 'bullets',
        clickable: true,
        bulletClass: 'swiper-pagination-bullet',
        bulletActiveClass: 'swiper-pagination-bullet-active',
      }"
      @slide-change="handleSwiperSlideChange"
      @swiper="handleMainSwiperInit"
    >
      <swiper-slide
        v-for="subIndex in 4"
        :key="subIndex"
        class="bg-red-400 !h-full"
      >
        <h2>
          {{ "parentIndex_" + props.parentIndex + "_____Slide_" + subIndex }}
        </h2>
      </swiper-slide>
    </swiper>
  </div>
</template>

“x” is not a constructor- PlayWright automating testing beginner

I am learning Playwright. This is what I have so far. Can someone please point out what I am doing wrong? I referred to youtube videos and still unable to see what the mistake is. I appreciate your help!

This is the LoginPage.js

class LoginPage{

    constructor(page){
        this.page=page;
        this.loginInput = 'input[name="username"]';
        this.passwordInput = 'input[name="password"]';
        this.loginButton = '.MuiLoadingButton-root';
    }

    //method

    async logintoWorld(){
        await this.page.fill(this.username, "manager1");
        await this.page.fill(this.password, "myPassword");
        await this.page.click(this.loginButton);
    }
}

export default LoginPage; 

This is the login.spec.js

import {test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';


test('Login to testingworld', async ({ page }) => {
  await page.goto('https://mytestingworld.com/auth/login');
  const myLogin = new LoginPage(page);
  await myLogin.logintoWorld();
});

When I run the test, I get this error:

@
login.spec.js:7
TypeError: _LoginPage.LoginPage is not a constructor

window.onload=null inside constructor not working

Here is what I had:

class A {
  constructor() {
    window.onload = () => {
        this.foo();
        window.onload = null; //this has no effect. Window keeps running foo() 
    }; 
  }
  foo() { console.log("class A"); };
}

The foo() was running every time the window loaded which implies window.onload=null had no effect.

What I tried is:

class A {
  constructor() {}
  foo() { console.log("class A"); };
}
const a = new A();
window.onload = () => {
    a.foo();
    window.onload = null; //this works
}; 

This fixed the problem, but I still have no idea what caused it in the first place.
It probably has something to do with binding the classes to the onload arrow function, but what exactly is happening?

Why My Form Keep Submitting after Page Refresh in Astro Js

I have this written in Astro

if (Astro.request.method === "POST") {
try {
    const contentType = Astro.request.headers.get('content-type');
    if (contentType?.includes('multipart/form-data') || contentType?.includes('application/x-www-form-urlencoded')) {
    const data = await Astro.request.formData();
    const nik = data.get("nik");
    const nama = data.get("nama");
    const tanggalLahir = data.get("tanggalLahir");
    const tempatLahir = data.get("tempatLahir");
    const jenisKelamin = data.get("jenisKelamin");
    const alamatEmail = data.get("alamatEmail");
    const nomorHandphone = data.get("nomorHandphone");
    const ktp = data.get("ktp");
    
    const request = {
        nik,nama,tanggalLahir,tempatLahir,jenisKelamin,alamatEmail,nomorHandphone,ktp
    }

    const requestStringify = JSON.stringify(request)
    console.log(requestStringify)

    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json',
        },
        body: requestStringify,
    });

    const dataJson = await response.json();
    console.log(dataJson);
    
    } else {
    throw new Error('Unsupported Content-Type');
    }
} catch (error) {
    if (error instanceof Error) {
    console.error("Form submission error:", error.message);
    }
}

everytime i reload the page the form keep submitting with this function sort of, with previous values I inserted. anything to prevent the from submitting when the page load or reloaded? thanks in advanced

How to optimize the JavaScript code for better performance?

I’m working on a React application with a large codebase, and I’m experiencing performance issues. What are some best practices to optimize JavaScript code for better web performance?

Specifically, I’m looking for tips on:

  • Code splitting and lazy loading
  • Minifying and compressing code
  • Optimizing DOM manipulation
  • Reducing unnecessary re-renders

Code example:

import React from 'react';
import ReactDOM from 'react-dom';

function App() {
  // Large amount of data being processed here
  const data = [...];
  return (
    <div>
      {data.map((item) => (
        <div key={(link unavailable)}>{item.name}</div>
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

Some specific code changes I try:

  • Use React.lazy to lazy-load components
  • Implement a caching mechanism to reduce repeated computations
  • Use React.memo to memoize components and reduce re-renders
  • Optimize the data.map loop by using a more efficient data structure or caching the results