React keeps rendering before state is able to change

There’s a state here, brushSize which is adjusted using a slider. It goes as props to another component, Board. However, the render function keeps executing before the state is able to change, and Board ends up getting the old value. I was able to confirm this by checking the received props value in Board.js, which is the old value.

According to what I could find, render() is supposed to execute once the state has changed, but that doesn’t seem to be happening.

import React from 'react'
import Board from './Board'
import './style.css'

class Container extends React.Component {
    constructor(props) {
        super(props);
        this.state = {brushSize: 2};

        this.brushSizeChange = this.brushSizeChange.bind(this);
    }

    brushSizeChange(e) {
        this.setState((prev) => { return { ...prev, brushSize: e.target.value } });
    }

    render() {
        return (
            <div className="container">
                <label>Brush size: </label>
                <input type="range" min="1" max="10" value={this.state.brushSize} onChange={this.brushSizeChange} />
                <h1>placeholder</h1>
                <div className="board-container">
                    <Board size={this.state.brushSize}/>
                </div>
            </div>
        )
    }
}

export default Container

JavaScript local storage issues

I am trying to post objects from a bootstrap modal to the local storage in JavaScript. The set of details gets posted to the local storage but the other form entries do not. Here is my code.

//function to add tasks to the loacal storage
function addTask() {
  myTasks.push(new TaskManager(id,taskName.value,assignedTo.value,dueDate.value,statusButton.value,description.value ));
  localStorage.setItem("tasks", JSON.stringify(myTasks));
}

How can I fix this Javascript solution

Problem:
https://open.kattis.com/problems/abc

So I am trying to do this code problem in Kattis with Javascript and I am unable to understand why my solution is wrong. If anyone could tell me why they think it might be wrong or highlight how I could test the Kattis cases and see the outputs that would be excellent. I didn’t just code this up, and instantly assumed it was right but I have created several test beds to simulate standard input and they seem to produce the same answers as the sample input. Note, there’s probably a much better way to approach the solution, I am very unfamiliar with node.JS still.

Here is my code:

const readline = require('readline');


const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});


rl.on('line', (line) => {

    var array = (line.split(' '));
    var test = parseInt(array[0]);
    
    if (!isNaN(test)) { // its a numba 
        
        var a = parseInt(array[0]);
        var b = parseInt(array[1]);
        var c = parseInt(array[2]);
        var arr2 = [a, b, c];
        var arr = arr2.sort(function (a, b) { return a - b });
        a = arr[0];
        b = arr[1];
        c = arr[2];
    }
    // z y x
    else if (isNaN(test)) {
        var g = line.split('');
        var z = g[0];
        var y = g[1];
        var x = g[2];


        if (z == 'A' && y == 'B') {
            var answer = [a, b, c];
        }

        else if (z == 'A' && x == 'B') {
            answer = [a, c, b];
        }

        else if (y == 'A' && x == 'B') {
            answer = [c, a, b];
        }

        else if (y == 'A' && z == 'B') {
            answer = [b, a, c];
        }

        else if (x == 'A' && z == 'B') {
            answer = [b, c, a];
        }

        else if (x == 'A' && y == 'B') {

            answer = [c, b, a];
        }
        else{
            console.log(b + " " + a + " " + c);
        }

    

        console.log(answer[0] + " " + answer[1] + " " + answer[2]);
    }
});

Khan Academy: Spaceship Ride

For Challenge: Spaceship Ride in Khan Academy’s Advanced JS: Natural Simulations in the computer programming category in the computing course, I need to speed the ships up, turn them upside down, and spin those ships around. this is the default code:
angleMode = “radians”;

var Spaceship = function() {
this.angle = new PVector();
this.velocity = new PVector(random(-0.01, 0.01), random(-0.01, 0.01));
this.amplitude = new PVector(random(20, width/2), random(20, width/2));
this.position = new PVector(0, 0);
};

Spaceship.prototype.oscillate = function() {
this.angle.add(this.velocity);
this.position.set(
sin(this.angle.x) * this.amplitude.x,
sin(this.angle.y) * this.amplitude.y);
};

Spaceship.prototype.display = function() {
pushMatrix();
translate(width/2, height/2);
stroke(181, 63, 0);
strokeWeight(9);
line(0, 0, this.position.x, this.position.y);
imageMode(CENTER);
image(getImage("space/octopus"),
this.position.x, this.position.y,
80, 100);
popMatrix();
};

