useState creates infinit loop

Why does assigning the ‘setTimeSlotsList(fetchAPI(day))’ creates inifit loop?

the code flow seems to be working when i just ‘console.log(fetchAPI(day))’ for testing.

     function FormValues () {
      const { values } = useFormikContext();
      const day = new Date(values.date)

      useEffect(() => {
        setTimeSlotsList(fetchAPI(day))
      }, [values.date]);
    }

Update Three.js 3d model texture + Fabric.js canvas as texture

I’m quite new to Three.js. I’m trying to develop a project where I use a pre-existing 3D model and modify one of its materials so that it uses a Fabric.js canvas as its texture. However, I’ve encountered an issue where the texture takes on the color of the canvas, but none of the images I add are visible. Here’s my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        body { margin: 0; }

        #controls {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 1;
        }
    </style>
</head>
<body>
    <div id="controls">
        <div class="colorPicker"></div>
        <canvas id="c"></canvas>
        <button id="clear">Borrar</button>
        <input type="file" id="file">
    </div>
    

    <script src="https://cdn.jsdelivr.net/npm/@jaames/iro@5"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/loaders/GLTFLoader.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>

    <script>
        let canvas = new fabric.Canvas('c',  {
            backgroundColor: 'white',
        });
        canvas.setHeight(512);
        canvas.setWidth(512);

        document.getElementById('clear').addEventListener('click', () => {
            !deleteActiveObjects()
        });

        function deleteActiveObjects() {
            const activeObjects = canvas.getActiveObjects();
            if(!activeObjects.length) return false;
            
            if(activeObjects.length) {
                activeObjects.forEach(function(object) {
                    canvas.remove(object);
                });
            } else {
                canvas.remove(activeObjects);
            }
            
            return true;
        }

        document.getElementById('file').addEventListener('change', (e) => {
            const file = e.target.files[0]; // Get the file from the input
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    fabric.Image.fromURL(event.target.result, function(img) {
                        img.set({
                            angle: 0,
                            padding: 10,
                            flipX: false
                        });
                        img.scaleToHeight(200);
                        img.scaleToWidth(200);
                        canvas.add(img);
                        canvas.renderAll(); // Redibujar el canvas después de añadir la imagen
                        
                        // Actualizar la textura del material 14
                        const texture = new THREE.CanvasTexture(canvas.getElement());
                        material14.map = texture;
                        material14.map.needsUpdate = true; // Esto asegura que la textura se actualice
                    });
                };
                reader.readAsDataURL(file); // Read the file as a data URL
            }
        });

        function colorPicker(material14) {
            let colorPicker = new iro.ColorPicker(".colorPicker", {
                width: 280,
                color: "rgb(255, 0, 0)",
                borderWidth: 1,
                borderColor: "#fff",
            });
        
            colorPicker.on(["color:change"], function(color) {
                canvas.backgroundColor = color.hexString;
                canvas.renderAll();
        
                // Actualiza la textura del material
                material14.map.needsUpdate = true;
            });
        }

        function initScene() {
            const scene = new THREE.Scene();
            scene.background = new THREE.Color(0xd3d3d3);

            const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
            camera.position.set(0, 1, 5);

            const renderer = new THREE.WebGLRenderer({ antialias: true });
            renderer.setSize(window.innerWidth, window.innerHeight);
            document.body.appendChild(renderer.domElement);

            const controls = new THREE.OrbitControls(camera, renderer.domElement);
            controls.enableDamping = true;
            controls.dampingFactor = 0.05;
            controls.screenSpacePanning = false;
            controls.minDistance = 2;
            controls.maxDistance = 50;
            controls.maxPolarAngle = Math.PI / 2;

            return { scene, camera, renderer, controls };
        }

        function addLights(scene) {
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
            scene.add(ambientLight);

            const light = new THREE.DirectionalLight(0xffffff, 1);
            light.position.set(10, 10, 10).normalize();
            scene.add(light);
        }

        function loadModel(scene) {
            const loader = new THREE.GLTFLoader();
            loader.load('assets/models/2x2.glb', function(gltf) {
                model = gltf.scene;
                model.scale.set(0.001, 0.001, 0.001);
                scene.add(model);
                console.log("Modelo cargado correctamente");
        
                const material14 = getMaterialByIndex(model, 14);
                if (material14) {
                    console.log("Material 14 encontrado:", material14);
        
                    // Usa el canvas de Fabric.js como textura
                    const texture = new THREE.CanvasTexture(canvas.getElement());
                    material14.map = texture;
                    material14.map.wrapS = THREE.RepeatWrapping;
                    material14.map.wrapT = THREE.RepeatWrapping;
                    material14.map.minFilter = THREE.LinearFilter;
                    material14.map.magFilter = THREE.LinearFilter;
                    material14.needsUpdate = true;
        
                    colorPicker(material14);
                }
            }, undefined, function(error) {
                console.error("Error al cargar el modelo:", error);
            });
        }

        function getMaterialByIndex(model, index) {
            let materials = [];
            model.traverse(function(child) {
                if (child.isMesh) {
                    materials = materials.concat(child.material);
                }
            });
            return materials[index] || null;
        }

        function animate(scene, camera, renderer, controls) {
            function render() {
                requestAnimationFrame(render);
                controls.update();
                renderer.render(scene, camera);
            }
            render();
        }

        function onWindowResize(camera, renderer) {
            window.addEventListener('resize', function() {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(window.innerWidth, window.innerHeight);
            });
        }

        function init() {
            const { scene, camera, renderer, controls } = initScene();
            addLights(scene);
            loadModel(scene);
            animate(scene, camera, renderer, controls);
            onWindowResize(camera, renderer);
        }

        init();
    </script>
