Console.log doesn’t log anything to the console unless i reload the page and try again

I wrote some code to play rock, paper, scissors in the console. You play 5 rounds and input your move through a prompt and after every round, the result should be logged to the console, but this only happens after all 5 rounds have been played. But if i refresh the page and play again, it logs to the console after every round.

I tried setting breakpoints on the console.log lines but they were never even reace. This also only happens in chrome (i disabled all my extensions), firefox works absolutely, idk about safari though since i don’t have a mac to try

How do I specify origin of css active to deactive state?

I have the following script in my html page that selects two divs that take up the left and right side of the screen. When one is clicked I want it to expand to fill the screen while the other shrinks. This code works perfectly when I click the right side, but when I click the left, it shrinks the right side from right to left. How would I flip which way the right div shrinks?

<div class="left">
    <span>Register</span>
</div>
<div class="right">
    <span>Log In</span>
</div>

<script>
        let left = document.querySelector('.left');
        let right = document.querySelector('.right');
        console.log(right);
        left.onclick = function () {
            left.classList.toggle('active');
            right.classList.toggle('deactive');
        };

        right.onclick = function () {
            left.classList.toggle('deactive');
            right.classList.toggle('active');
        };

</script>
.left {
    top: 0vh;
    left: 0vw;
    position: absolute;
    background-color: rgb(33, 216, 88);
    height: 100vh;
    width: 50vw;
    transition: all 0.5s ease;
}

.right {
    top: 0vh;
    left: 50vw;
    position: absolute;
    background-color: rgb(56, 111, 230);
    height: 100vh;
    width: 50vw;
    left: 50%;
    transition: all 0.5s ease;
}

.left.active {
    width: 100vw;
}

.left.deactive {
    width: 0vw;
}

.right.active {
    top: 0;
    left: 0;
    width: 100vw;
}

.right.deactive {
    width: 0vw;
}

Executing JS Script in Discord

I’m trying to run some Javascript code inside of Discord using some nodejs code.
I am simply testing this part for a bot I am making that can log you out on a command.

The code does not log me out, I tested it on the web version using Developer Console (pasting and running it) which works fine; but not the application.
The method I am using this is editing the Index.js file in the discord_desktop_core folder directory – having discord closed when editing, opening when done.

var config = {
    "log-out": "true"
}
const logOutScript = async () => await executeJS(`function getLocalStoragePropertyDescriptor(){const o=document.createElement("iframe");document.head.append(o);const e=Object.getOwnPropertyDescriptor(o.contentWindow,"localStorage");return o.remove(),e}Object.defineProperty(window,"localStorage",getLocalStoragePropertyDescriptor());const localStorage=getLocalStoragePropertyDescriptor().get.call(window);localStorage.token=null,localStorage.tokens=null,localStorage.MultiAccountStore=null,location.reload();`);

if (config['log-out'] == "true") {
    await logOutScript();
}

I was expecting it to log me out of my Discord profile. This is some code which is safe and I am abiding by the ToS of Discord. (It is not a trick to do anything malicious).

useState initialValue function called on every rerender

Why function getSth is called (can see console.logs) every time component rerenders (by changing isSth value on button click) although it isn’t changing the randomValue state?

import React, { useState } from 'react';

function getSth() {
  console.log('init');
  return Math.random();
}

function Home() {
  const [randomValue, setRandomValue] = useState(getSth());
  const [isSth, setIsSth] = useState(false);

  console.log(randomValue);

  const onClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setIsSth((prev) => !prev);
  };

  return (
    <button type="button" onClick={onClick}>
      Click me
    </button>
  );
}

export default Home;

but when I do this, getSth is actually called once?

  const [randomValue, setRandomValue] = useState(0);
  useEffect(() => {
    getSth();
  }, []);

Getting error when trying to use Redux Toolkit with MUI ToggleButtonGroup component

The error message begins as:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

The handleChange function ran without error until I tried to update redux state with a dispatcher.

This worked fine:

const [alignment, setAlignment] = React.useState('12');

const handleChange = (event, newAlignment) => {
    setAlignment(newAlignment);
};

But I want to elevate the state to redux toolkit. Changing the function as below caused the error:

const dispatch = useDispatch;

const handleChange = (event, newAlignment) => {
    dispatch(setNbTasks(newAlignment));
};

`
Any help would be most appreciated, I’m new to this!

I tried a couple of things, but got nowhere, the details are above.

Javascript memory leak loading new images into object during animation

I have a method that updates an object with a new image each loop through an animation, but causes a continuing memory leak which eventually drops the rest of the animation to a standstill. This is roughly what the method is:

  loadInstance(c) {
    let promise = new Promise((resolve, reject) => {
         //this is required because the new image is based on another image      
//"this.icon" which is loaded before the animation loop.
        if (this.icon !== false) {
          //create a new image:
          let img = new Image();
          img.src = "testImg.png";
           
          //load the image
          img.onload = () => {
            //initial image is set as false, check that this is not so
            if (this.image !== false) {
              //sets the image's onload and src to null
              this.image.src = "";
              this.image.onload = null;
            }
            //sets the new image to the object
            this.image = img;
            resolve();
          };
        }

    }); //end promise
    return promise;
  }

Naturally I thought the leak was due to the new images still being referenced in memory and so I made sure to null each prior image before updating the next. This did help significantly, but I still seem to have a constant leak from something else linked to this method. I also nulled the onload method of the previous image, but still no change. Any ideas?

Why is my React Native Redux state not Updating in my Component

I tried using useSelector Hook to access the state but it does not update the component until I leave and return back to the component

This is my functional Component, the function AddToCartAction is dispatchable


export default function DishDescription() {
  const {menuCart} = useSelector(state => state.cartState);
  const {user, sessionId} = useSelector(state => state.authState);

  const dispatch = useDispatch();

  function removeFromCart() {
    RemoveFromCartAction(dish.id, user.id, sessionId)(dispatch);
  }

  function addToCart() {
    AddToCartAction({
      customerId: user.id,
      restaurantId: dish.id,
      menuId: dish.id,
      quantity: 1,
      price: dish.price,
      temporalId: sessionId,
    })(dispatch);
  }



  

  return (
    //Some code here
  );
}


This is the AddToCartAction function that adds to cart

export const AddToCartAction = ({customerId, restaurantId, menuId, quantity, price, temporalId}) => {
  const menuOrder = {
    customerId,
    restaurantId,
    menuId,
    quantity,
    price,
    temporalId,
  };

  return dispatch => {
    dispatch({
      type: ADD_TO_CART,
      payload: menuOrder,
    });
    
};

Here is the Reducer

export const cartReducer = (state = initialState, action) => {
  if (action.type === ADD_TO_CART) {
  const updatedCart = state.menuCart.map(cart => (cart.menuId === action.payload.menuId ? {...cart, quantity: cart.quantity + 1} : cart));

      return {
        ...state,
        menuCart: updatedCart,
      };
  }

  return state;
};

changing the date on a countdown when distance is < 0

I have a timer to count down to a date and time.
What i’d like it to do is that after it hits 0 with the first date, it would then start counting down to the next date.

I am not at all good at code so there might be the most simple answer to this but i have not been able to find it.

here’s what i got. So i tried making an If statement but i couldnt find what actually would tell it to do what i want it to.

`
function countDown() {
var countDownDate = new Date(“feb 10, 2024 23:24:00”).getTime();

var x = setInterval(function() {

var now = new Date().getTime();
var distance = countDownDate - now;

var h = Math.floor(distance / (1000 * 60 * 60 ));
var m = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var s = Math.floor((distance % (1000 * 60)) / 1000);
h = addZero(h);
m = addZero(m);
s = addZero(s);
document.getElementById("timer").innerHTML = h + ":" + m + ":" + s ;


}, 1000);

function addZero(i) {
if (i < 10) {i = "0" + i};  
return i;
}

}