var ships = [];
for (var i = 0; i < 10; i++) {
ships.push(new Spaceship());
}

draw = function() {
background(174, 218, 232);
for (var i = 0; i < ships.length; i++) {
    ships[i].oscillate();
    ships[i].display();
}
};

Can you please tell me what I need to change or add?

Three.js – Need to update camera position live based on updated sql code

I have a mysql code that updates values live from a .php file and I have a three.js model viewer that I want to be able to rotate live based on the updated sql input. The code below shows it in the camera.position.set tag My page does show the numbers updated every second, but I need the model to update as well. I’ve tried various types of animate(), settimeout, etc. but don’t really know the best way to do this.

Here’s my existing three.js code. Note, the result WORKS, it just doesn’t update unless I refresh the page.

        <script>
            if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

            var camera, scene, renderer;

            init();

            function init() {

                scene = new THREE.Scene();
                scene.add( new THREE.AmbientLight( 0x999999 ) );

                var pointLight = new THREE.PointLight( 0xffffff, 0.6 );
                pointLight.position.set(80, 80, 90);
                scene.add( pointLight );

                camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 500 );

                // Z is up for objects intended to be 3D printed.

                camera.up.set( 0, 0, 1 );
                camera.position.set( <?php echo $xaxis; ?>, <?php echo $yaxis; ?>, <?php echo $zaxis; ?> );

                //camera.add( new THREE.PointLight( 0xffffff, 0.8 ) );

                scene.add( camera );

                renderer = new THREE.WebGLRenderer( { antialias: true } );
                renderer.setClearColor( 0x333333 );
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( window.innerWidth, window.innerHeight );
                document.body.appendChild( renderer.domElement );

                var loader = new THREE.ThreeMFLoader();
                loader.load( './models/3mf/cube_gears.3mf', function ( object ) {

                    scene.add( object );
                    render();

                } );

                var controls = new THREE.OrbitControls( camera, renderer.domElement );
                controls.addEventListener( 'change', render );
                controls.target.set( 80, 65, 35 );
                controls.update();

                window.addEventListener( 'resize', onWindowResize, false );

            }

            function onWindowResize() {

                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();

                renderer.setSize( window.innerWidth, window.innerHeight );

                render();

            }

            function render() {

                renderer.render( scene, camera );

            }
</script>

Using setState in async function then calling it in useEffect [duplicate]

Here is my function:

functon ABCComponent({ navigation }){

    const testPostID = "1234567891011";
    
    const [post, setPost] = useState("");

     const getPostById = async(postID)=>{
        await axios.get(`http://localhost:5000/posts/post/${postID}`)
            .then((response) =>{
                dispatch(setLoading(true));
                dispatch(setSuccess(true));
                dispatch(setLoading(false));
                response.data.message.map((post, index) =>{
            
                    setPost(post); // I think it's complaining about this line
                });
            }).catch((error) =>{
                console.log("err: ", error);
                dispatch(setLoading(true));
                dispatch(setSuccess(false));
                dispatch(setLoading(false));
                dispatch(setMessage(`${error}`));
            });
    };

    useEffect(() =>{
        getPostById(testPostID);
    }, []);
    
}

I am getting the following error:

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, a useEffect cleanup function,
in ABCComponent.

what is the best way to go about solving this?

React Test Library – Test removing task from list of tasks not working properly

I’m starting to use react test library and can’t understand why my test is not working. I have a list of tasks stored in a state and every task has a delete button. The test consists of checking if the task with a specific role number can be found in the document after the delete button gets clicked.

type Task = {
  id: number
  description: string
  completed: boolean
}
    
type TaskCardProps = {
  data: Task
  removeTodo: (id: number) => void
  completeTodo: (id: number) => void
}

const TaskCard = ({data, removeTodo, completeTodo}: TaskCardProps) => {

      const handleRemove = () => {
        removeTodo(data.id)
      }
    
      const handleComplete = () => {
        completeTodo(data.id)
      }
    
      return (
        <div>
          <p>TaskCard</p>
          <button role={'remove-task-button-' + data.id} onClick={handleRemove}>
            Remove Task
          </button>
          <input type="checkbox" onChange={handleComplete} />
        </div>
      )
    }

When I click the button to remove a task, It is removed from the list but when I run the test It says the element is still in the document.

This is my test:

import {render, screen, waitFor} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import '@testing-library/jest-dom'
import {Task} from './types'
import TaskCard from './components/Cards/TaskCard'

    test('Click delete button', async () => {
        const task: Task = {
          id: 3,
          description: 'description',
          completed: false,
        }
        const completeTodo = jest.fn()
        const removeTodo = jest.fn()
    
        render(<TaskCard data={task} removeTodo={removeTodo} completeTodo={completeTodo} />)
    
        userEvent.click(screen.getByRole(`remove-task-button-${task.id}`))
    
        await waitFor(() => expect(screen.queryByRole(`remove-task-button-${task.id}`)).not.toBeInTheDocument())
      })

This is the result of the test:

    ✕ Click delete button (1073 ms)

  ● TaskCard Component › Click delete button

    expect(element).not.toBeInTheDocument()

    expected document not to contain element, found <button role="remove-task-button-3">Remove Task</button> instead

Remove the format of selected text only

My problem is when I want to remove the format of a selected text, the format of the whole text will be removed.

document.getElementById('bold').addEventListener('click', () => edit('STRONG'));
document.getElementById('italic').addEventListener('click', () => edit('EM'));

function edit(format) {
  let parentElementOfSelectedText = document.getSelection().getRangeAt(0).commonAncestorContainer;

  // If element is already formatted, undo the format
  if (parentElementOfSelectedText.tagName === format || parentElementOfSelectedText.parentElement.tagName === format) {
    if (parentElementOfSelectedText.tagName !== format) parentElementOfSelectedText = parentElementOfSelectedText.parentElement;

    let grandParentOfSelectedText = parentElementOfSelectedText.parentElement;
    if (parentElementOfSelectedText.textContent) {
      const selectedText = document.createTextNode(parentElementOfSelectedText.textContent);

      //work with range of old element because 
      //text nodes are pass by value
      //and we cant create a range after its a text node
      const range = document.createRange();
      range.selectNode(parentElementOfSelectedText);

      //this replaces some of your code but uses a range
      range.deleteContents();
      range.insertNode(selectedText);

      grandParentOfSelectedText.normalize();

      //select the range again :)
      const selection = window.getSelection();
      selection.removeAllRanges();
      selection.addRange(range);
    }
  } else {
    let selectedText = document.getSelection().getRangeAt(0);
    const node = document.createElement(format);
    const fragment = selectedText.extractContents();

    if (fragment) {
      node.appendChild(fragment);
    }
    selectedText.insertNode(node);


    //make only the inside of the node a range
    //so [...].commonAncestorContainer is "STRONG" or "EM"
    //and gets recognized
    const range = document.createRange();
    range.selectNodeContents(node);
    const selection = window.getSelection();
    selection.removeAllRanges()
    selection.addRange(range);
  }
}
<button id="bold">B</button>
<button id="italic">I</button>
<div contentEditable="true">Lorem</div>

Select Lorem and click on the B button. So Lorem will be bold. Now type ipsum after Lorem. Ipsum will also be bold. Select ipsum and click again on the B button. Now not only ipsum lost its format but also Lorem.

It is fine when the text that gets entered will have the same format as the text before. But the user should be able to remove the format of the selected text only.

So when they start to type, the value should be Lorem ipsum and when the remove the format of ipsum, it should be Lorem ipsum.

How can I do this?

how to reuse a variable with everything and its value in another page of my project

im working on a e-commerce and im trying to do the page where you fill your info, but i cant use my variable cart, or my total.textContent i just need to show my cart, the total of the cart and my form but i cant use any of my variables or functions

enter code here

    const container = document.getElementById("container");
    
    const cartContainer = document.getElementById("cart-items");
    
    let cart = [];
    
    export let stock = [
    
        {id: 1, item: "Playera blanca - Logo rojo", precio: 265, imagen: '<img class="cart-review-img" src="./images/Playera blanca - Logo rojo.png" alt="">'
}];
    
    const upDateCart = () => {
        cartContainer.innerHTML = ""
    
        cart.forEach((prod) => {
            const div = document.createElement("div")
            div.className = ("cart-review-cotainer")
            div.innerHTML = `
            <div class="cart-image col-md-5">
                ${prod.imagen}
            </div>
            <div class="col-md-5 d-flex flex-column  justify-content-between">
                <div>
                    <p id="cart-item-name">${prod.item}</p>
                    <p id="cart-item-price">${prod.precio}</p>
                </div>
            </div>
            <div class="col-md-2 delete-container">
                <button onclick="deleteItem(${prod.id})" id="delete-item"><img class="delete-img" src="./images/trash-solid.svg" alt=""></button>
            </div>
            `
            cartContainer.appendChild(div)
    
           localStorage.setItem("newCart", JSON.stringify(cart))
           
        })
        total.innerText = cart.reduce((acc, prod) => acc + prod.precio, 0)
    }
    
    if(localStorage.getItem("newCart")) {
        newCart = JSON.parse(localStorage.getItem("newCart"))
        console.log(newCart)
        upDateCart()
    }
    
    window.deleteItem = deleteItem;
    
    window.cart = cart;
    
    window.test = test;
    
    window.newCart = newCart;