</body>
</html>

I’ve try updating the material when an image is uploaded but it does nothing.

Conditional Rendering of Controlled Components Giving a Blank Page When False

I’ve been working on my first React Project, a CV application where users can input their information and generate a CV. After the user submits the form, the form should disappear and the relevant info displayed on the page.
Unfortunately, nothing is displayed after the input boxes are filled, and it seems like the state values become empty after pressing the submit button. Also, the input fields disappear even before I press the submit button.

Here’s the code –

import React, { useState } from 'react';

export default function Info(){
    const [person, setPerson] = useState({
    full_name: "",
    email_ID: "",
    phone_number: "",
    edit_mode: true
    });
    
    const changeHandler = (e) =>{
        setPerson({ [e.target.name] : e.target.value })
    }

    const submitHandler = (e) =>{
        e.preventDefault();
        setPerson({
            edit_mode: false
        }); 
    }
    const editHandler = (e) =>{
        setPerson({
            edit_mode: true
        })
    }
    const editContent = (
    <div>
        <form onSubmit={submitHandler} >
            <input 
                type = "text"
                value = {person.full_name}
                placeholder='Enter Your Full Name'
                onChange={changeHandler}/>
            <br/>
            <input 
                type = "email"
                value = {person.email_ID}
                placeholder='Enter Your Email ID'
                onChange={changeHandler}/>
            <br/>
            <input 
                type = "tel"
                value = {person.phone_number}
                placeholder='Enter Your Phone Number'
                onChange={changeHandler}/>
            <br/><br/>
            <button type="submit" className="submit-button">SUBMIT</button>
        </form>
    </div>
    )

    const submittedContent = (
        <div>
            <button onClick={editHandler} className="edit-button">EDIT</button>;
            <h2>{person.full_name.toUpperCase()}</h2>
            <br/>
            <p>{person.email_ID}</p>
            <p>|</p>
            <p>{person.phone_number}</p>
        </div>
    )

    return(
        <>
            {person.edit_mode ? editContent : submittedContent}
        </>
    )
}

Is there a way to fix this without involving the use of additional React Hooks, since I’m just starting out with React and want to implement this using only the useState hook. Thanks!!

Add custom method to ECMAScript object

Since I am limited to use ECMAScript version 7, and I wanted to use String methods like padStart() introduced in ES 8

I added the folowing code for the custom padStart(digits,character) method which was working as expected:

String.prototype.padStart = function(digits,fill){
        value = this;
        while (value.length < digits){
       value = fill+value;
   }
   return value
}

Now I added a second method padEnd(digits,character) to my code:

String.prototype.padEnd = function(digits,fill){
        value = this;
        while (value.length < digits){
       value = value + 'X';
   }
   return value + 'X'
}

And I was expecting I were able to uses both new methods on String-Objects, but I found that only the code of the first method is used, even if I use the padEnd() method on the String object.

What am I doing wrong?

Div covered using ngIf is still visible for a second

I’m trying to make a webpage using Angular 17 that opens into a ‘loading screen’ div positioned above the other elements, and the div disappears after two seconds. The timer is controlled using setTimeout(). It sort of works, except the main content is still visible for a second before the loading screen pops up.

app.component.html

<div *ngIf = "LoadingStatus" class = "LoadingScreen">
  <!-- div displays loading screen for two seconds upon opening, then disappears. -->
</div>

<!-- <ng-container *ngIf = "!LoadingStatus"> -->
  <div class = "background">
    <div id = pLogo>
      <!-- main content -->
    </div>
  </div>
  <router-outlet />
<!-- </ng-container> -->

app.component.ts

