React reducer – state not accessible within reducer function

In my app I have the following state/reducer setup:

const initialState = {
  inputValues: {
    username: "",
    fullName: "",
    email: "",
    password: ""
  },
  inputValidities: {
    username: false,
    fullName: false,
    email: false,
    password: false
  },
  formIsValid:false
}

const [state, dispatch] = useReducer(reducer, initialState);

I then call dispatch to update the state:

dispatch({type: "handleInputChanged", payload: {id, value, validationResult: result}})

My reducer looks like so:

export function reducer(state, action) {
    switch(action.type) {
        case "handleInputChanged":
            const {id, value, validationResult} = action.payload
            console.log(state.inputValues);

    }
}

When attempting to log state.inputValues, an error ooccurs stating: Cannot read properties of undefined (reading ‘inputValues’).

How am I able to access the current state input values? Thanks.

Generate a word document from a simple form

I am trying to modify a word document with data retrieved via a form without success. Please help me. My code manages to retrieve the data from the form when I look in the console but no file is downloaded.

My form:



<form id="myForm">

        <label for="name">Nom:</label>

        <input type="text" id="name" name="name" value="John"><br>

        <label for="email">Email:</label>

        <input type="email" id="email" name="email" value="[email protected]"><br>

       

        <button id="generate">Générer le document</button>

    </form>


JS file:


<script

 src="https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.39.1/docxtemplater.js"></script>

    <script src="https://unpkg.com/[email protected]/dist/pizzip.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>

    <script src="https://unpkg.com/[email protected]/dist/pizzip-utils.js"></script>

    <script>

        function loadFile(url, callback) {

            PizZipUtils.getBinaryContent(url, callback);

        }


window.generate = function generate() {

    // Récupérer le formulaire par son ID

    const form = document.getElementById('myForm');

    

    // Utiliser FormData pour obtenir les données du formulaire

    const formData = new FormData(form);

    

    // Convertir les données du formulaire en un objet JavaScript

    const data = {};

    formData.forEach((value, key) => {

        data[key] = value;

    });

    console.log("Données du formulaire:", data); // Afficher les données extraites du formulaire

    loadFile(

        "doc.docx",

        function (error, content) {

            if (error) {

                console.error("Erreur lors du chargement du fichier doc.docx:", error); // Afficher les erreurs de chargement

                return;

            }

            const zip = new PizZip(content);

            const doc = new window.docxtemplater(zip, {

                paragraphLoop: true,

                linebreaks: true,

            });

            // Rendre le document avec les données du formulaire

            doc.render(data);

            const blob = doc.getZip().generate({

                type: "blob",

                mimeType:

                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",

                compression: "DEFLATE",

            });

            // Enregistrer le document avec un nom basé sur le nom saisi dans le formulaire

            saveAs(blob, "Contrat_" + data.name + ".docx");

        }

    );

};
</script>

I have a form containing several fields. I want to be able to use form fields to fill out a word document template. My code doesn’t seem to work, I can’t generate the word file.

What does the default output colorization of console.dir() represent in DevTools?

The console.dir() method available in your browser’s DevTools outputs object properties and accessors using colorized text. For example, this basic Vector Class:

DevTools console.dir() output showing a mix of yellow and gray property names

In this image we have internal methods ([[Method]]) in yellow with everything else in gray… With one exception, the from static method. But it isn’t the only static method, each method that begins with “from” is static, the only difference is that the base from method is declared inside of a static block rather than as an independent method using the static keyword.

The class is as follows:

class Vector {

  static  {
    this.from = function from(...args) {
      if (args.length === 2) return Vector.fromCoords(...args);
      const arg = args[0];
      if (Array.isArray(arg)) return Vector.fromArray(arg);
      if (typeof arg === 'string') return Vector.fromString(arg);
      if (typeof arg === 'object') return Vector.fromObject(arg);
      return new Vector();
    }
  }

  static fromString(string) {
    return new Vector(...string.split(' ').join('').split(','));
  }

  static fromObject({ x, y }) {
    return new Vector(x, y);
  }

  static fromCoords(x, y) {
    return new Vector(x, y);
  }

  static fromArray([x, y]) {
    return new Vector(x, y);
  }

  constructor(x, y) {
    this.x = Number(x) || 0;
    this.y = Number(y) || 0;
  }

  get angle() {
    const { x, y } = this;
    return x > 0 ?
      y > 0 ?
        Math.atan(Math.abs(y / x)) :
        Math.atan(Math.abs(x / y)) + (3 * Math.PI) / 2 :
      y > 0 ?
        Math.atan(Math.abs(x / y)) + Math.PI / 2 :
        Math.atan(Math.abs(y / x)) + Math.PI;
  }