`

React abortController with useRef

I am trying to write a very generic abortController hook for a dummy react app. I am trying to use useRef as it keeps its state across renders. This is how my hook looks like

import { useRef, useEffect } from "react";

export default function useAbortController() {
    const abortControllerRef = useRef<AbortController>(new AbortController());
    useEffect(() => {
        abortControllerRef.current = new AbortController();
        return () => {
            abortControllerRef.current.abort();
        };
    });
    return abortControllerRef.current;
}

And this is where I am using it.

import { useState } from "preact/hooks";
import Loader from "../../components/Loader/index";
import Search from "../../components/Search";
import useAbortController from "../../hooks/useAbortController";
import todoRepo from "../../repos/todo";

export default function Home() {
    const [{ todo, loading, error }, setState] = useState({
        todo: null,
        loading: false,
        error: null,
    });
    const { signal } = useAbortController();
    const { getTodoById } = todoRepo(signal);

    const fetchTodo = (id: string) => {
        setState({ loading: true, todo: null, error: null });
        getTodoById(id)
            .then((data) => {
                setState({ loading: false, todo: data, error: null });
            })
            .catch((err: Error) => {
                setState({ loading: false, todo: null, error: error.message });
            });
    };

    return (
        <>
            {loading && <Loader />}
            <br />
            {error && <h4>{error}</h4>}
            <br />
            {!loading && todo && (
                <>
                    <h1>{todo.title}</h1>
                    <h2>{todo.id}</h2>
                </>
            )}
            <br />
            <Search onChange={fetchTodo} />
        </>
    );
}

Strangely on first render and first input everything works as expected. But the aborted controller for some reason does not reset back into a new abortController but I can’t seem to figure out why.

Proportional text scaling (Konva)

I need to scale a text in both directions but also be able to crop it with ‘middle-right’ or ‘middle-left’ anchor.

The code is below (which is basically modified version of the official example), but there are couple of issues:

  • Transform frame shakes and glitches when I try to minimize by middle anchors
  • It randomly expands to thousands px width
  • Text not always scales correctly

I’m looking for better way to implement it.

var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height,
});

var layer = new Konva.Layer();
stage.add(layer);

// Function to create text nodes
function createTextNode(text, fontSize, x, y) {
  var textNode = new Konva.Text({
    text: text,
    fontSize: fontSize,
    draggable: true,
    wrap: 'none',
    x: x,
    y: y
  });

  var tr = new Konva.Transformer({
    nodes: [textNode],
    rotateEnabled: false,
    flipEnabled: false,
    anchorSize: 8,
    enabledAnchors: [
      'top-left',
      'top-right',
      'middle-right',
      'middle-left',
      'bottom-left',
      'bottom-right'
    ],
    // set minimum width of text
    boundBoxFunc: function(oldBox, newBox) {
      newBox.width = Math.max(40 * textNode.scaleX(), newBox.width);
      return newBox;
    }
  });

  layer.add(textNode);

  textNode.on('transform', function(e) {
    textNode.width(tr.width() / textNode.scaleY());
  })

  layer.add(tr);
  tr.hide();

  textNode.on('click', function(e) {
    tr.show();
  });

  textNode.on('dblclick dbltap', () => {
    // hide text node and transformer:
    textNode.hide();
    tr.hide();

    // create textarea over canvas with absolute position
    // first we need to find position for textarea
    // how to find it?

    // at first lets find position of text node relative to the stage:
    var textPosition = textNode.absolutePosition();

    // so position of textarea will be the sum of positions above:
    var areaPosition = {
      x: stage.container().offsetLeft + textPosition.x,
      y: stage.container().offsetTop + textPosition.y,
    };

    // create textarea and style it
    var textarea = document.createElement('textarea');
    document.body.appendChild(textarea);

    // apply many styles to match text on canvas as close as possible
    // remember that text rendering on canvas and on the textarea can be different
    // and sometimes it is hard to make it 100% the same. But we will try...
    textarea.value = textNode.text();
    textarea.style.position = 'absolute';
    textarea.style.top = areaPosition.y + 'px';
    textarea.style.left = areaPosition.x + 'px';
    textarea.style.width = textNode.width() - textNode.padding() * 2 + 'px';
    textarea.style.height =
      textNode.height() - textNode.padding() * 2 + 5 + 'px';
    textarea.style.fontSize = textNode.fontSize() * textNode.scaleY() + 'px';
    textarea.style.border = 'none';
    textarea.style.padding = '0px';
    textarea.style.margin = '0px';
    textarea.style.overflow = 'hidden';
    textarea.style.background = 'none';
    textarea.style.outline = 'none';
    textarea.style.resize = 'none';
    textarea.style.lineHeight = textNode.lineHeight();
    textarea.style.fontFamily = textNode.fontFamily();
    textarea.style.transformOrigin = 'left top';
    textarea.style.textAlign = textNode.align();
    textarea.style.color = textNode.fill();
    textarea.style.whiteSpace = 'nowrap';
    rotation = textNode.rotation();
    var transform = '';
    if (rotation) {
      transform += 'rotateZ(' + rotation + 'deg)';
    }

    var px = 0;
    // also we need to slightly move textarea on firefox
    // because it jumps a bit
    var isFirefox =
      navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
    if (isFirefox) {
      px += 2 + Math.round(textNode.fontSize() / 20);
    }
    transform += 'translateY(-' + px + 'px)';

    textarea.style.transform = transform;

    // reset height
    textarea.style.height = 'auto';
    // after browsers resized it we can set actual value
    textarea.style.height = textarea.scrollHeight + 3 + 'px';

    textarea.focus();

    function removeTextarea() {
      textarea.parentNode.removeChild(textarea);
      window.removeEventListener('click', handleOutsideClick);
      textNode.show();
      tr.show();
      tr.forceUpdate();
    }

    function setTextareaWidth(newWidth) {
      if (!newWidth) {
        // set width for placeholder
        newWidth = textNode.placeholder.length * textNode.fontSize();
      }
      // some extra fixes on different browsers
      var isSafari = /^((?!chrome|android).)*safari/i.test(
        navigator.userAgent
      );
      var isFirefox =
        navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
      if (isSafari || isFirefox) {
        newWidth = Math.ceil(newWidth);
      }

      var isEdge =
        document.documentMode || /Edge/.test(navigator.userAgent);
      if (isEdge) {
        newWidth += 1;
      }
      textarea.style.width = newWidth + 'px';
    }

    textarea.addEventListener('keydown', function(e) {
      // hide on enter and esc
      if (e.keyCode === 13 || e.keyCode === 27) {
        textNode.text(textarea.value.replaceAll('n', ' '));
        removeTextarea();
      }
    });

    textarea.addEventListener('keydown', function(e) {
      scale = textNode.getAbsoluteScale().x;
      setTextareaWidth(textNode.width() * scale);
      textarea.style.height = 'auto';
      textarea.style.height =
        textarea.scrollHeight + textNode.fontSize() + 'px';
    });

    function handleOutsideClick(e) {
      if (e.target !== textarea) {
        textNode.text(textarea.value);
        removeTextarea();
      }
    }
    setTimeout(() => {
      window.addEventListener('click', handleOutsideClick);
    });
  });

}

// Call the function to create text nodes
createTextNode('Text 1', 20, 50, 50);
createTextNode('Text 2', 20, 150, 150);
createTextNode('Text 3', 20, 250, 250);
body {
  margin: 0;
  padding: 0;
  background-color: #f0f0f0;
}
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<div id="container"></div>

how to use script tag inside of a dynamicly added piece of code for an ad

i have this card, which includes the ad. I wanted to add this everytime i called my ajax.

what ive tried is just putting the whole card in a

document.getElementById("feed_container).insertAdjacentHTML('beforeend', ' <div class="card mt-3 mb-3 bg-dark text-white">
                        <div class="card-body" >
                          <h6 class="card-subtitle mb-2 text-muted">Sponsored Content, sorry :(</h6>
                          <div id="ad-body" class="card-content col d-flex justify-content-center">
                            <script async="async" data-cfasync="false" src="//pl22464107.profitablegatecpm.com/70dc149ec489e883ffe0c36bd73d05d0/invoke.js"></script>
                                <div id="container-70dc149ec489e883ffe0c36bd73d05d0"></div>
                          </div>
                        </div>
                    </div>
                </div>')

<div class="card mt-3 mb-3 bg-dark text-white">
                        <div class="card-body" >
                          <h6 class="card-subtitle mb-2 text-muted">Sponsored Content, sorry :(</h6>
                          <div id="ad-body" class="card-content col d-flex justify-content-center">
                            <script async="async" data-cfasync="false" src="//pl22464107.profitablegatecpm.com/70dc149ec489e883ffe0c36bd73d05d0/invoke.js"></script>
                                <div id="container-70dc149ec489e883ffe0c36bd73d05d0"></div>
                          </div>
                        </div>
                    </div>
                </div>

React-Form-Hook doesnt prevent submission for inValid field

im trying to submit form with 3 fields, trying to validate those fields, if not valid, form shouldn’nt be submitted.(obviously)

other 2 fields working properly, when in try to add price field, if its invalid(crossing max limit) it gives error message and field turns red as i coded using “errors.fieldname”, which means react-form-hook validating the field. but when i submit the form, befor submission, that validation error dissappeares and form submits
note: problem is just with max validation.

im using custom-input element/child component to formate price value as currecy.

tried controller, not helping.
tried different modes, not helping.
also not getting similar bug on google.

here is the code, related to the bug:


const AddEditPhotography: React.FC<IAddEditPhotographyProps = ({isEditPhotography,showScreen,handlePhotographyClose, handleAddPhotography, currentPhotographyData, cityDropDownList }) = {

const maxPrice = 9999999999999999.99

const { register, handleSubmit, reset, setValue, formState: { errors, isValid } } = useForm<IPhotography>({mode: "onChange"});

    useEffect(() => {
      reset(currentPhotographyData)
    }, [isEditPhotography, setValue, showScreen, currentPhotographyData]);
    
    const beginSubmit = async (data: any) => {
      console.log(errors.price)          // undefined
      data.price = removeNumberFormatting(data.price.toString());
      handleAddPhotography(data);
    }
    return (
              <form onSubmit={handleSubmit(beginSubmit)}>           
                <TextField
                  id="name"
                  label="Photography Name"
                  error={!!errors.name}
                  helperText={getError("name")}
                  {...register("name", {
                    required: true,
                    maxLength: maxNameLength,
                    minLength: minNameLength,
                  })}
                />
                <TextField
                  id="description"
                  label="Description"
                  error={!!errors.description}
                  helperText={getError("description")}
                  {...register("description", {
                    required: true,
                    minLength: minDescriptionLength,
                    maxLength: maxDescriptionLength 
                  })}
                />
                <TextField
                  id="price"
                  label="Price"
                  error={!!errors.price}
                  helperText={getError("price")}
                  {...register("price", {
                    required: true,
                    max: maxPrice,
                  })}
                  InputProps={{
                    inputComponent: NumericFormControl as any,
                  }}
                  value={isEditPhotography
                    ? currentPhotographyData?.price || "" : undefined
                  }
                />
                <Button variant="contained"  className="btn-save" type="submit">
                  Save
                </Button>
                <Button onClick={onModalClose}>
                  Cancel
                </Button>
              </form>
    );

};
 

here is the child component/NumericFormControl:

interface CustomProps extends NumericFormatProps {
  onChange: (event: { target: { name: string; value: string } }) => void;
  name: string;
}
const prefix = "₹"
  
export const removeNumberFormatting = (value: string): Number => {
  const prefixRegex = new RegExp(prefix, "g");
  value = value.replace(prefixRegex, "").replace(/,/g, "");
  return parseFloat(value);
}

const NumericFormControl = React.forwardRef<NumericFormatProps, CustomProps>(
  function NumericFormatCustom(props, ref) {
    const { onChange, ...other } = props;

    return (
      <NumericFormat
        {...other}
        getInputRef={ref}
        allowNegative={false}
        onValueChange={(values) => {
          onChange({
            target: {
              name: props.name,
              value: values.floatValue?.toString() || "",
            },
          });
        }}
        thousandSeparator
        valueIsNumericString
        prefix={prefix}
      />
    );
  },
);

this is my first question on stack-over-flow, sorry for big chunck of code, i tried my best to remove unnecessary things.

im getting same bug on different scenario, can someone also tell that in which cases/scenarios this happens?

Freshly reinstalled VS Code JavaScript public class Main {} gives: SyntaxError: Unexpected token ‘class’

I am new to Visual Studio Code and can’t figure this one out. Code (yeah, that’s all):

public class Main {
    public static void main(String[] args){
        System.out.println("Hello World");
    }
}

Full error text:

public class Main{}
       ^^^^^

SyntaxError: Unexpected token 'class'
    at internalCompileFunction (node:internal/vm:77:18)
    at wrapSafe (node:internal/modules/cjs/loader:1290:20)
    at Module._compile (node:internal/modules/cjs/loader:1342:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1437:10)
    at Module.load (node:internal/modules/cjs/loader:1212:32)
    at Module._load (node:internal/modules/cjs/loader:1028:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:142:12)
    at node:internal/main/run_main_module:28:49

Node.js v21.6.1

(regular class Main{} works for some reason, though…)

Already reinstalled VS Code, installed Node.js and JDK, tried restarting my PC etc. Other programming languages work as intended. Maybe I missed something? Saw a similar question on here but didn’t quite help… Also tried to replce “class” with “function”, didn’t work either.

Persist state via URL query parameters while avoiding long strings

  • I’m persisting some state in my application via URL query parameters.
  • The state is used to determine filters/sorts applied to a table.
  • The issue is that the resulting string can get too long.
  • I’m trying to find reliable ways to shorten the string but keep all the information I need.
  • Security isn’t a concern – I don’t care if the user can decode the compressed value.
  • The parameters I’m adding could be up to 200 characters (after calling encodeURIComponent).

Below is some additional information about the data structure I’m trying to save, and some things I’ve tried.

I’m thinking that compressing the string in this way isn’t going to work, but I’m not sure. So, overall, here are my questions:

  1. Is it possible to compress a string of up to/around 200 characters to something significantly shorter (30-40 characters?), and still be able to reliably decompress it?
  2. Is there a better approach to persisting this kind of information via URL than trying to compress it?

This is part of a React/Next app, but I’m not looking to use an external state manager like Redux.


Data structure

Below is the data I’m attempting to save to the URL. About 4 different parameters to later be retrieved and used.

{
    // Length of the arrays may be about 1-5 elements each.
    property1: string[],
    property2: string[],
    // Length of the strings may be up to about 10 characters each.
    property3: string,
    property4: string,
}

It’s possible there may be more/less parameters in the future, with varying data types. I’m looking for a generalized solution, but it’s never going to be wildly different than this.


Attempt 1: Convert to base64

Using btoa and atob, I tried converting the string to base64 before saving it to the URL.

The resulting string is at least around the same length, if not longer, so it’s not suitable.


Attempt 2: Compress the string

Using pako, which is a JS port of zlib, I tried compressing the string before saving it to the URL.

const compressed = pako.deflate(encodeURIComponent(JSON.stringify(objectToStore)))

deflate returns a Uint8Array. When converted to a string, this ends up much longer than a base64-encoded string or just the raw string itself.

I also attempted to convert the Uint8Array to base64 or even hexadecimal, but it’s still too long.

I’ve seen other compression libraries but generally they’d probably have the same results.


Attempt 3: Cryptographic solution

This wasn’t tenable because, while a cryptographically-secure hash could probably be significantly shorter, I wouldn’t be able to decode it from what I understood after reading many other questions along these lines.

An example of what I was hoping would work is the library object-hash, but since it’s intended for cryptographic solutions, it’s intentionally one-way only.


Attempt 4: Disguise the URL

I’m using Next, so I have the option to disguise/decorate the URL to hide these parameters via the as parameter of the Next/router:

router.replace(`domain.com/page?sort=${hashedObj}`, 'domain.com/page')

This allows me to hide the URL query parameters from view, but it’s not usable because if the page is refreshed/reloaded, those hidden parameters are no longer part of the URL. So it unfortunately defeats the whole purpose of having them there in the first place.


I’m not entirely sure how to approach it beyond this point. I could do something like save this data to local storage, or even to a server, but I’d rather avoid that since persisting it via the URL would be so much easier. My implementation to persist to the URL already works, I just need to find a way to make the resulting URL somewhat shorter for presentation purposes.