import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ButtonModule } from 'primeng/button';
import { DividerModule } from 'primeng/divider';
import { RippleModule } from 'primeng/ripple';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, ButtonModule, DividerModule, RippleModule, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
  title = 'login_app';
  LoadingStatus = true;

  ngOnInit(): void {
    setTimeout(() => {
      this.LoadingStatus = false;
    }, 2000);
  }
}

app.component.css

h1, h2, h3, p {
    font-family: "Arial";
}

#pLogo {
    position: fixed;
    top: 20px;
    left: 20px;
}

.background {
    background-color: #ffffff;
    height: 100vh;
    width: 45%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
}

#welcomeText {
    margin-top: 25%;
}

#loginButton {
    margin-top: 15%;
}

#RequestAccessLink {
    margin-top: auto;
    margin-bottom: 10%;
}

:host ::ng-deep .p-button { 
    background-color: #00a19c;
    border-color: #00a19c;
    font-family: Arial, sans-serif !important;
    font-size: 1.5vw;
}

:host ::ng-deep .p-button:hover { 
    background-color: #00928d;
    border-color: #00928d;
    font-family: Arial, sans-serif !important;
    font-size: 1.5vw;
}

.LoadingScreen {
    background-color: #00a19c;
    height: 100vh;
    width: 100vw;
    margin:0px;
    position: fixed;
    z-index: 1000;
}

What could the issue be?

Thank you!

Openlayers throws error by applying extent on ol.layer.Tile

I’m trying to render a tile layer on Open Street Map as an overlay layer.
When I set extent to avoid sending out-of-bound requests to the tile server, I get error tilesByZ[z] is not iterable which I don’t understand.

enter image description here

Here is my code:

/**
 * Create ol.layer.Tile
 * @param {ITileLayer} params layer parameters
 */
export const CreateTileLayer = (params: ITileLayer): TileLayer<OSM | XYZ> => {
  const layer = new TileLayer({
    source: CreateTileSource(params.id, params.url),
    properties: {
      id: params.id,
      label: params.label,
      groupId: params.groupId,
      type: params.type,
    },
    extent: params.extent,
  });
  layer.setZIndex(params.zIndex);
  layer.setVisible(params.visible);
  return layer;
};

I searched on Openlayer github issues and I found it was reported here as a bug and fixed here.

Then I tried to install the latest version ("ol": "^10.0.0") but it didn’t work.
I expected the new release fixes this issue.

Should I wait for a new release?

How to correctly manage state in a parent component when passing data to child components in React?

I’m building a React application where I have a parent component that holds the state and several child components that need to receive and update this state. I’m using props to pass the state and a callback function to update the state from the child components. However, I’m encountering issues where the state updates aren’t reflecting immediately in the child components, or the state becomes inconsistent.

function ParentComponent() {
    const [data, setData] = useState([]);

    const updateData = (newData) => {
        setData(newData);
    };

    return (
        <div>
            <ChildComponent data={data} updateData={updateData} />
            <AnotherChildComponent data={data} />
        </div>
    );
}

function ChildComponent({ data, updateData }) {
    const handleClick = () => {
        const updatedData = [...data, 'New Item'];
        updateData(updatedData);
    };

    return (
        <div>
            <button onClick={handleClick}>Add Item</button>
        </div>
    );
}

function AnotherChildComponent({ data }) {
    return (
        <ul>
            {data.map((item, index) => (
                <li key={index}>{item}</li>
            ))}
        </ul>
    );
}


What is the best practice for managing state between parent and child components in React?
How can I ensure that all child components receive the updated state immediately?
Are there any performance concerns with this approach, and how can I optimize it?

Converting array and array of arrays into array of objects [duplicate]

I’ve been facing issues in making array of objects using array and array of arrays. In my scenario I’m having 400 cols and 5000 rows. Having col names in separate array and user data in array of arrays.

My Expectation:
Array of objects = Array (Cols_name) + Array_of_arrays (User_data)

var cols_names=['name','address','phoneno'];
var arr_of_arrs=[
    ['ABC','INDIA','0989898976'],
    ['XYZ','USA','0989898998'],
    ['CDE','UK','0989898956']
    ];
    
const arr_of_obj = arr_of_arrs.map((...cols_names) => ({cols_names}));
console.log(arr_of_obj);

I got output like this:

[
  { cols_names: [ [Array], 0, [Array] ] },
  { cols_names: [ [Array], 1, [Array] ] },
  { cols_names: [ [Array], 2, [Array] ] }
]

I need like this:

[
  {
    "name":"ABC",
    "address":"INDIA",
    "phoneno":"0989898976"
  },
  {
   "name":"XYZ",
    "address":"USA",
    "phoneno":"0989898998"
  },
  {
    "name":"CDE",
    "address":"UK",
    "phoneno":"0989898956"
    
  }
]