my files in vs code

Passing a variable from one component to another

I have a quiz app built with React, that after the user answers it, it shows his score and then he needs to insert his email to send the results to the site owner.

I have a main component called App.js with the quiz and I saved his score like this:

const[score,setScore] = useState(0);

Now I want to show this score in my component “Score.js”, so I need to get this score from App.js and send it to Score.js.

Java Script Function changes parameter variables globally, how to avoid that?

rotr() removes the last array value and places it to array-index 0 (to the the beginning). The method does that for n times. Its rotating the array x by n.

My problem is the first XORXOR parameter is w[sh1] rotatet by 7. Okay! Thats good.

The second XORXOR parameter is rotatet by 7 + 18 and the last parameter is rotatet by 7+18+3. Thats not how i want it…

The first parameter of rotr should and must always be the same array. Why is the function changing the array globally. Its not modifying the parameter and returns a copy of that modification? With return? Always used Python… then one time a little bit JS and its completely getting on my nerves… can someone help me and explain it to me?? my whole algorithm is a failure because of that *****

const s0 = XORXOR(rotr(w[sh1], 7), rotr(w[sh1], 18), shr(w[sh1], 3))

function rotr(x, n) {
    for(let c = 0; c<n; c++) {
        x.unshift(x.pop());
    }
    return x
}

How to use module.exports in scale

I am trying to export variables from my index.js to my api.js. I used module.exports.client and it works fine no problems then I added more then it started saying Console Logs and I have no idea why. I have looked at many different posts on using module.exports but I still can’t get it to work

C# – How to find and replace every nth character occurrence using regex? Conversion from Javascript to C#

Find and replace every 3rd character occurrence in a given string and replace it with H

I found this Javascript code that does the same thing and would like to convert it into a C# code. Can you please assist ?

Found here

str = str.replace(/((?:[^x]*x){2}[^x]*)x/g, '$1y');

let str = 'I amx nexver axt hoxme on Sxundxaxs';
let n = 3;
let ch = 'x';

let regex = new RegExp("((?:[^" +ch+ "]*" +ch+ "){" + (n-1) + "}[^" +ch+ "]*)" +ch, "g");

str = str.replace(regex, '$1y');

console.log(str);
//=> I amx nexver ayt hoxme on Sxundyaxs

Why does CodePen script not work with my NextJS local server?

Before anything, keep in mind I am extremely new to both NextJS, CodePen, and web dev in general.

I found this cool mouse movement animation on CodePen and wanted to implement it onto the website I just started building on NextJS. I’m fairly certain I imported the files correctly and the CSS works however the script does not.

This is my entire index.js code.

import Head from 'next/head'
import Script from 'next/script'

export default function Home() {
  return (
    <html lang="en" >
    <Head>
          
      <meta charset="UTF-8"/>
      
      <title>CodePen - Animated Background</title>
      <link href='https://fonts.googleapis.com/css?family=Raleway:200,400,800' rel='stylesheet' type='text/css'/><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"/>
      <link rel='stylesheet' href='https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/css/demo.css'/><link rel="stylesheet" href="../styles/dynamic.css"/>

    </Head>
    <body>

      <div id="large-header" className="large-header">
        <canvas id="demo-canvas"></canvas>
          <h1 className="main-title">Vansh <span className="thin">Sharma</span></h1>
      </div>

      <Script src='https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/js/EasePack.min.js'/>
      <Script src='https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/js/rAF.js'/>
      <Script src='https://www.marcoguglie.it/Codepen/AnimatedHeaderBg/demo-1/js/TweenLite.min.js'/>
      <Script src="../scripts/dynamic_script.js" strategy='beforeInteractive' defer={false} type='text/javascript'/>

    </body>
    </html>

  )
}