  set angle(_) {
    console.error('SET:angle is prohibited on instances of Vector');
  }

  get degrees() {
    return this.angle * 180 / Math.PI;
  }

  set degrees(_) {
    console.error('SET:degrees is prohibited on instances of Vector');
  }

  get magnitude() {
    const xSquared = this.x ** 2;
    const ySquared = this.y ** 2;
    return Math.sqrt(xSquared + ySquared);
  }

  set magnitude(_) {
    console.error('SET:magnitude is prohibited on instances of Vector');
  }

  add(object, ...args) {
    const vector = object instanceof Vector ? object : Vector.from(object);
    this.x += vector.x;
    this.y += vector.y;
    return this;
  }

  clone() {
    return Vector.from(this);
  }

  isWithinBounds(point, size) {
    const halfSize = size / 2;
    point = Vector.from(point);
    const { x, y } = point;
    return this.y >= y - halfSize
      && this.y <= y + halfSize
      && this.x >= x - halfSize
      && this.x <= x + halfSize;
  }

  scale(multiplier) {
    this.x *= multiplier;
    this.y *= multiplier;
    return this;
  }

  subtract(vector) {
    return new Vector(this.x - vector.x, this.y - vector.y);
  }

  toString() {
    const xString = this.x.toFixed(3).replace(/.?0+$/, '');
    const yString = this.y.toFixed(3).replace(/.?0+$/, '');
    return `${xString}, ${yString}`;
  }
}

The console output was written using console.dir(Vector); on Microsoft Edge.

I was expecting to find an answer buried in the Google Developer Forums, MDN, or on Stack Overflow and was quite surprised when I didn’t.

My current assumption is that gray methods are those that were declared and have not been modified at runtime, whereas yellow methods have either been programmatically updated or otherwise have scopes beyond their declaration. This makes sense to me, as accessing private static variables when you have multiple static initialization blocks on a class can be a bit tricky and occasionally takes witchcraft and magic smoke to function correctly, especially when you’re instantiating the prototype from inside.

How to connect to a URL without visiting or loading the page using NextJS getServerSideProps?

I am trying to briefly connect to a url to utilize the back-end service that is triggered on window.onLoad(). This means the window has to load for the back-end services to occur.

I’ve been trying to find a way to avoid viewing the intermediate URL overall, thus I’ve considered opening and closing the URL with a separate tab by using this method which is not ideal.

let openTab = window.open("INTERMEDIATE URL", "_blank");
openTab.blur();
openTab.close();

Is there a way to briefly direct to the intermediate url and redirect back to the end destination using NextJS getServerSideProps?

export async function getServerSideProps({params}) {
  window.open("INTERMEDIATE URL", "_self");
    return {
      redirect: {
        permanent: false,
        destination: 'FINAL URL'
      }
    }
}

Any ideas or work around would be appreciated.

Script omitting trailing zeros – any easy way to always keep two decimals?

I have a script that animates a counter from 0 to a pre-determined value (number in Euros, located in the HTML). It’s using jQuery, but i don’t think it matters in this case.

The output is displayed with two decimal places. But if the last digit is a zero, like in 1380.20 €, it is displayed as 1380.2 €. For some reason, the script is omitting digits, if those are zeros. Is this a bug in jQuery, or is this by design?

This is the code:

var euroTotal = $('.euroTotal').text();   
$({numberValue: 0}).animate({numberValue: euroTotal}, {
                duration: 3000,
                easing: 'swing',
                progress: function() {
                    $('.euroTotal').text(Math.ceil(this.numberValue*100)/100 + " €");
                }
            });

Unfortunately, i’m a total beginner in Javascript. My research shows that i can use toFixed(2), but i lack the knowledge of how to implement this method here.

Would someone be kind enough to teach me how to modify this?

Google Apps Script – getting 404 exception despite try/catch block and muteExceptions

I’m trying to write a script to pull prices from a Magic: The Gathering card database called Scryfall. The script is able to get prices for normal versions of cards, but it has issues when it requests variant cards that are listed differently in Scryfall than they are in our inventory. I plan to handle that later. For now, I’m just trying to have the script revert to requesting info on the normal version of a card if it can’t grab the variant it wants.

Here’s the script for getting prices as-is. The sleep lines are there to comply with Scryfall’s request rate cap.