Note: I can’t write the below code like this because I’m having 400 cols. I should not specify each and every col names statically in the code:

const arr_of_obj = arr_of_arrs.map(([name,address,phoneno]) => ({name, address,phoneno}));

console.log(arr_of_obj);

Javascript amcharts5 heat map heat legend add gradient color

I am sorry this question may not be smooth using a translator.

I using amcharts5.
I’d like to add some color to the gradients.
The only thing found was to specify start color and end color.
The other gradation demo was not to have a smooth color, but to specify a color for each value.

https://www.amcharts.com/demos/heat-map-with-legend/

When using code, you can specify only two colors.

https://www.amcharts.com/docs/v5/tutorials/a-custom-heat-legend-using-a-gradient/

This demo wasn’t the gradient addition I wanted.
I want to add the desired color and designate offset for each color so that it connects naturally.

color: [
‘#313695’, ‘#00a31b’, ‘#f0d800’, ‘#f06c00’, ‘#f00000’, ‘#cc0055’
]

I hope the color will be designated and it will continue smoothly.

enter image description here

I want to add colors to make a legend like the image.

cors error in backend php server , the api is working in some devices and giving cors error in some devices

i have created a chatbot has form , and the form will send the payload to backend php server , the api will create conversation , the chatbot is fully working in some devices, and it is giving cors error some devices.
headers i am sending from frontend –

    const response = await fetch("https://example.com/api/create-conversation", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    });
    const result = await response.json();

the backend php code :

header("Access-Control-Allow-Headers: *");
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        header("HTTP/1.1 200 OK");
        header("Content-type:application/json");
        header('Content-Type: text/plain');

Why is the API working on some devices but not on others? I am using var client = new XMLHttpRequest(); to load the page, and the UI automatically updates. The targeted frontend has an embed code which is opened with client.open(“GET”, “https://example.com/embed-code”);. I have targeted the UI of the embed code with DOM manipulation and handle the UI inside the client.onload scope, while the functions responsible for API handling are outside this scope.

Given this setup, why does the API work on some devices but not on others? The console shows an error: “(Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.” I have added the header: header(“Access-Control-Allow-Origin: *”);.

The API is not working consistently across all devices; some devices return a CORS error. I want the API to work on every device. What could be the issue?

ReadableStream from Fetch API not consuming entire data

I am trying to use Fetch API’s stream capability to read streaming data from backend and use it, based on this.

My code is structured as:

function init() {
  container = document.createElement("div");
  document.body.appendChild(container);

  fetch("http://localhost:8080/data/stream", {
    method: "GET",
    headers: {
      Accept: "application/json",
    },
  }).then((response) => {
    const reader = response.body.getReader();
    return new ReadableStream({
      start(controller) {
        return pump();
        function pump() {
          return reader.read().then(({ done, value }) => {
            // When no more data needs to be consumed, close the stream
            if (done) {
              controller.close();

              // do something with data fetched

              return;
            }
            // Enqueue the next data chunk into our target stream
            controller.enqueue(value);

            // put data in some data structures(like arrays) for using at end

            return pump();
          });
        }
      },
    });
  });
}

init();

But this is not working as expected. I expect it to consume all of the streamed data, but while backend streams almost 1.5 million records, this code is able to consume very little of that. ‘done’ gets true even before entire data has arrived.

What mistake am I making here?

How do I set up a UI Aceternity component in a preexisting Next.js project?

I watched a video and found out about UI Acernity and it feels like a godsend. However, I am struggling with setting it up. I have read some articles and watched some videos but it feels like I am learning how to code for the first time again and I have no clue what I am doing. I am so clueless I nearly deleted my project directory by accident.

So I was wondering if anyone could explain how to do this. I am trying to follow the guides on https://ui.aceternity.com/components/background-boxes which is the component I want to add, but typescript is tripping me up. Could anyone explain to me how to do this?

I tried downloading dependencies, then adding a util file, and then updating my tailwind.config.js file, but I kept on running into an error or some issue that was different everytime. I also tried installing shadcn and doing it that way but that led to even more issues.

Making JavaScript WebApps based on a database

I’d like to learn to make web applications based on databases, like this example. I couldn’t find a lot of information regarding the backend on the GitHub repo of the example.

In the example, there seems to be a central database, and other individual elements are also generated for each “card”. Finally, there are scripts that control how the elements come together.

What should one learn to make such apps? Is this a Single Page Application? Are there any frameworks that exist already that can be used? How about the animations: are they made using CSS or Javascript? Does one have to use JavaScript, or can one use something like Rails or Django for the purpose? What about Flutter?

If someone can help me get started, that would be great!