function getPrice(cardname, setCode, variant) {
  Utilities.sleep(100);
  var url = "https://api.scryfall.com/cards/named?fuzzy=" + encodeURI(cardname);
  if (setCode != "") { url + "set=" + setCode; }
  var response;
  try {
    JSON.parse(UrlFetchApp.fetch(url), {muteHttpExceptions: true});
  }
  catch {
    Utilities.sleep(30);
    url = url.split(' (', 1);
    console.log(url);
  }
  response = JSON.parse(UrlFetchApp.fetch(url));
  response = parseFloat(response.prices.usd);
  return response;
}

I run my script and it fetches prices for all the normal cards I’d like, but right now it’s getting stuck on a card called “Virtue of Persistence (Showcase)”. I checked that the string-splitting line inside the catch block is working properly (cutting the string down to “Virtue of Persistence”) and it is. Yet I’m still getting the following error when the script reaches that entry:

Exception: Request failed for https://api.scryfall.com returned code 404. Truncated server response: { “object”: “error”, “code”: “not_found”, “status”: 404, “details”: “No cards found matching “Virtue of Persistence (Showcase)”” } (use muteHttpExceptions option to examine full response)

This is confusing, because I am using muteHttpExceptions, and I’m using try/catch blocks to re-format the string and redo the request when an exception is hit, yet the script is still stopping execution on this line. Any ideas?

The initial version of the script didn’t use a try/catch block. I was just truncating all strings so they didn’t have any parenthetical text. I thought try/catch would keep the script from stopping execution when an error occurred. And when that didn’t work, I thought muteHttpExceptions would do the same. I’m not sure what to try next.

Value of button in my react app doesn’t change after i call hook function

After the button in my react app is clicked three things happen a random sound is played from my library of dj khaled saying random words, the associated picture is rendered after an animation is played curtesy of frame-motion and afterward once the picture is rendered i want the button on the text to say clear so the user clears out the text and picture and generate a new one and the cycle happens again however the value of the button (text) does not change here is the associated code.

import "./center.css"
import {Howl,Howler} from "howler"
import { asparagus,cappucino,chandelier,tigerwoods,pic_asparagus,pic_cappucino,pic_chandelier,pic_tigerwoods } from "./import"
import Navbar from './nav'
import {motion} from 'framer-motion'
import { useState } from "react"


const sounds=[
  {sound : asparagus, label:"asparagus",image:pic_asparagus},
  {sound : cappucino, label:"cappucino",image:pic_cappucino},
  {sound : chandelier, label:"chandelier",image:pic_chandelier},
  {sound : tigerwoods, label:"tigerwoods",image:pic_tigerwoods},
]

const variants = {
  disappear : {
    opacity : 0  
  },
  appear : {
    opacity: 1
  }
}

var flagito=true;

function playsound(src)
{
  const sound = new Howl({src,html5:true})
  sound.play();
}

function Center()
{
  Howler.volume(1.0)
  const [flag , setFlag] = useState(true)
    return(
      <div className="center">
        <Navbar />
        <div className="main">
            <h2>Let dj Khaled names things</h2>
            <div className="mainmain">
              <motion.img
              variants={variants} 
              initial={{opacity: flag ? 1 :0}}
              animate={{opacity: flag ? 0 :1}}
              id="picture"/>
              <input type="text" name="name" id="name" className="inputtext" placeholder="The name" readOnly />
              <input type="button" value="Generate" className="inputbutton" id="btn" 
              onClick={()=>{
                if(flagito)
                {
                  setFlag(!flag)
                  const index=Math.floor(sounds.length*Math.random())
                  playsound(sounds[index].sound)
                  document.getElementById("name").value=sounds[index].label
                  document.getElementById("picture").setAttribute("src",sounds[index].image)
                  document.getElementById("btn").value='Degenerate'
                  flagito=!flagito;
                }
                else
                {
                  setFlag(!flag)
                  document.getElementById("name").value=''
                  document.getElementById("btn").value='Generate'
                  flagito=!flagito
                }
                console.log(document.getElementById("btn").value)
              }} 
              />
            </div>
        </div>
      </div>  
    )
}

export default Center

this is my first react app so it is probably not top notch but i can’t for the life of me figure it out.
i tried removing the call to the hook function setFlag and that seems to allow the button to change values.

Ordering div list with decimal values group by value

After testing many solutions founded, none of them is sorting correctly. I need to sort a list grouped by a classification field:

<div id="idx-list-ctn" class="list-ctn">
    <div class="header-ctn">
        <div>Fornecedores</div>
        <div><img id="lst-order-by-btn" src="/Images/distance-19x19.png">Ordenar</div>
    </div>
    <div id="lst-19324" class="partner-ctn" data-classification="2" data-distance="2">
        <div class="info-wrp lp-blc-rate-2">
            <div class="info">
            </div>
        </div>
    </div>
    <div id="lst-19325" class="partner-ctn" data-classification="1" data-distance="2">
        <div class="info-wrp lp-blc-rate-2">
            <div class="info">
            </div>
        </div>
    </div>
    <div id="lst-19326" class="partner-ctn" data-classification="1" data-distance="2,2">
        <div class="info-wrp lp-blc-rate-2">
            <div class="info">
            </div>
        </div>
    </div>
    <div id="lst-19327" class="partner-ctn" data-classification="2" data-distance="1,9">
        <div class="info-wrp lp-blc-rate-2">
            <div class="info">
            </div>
        </div>
    </div>
    <div id="lst-19328" class="partner-ctn" data-classification="1" data-distance="0,9">
        <div class="info-wrp lp-blc-rate-2">
            <div class="info">
            </div>
        </div>
    </div>
    <div id="lst-19329" class="partner-ctn" data-classification="2" data-distance="1,7">
        <div class="info-wrp lp-blc-rate-2">
            <div class="info">
            </div>
        </div>
    </div>
</div>

This is the function I have build until now:

$("#idx-list-ctn").find('.partner-ctn').sort(function (a, b) {

    var aa = $(a).data('distance');
    var bb = $(b).data('distance');

    a = parseFloat(aa); // get the value of .score element inside a
    b = parseFloat(bb); // get the value of .score element inside b
    return b - a;                          // sort descendently
}).appendTo("#idx-list-ctn");

Without the classification grouping yet, I get the order 2 -> 2 -> 2,2 -> 1,9 -> 0,9

How to find repeating sequence in string in javascript [duplicate]

I need to find if a number starts repeating itself within a string.

I’m working with the results of math operations, for example, 1/3 or 4/7 gives results of 0.333333 and 0.57142857142 but the problem can be simplified by just taking into account the fraction part.

What I want to do is to shorten these numbers to 0.333… and 0.571428…

So I need to find a sequence that’s uninterrupted, repeating, of any length, and may not end exactly with the last characters in the last iteration (571428 actually doesn’t repeat in the 0.57142857142 but I need to match it nevertheless).

I guess the solution would be to take a substring of the first number (5) and enlarge it until I run into the same number again. Then I split the string into equally sized chunks, comparing them all, except the last one, where I only compare if it starts with the same sequence. If this check fails, I’ll keep enlarging until I run into another instance of the first number and repeat the process. If that all fails, I’ll start from the second number.
That should work, but it’s so many iterations it would kill the performance of the app.

Theoretically, I can ignore the last incomplete part of the repetition and check it in a separate step, but I need to find the pattern first.

(Just to give you an idea, I’m working with numbers like 0.5714285714285714285714285714285714285714285714285714285714285714 – so that’s enough digits for the repetition to occur at least once (unlike in 0.57142857142). Anything that doesn’t repeat within that length, I can safely assume to be non-repeating and simply round it up to a predefined length.)

Any ideas?

can’t get notification from expo notification after build apk

I am currently working on a React Native Expo application, and I’m trying to use Expo Notifications. It works well on Expo Go, but after building the APK, I can’t receive any notifications. Can anyone help me?
this is my app.js code :

import "react-native-gesture-handler";
import { StatusBar, StyleSheet } from "react-native";
import Stacks from "./src/Routes/Stacks";
import { I18nManager } from "react-native";
import NoConnectionScreen from "./src/Seller Screens/Screens/NoConnectionScreen";
import { useNetInfo } from "@react-native-community/netinfo";
import { useEffect, useRef, useState } from "react";
import * as Device from "expo-device";
import * as Notifications from "expo-notifications";
import AsyncStorage from "@react-native-async-storage/async-storage";
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});
try {
  I18nManager.allowRTL(false);
  I18nManager.forceRTL(false);
  // the next line is the most effective one
  I18nManager.swapLeftAndRightInRTL(false);
} catch (e) {
  console.log(e);
}
const App = () => {
  state = { rtl: false };
  const [isLoading, setIsLoading] = useState(true);
  const notificationListener = useRef();
  const responseListener = useRef();
  async function registerForPushNotificationsAsync() {
    let token;

    if (Platform.OS === "android") {
      await Notifications.setNotificationChannelAsync("default", {
        name: "default",
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: "#FF231F7C",
      });
    }

    if (Device.isDevice) {
      const { status: existingStatus } =
        await Notifications.getPermissionsAsync();
      let finalStatus = existingStatus;
      if (existingStatus !== "granted") {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }
      if (finalStatus !== "granted") {
        alert("Failed to get push token for push notification!");
        return;
      }
      token = await Notifications.getExpoPushTokenAsync({
        projectId: "b37ba3bc-286c-43a3-b3f2-ae2fa40ca6cd",
      });
      const expotoken = token.data;
      console.log(token.data);
      await AsyncStorage.setItem("expotoken", expotoken);
    } else {
      alert("Must use physical device for Push Notifications");
    }

    return token;
  }

  useEffect(() => {
    registerForPushNotificationsAsync();
    notificationListener.current =
      Notifications.addNotificationReceivedListener((notification) => {
        console.log(notification);
      });

    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        console.log(response);
      });

    return () => {
      Notifications.removeNotificationSubscription(
        notificationListener.current
      );
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);
  setTimeout(() => {
    setIsLoading(false);
  }, 20);
  const net = useNetInfo();

  return (
    <>
      <StatusBar backgroundColor={"#6c757d"} barStyle="light-content" />
      {net.isConnected == true && isLoading == false && <Stacks />}
      {net.isConnected == false && <NoConnectionScreen />}
    </>
  );
};
export default App;
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

tried
useNextNotificationsApi:true
and this
expo push:android:upload –api-key

react-chartjs-2 re-rendering line chart on mouseover of another component

I have a basic Line chart:

import {Line} from 'react-chartjs-2';

// .. options and data

<Line options={options} data={dataState}/>

On the same page I have a map I am using from react-simple-maps and I am using a mouseEnter() to try and set a hook — But every time I hover over one of my elements, the unrelated graph from charts-2 re-renders. How can I prevent this from happening?

My mouseEnter() event and the component it’s tied to:

<ComposableMap projection="geoAlbersUsa">
    <Geographies geography={geoUrl}>
        {({geographies}) => (
            <>
                {geographies.map(geo => {
                    const state = allStates.find(s => s.val === geo.id).id;
                    const val = allStates.find(s => s.val === geo.id).val;
                    const cur = data.find(s => s.id === state);
                    console.log(state)
                    return (
                        <Geography
                            key={geo.rsmKey}
                            stroke="#FFF"
                            geography={geo}
                            style={{
                                default: {
                                    fill: cur ? colorScale(cur.val) : "#EEE",
                                    stroke: "#607D8B",
                                    strokeWidth: 0.75,
                                    outline: "none",
                                },
                                hover: {
                                    fill: "#CFD8DC",
                                    stroke: "#607D8B",
                                    strokeWidth: 1,
                                    outline: "none",
                                },
                                pressed: {
                                    fill: "#28538a",
                                    stroke: "#607D8B",
                                    strokeWidth: 1,
                                    outline: "none",
                                },
                            }}
                            onMouseEnter={(event) => { setMetric(val) }}
                        />
                    )
                })}
            </>
        )}
    </Geographies>
</ComposableMap>

setMetric is just a hook that is initially set to 0.

Is it safe to have a website where users can add HTML using tinyMCE? The final HTML will also be stored in a database

As a junior developer, I acknowledge my limited knowledge regarding web security. Recently, I integrated a basic tinyMCE editor into my company’s website, enabling users to edit their profile page. The tinyMCE editor includes a “code” button in the toolbar along with a corresponding plugin, allowing users to save their content in HTML format to the MySQL database. However, I am apprehensive about the potential for XSS attacks, SQL injection, or other forms of attack. Given my limited familiarity with these types of attacks, I am uncertain if users could exploit these vulnerabilities to compromise the website’s security.

If your response is affirmative, kindly furnish me with a straightforward, *innocuous code illustration *suitable for presentation to non-technical personnel within the company. Additionally, elucidate the potential vulnerability associated with it.

Is there a way to create a cluster blob chart with text inside the bubble in react functional component without X and Y axis?

I want to achieve something like this: https://camo.githubusercontent.com/36e4135ac47b58f69aac98d9aced2f26b3adc157bb398117e39e79c747ea9739/687474703a2f2f692e696d6775722e636f6d2f4f514564674f572e676966

The Cluster blob chart (Bubble chart with text inside the bubble) (bubble should be resized according to the text length) without X and Y axis or grid in background in Reactjs.