how i can pass props in redux? and save it global

import axios from "axios";
import React, {useEffect, useState} from "react";

in loginUser i get sucessfuly the username ,and redirect …but befor redirect it

const url = `https://api.agify.io`


export const loginUser = (values, history, setFieldError, setSubmitting) => {
    const username = values.email.split("@")[0]
    return () => {
        axios.get(url,{
            params:{
                name:username
            }
        }).then((response) => {
            console.log("username", username)

//here i should save username for use it globall

            console.log("response", response)
            history.push("/user")
        }).catch(error => console.error(error))
        setSubmitting(false);
    }
}

i should use the user name that come from loginUser for showing it in my code on Userinfo,after getting that props save it globally,for using everywhere,
after that should work axios call

export const Userinfo = () => {
    const [state, setState] = useState({info: []});
    useEffect(() => {
        axios
            .get("https://api2.binance.com/api/v3/ticker/24hr")
            .then((response) => {
                setState({
                    info: response.data
                });
                console.log(response.data);
            });
    }, [])
    const {info} = state;
    return (
        <div>
            <h2>post!</h2>
            {info.map((user) => (
                <div key={user.data}>
                    <h6>{user.count}</h6>
                </div>
            ))}
        </div>
    );
}


this code i write in redux component

here is my code
https://codesandbox.io/s/agitated-cherry-rfrj6?file=/src/auth/actions/userActions.js

Is it possible assign the checked state to the value of the current checkbox in razor form without onclick method?

I have an ASP.Net Core MVC Web Application project.
I want to send the checkbox’s checked state as the value to the model’s related parameter on form submit.
I have seen so many examples that using jquery to get/set the value of the checkbox via onchange methods.

What I wonder is that is it possible to assign the current checkbox’s checked state to the value in a similar way to the code below.(it doesn’t work)

<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActiveTournament" value="(this.checked)" 

One of the simplest working examples I found is the following but it returns false if the checkbox is checked by default and its state is not changed.

<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActive" onchange="if(this.checked) this.value='true'; else this.value='false';" >

I know that there are many ways to achieve what I want but I want the cleanest solution.

Thanks in advance!

Splitting a multiline string by regex ha unwanted elements in result array

I’m trying to split a multiline string using a regex.

const regexCommitSha = RegExp(/([0-9a-f]{7})s/m)
const result = commits.split(regexCommitSha)
console.log(result)

This is my multiline string (commits):

1234567 fix: simple bug fix
apps/backend/src/lib/file.ts
1234567 fix: second bug fix
apps/backend/src/lib/file.ts
apps/frontend/src/lib/file.ts
1234567 feat: new feature
apps/frontend/src/lib/file.ts
1234567 feat: second feature
apps/frontend/src/lib/file.ts

And this is my result:

[
  '',
  '1234567',
  'fix: simple bug fixnapps/backend/src/lib/file.tsn',
  '1234567',
  'fix: second bug fixn' +
    'apps/backend/src/lib/file.tsn' +
    'apps/frontend/src/lib/file.tsn',
  '1234567',
  'feat: new featurenapps/frontend/src/lib/file.tsn',
  '1234567',
  'feat: second featurenapps/frontend/src/lib/file.ts'
]

Why do I have the empty string as first element and why do I have '1234567'-elements in my result array? As this is my splitter, I thought this is not existing in the result.

I would expect

[
  'fix: simple bug fixnapps/backend/src/lib/file.tsn',
  'fix: second bug fixn' +
    'apps/backend/src/lib/file.tsn' +
    'apps/frontend/src/lib/file.tsn',
  'feat: new featurenapps/frontend/src/lib/file.tsn',
  'feat: second featurenapps/frontend/src/lib/file.ts'
]

What am I doing wrong?

I need help so i can display the users balance once they connect

    //---------------------------connect wallet------------------------------\

    window.userWalletAddress = null
    const loginButton = document.getElementById('connectWallet')
    const userWallet = document.getElementById('userWallet')

    function toggleButton() {
      if (!window.ethereum) {
        loginButton.innerText = 'MetaMask is not installed'
        return false
      }

      loginButton.addEventListener('click', loginWithMetaMask)
    }

    async function loginWithMetaMask() {
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
        .catch((e) => {
          console.error(e.message)
          return
        })
      if (!accounts) { return }

      window.userWalletAddress = accounts[0]
      userWallet.innerText = window.userWalletAddress
      loginButton.innerText = 'Sign out of MetaMask'

      loginButton.removeEventListener('click', loginWithMetaMask)
      setTimeout(() => {
        loginButton.addEventListener('click', signOutOfMetaMask)
      }, 200)
    }

    function signOutOfMetaMask() {
      window.userWalletAddress = null
      userWallet.innerText = ''
      loginButton.innerText = 'Sign in with MetaMask'

      loginButton.removeEventListener('click', signOutOfMetaMask)
      setTimeout(() => {
        loginButton.addEventListener('click', loginWithMetaMask)
      }, 200)
    }

    window.addEventListener('DOMContentLoaded', () => {
      toggleButton()
    });

    // ---------------------------------------------------------\



    const testnet = ' https://data-seed-prebsc-1-s1.binance.org:8545/';
    const walletAddress = document.getElementById('userWallet').innerText;

const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
var balance = web3.eth.getBalance(walletAddress); //Will give value in.
balance = web3.toDecimal(balance);

ok so i’m trying to get the users current smart chain balance to show in the console for now but when i try to grab the data of the wallet address

(which shows in an element with an ID of userWallet after they connect)

but when i try to grab the elements inner text it shows as undefined in the terminal
but if i put an actual address without trying to grab but rather as a string it works correctly.

I honestly think i should get better at javascript before diving into this web3 stuff but i’m stubborn and want this to work lol.

also if anyone wants to help with a little project of mine let me know and ill see how i can contact you (i don’t know if its against the rules to post my telegram here yet)

Ellipsize middle of string in Javascriptt

I am currently trying to create a function that will ellipsize the middle of a text string. The idea is for it to show the first five characters and the last five characters. The middle of the string will just show as

So for example if I have dkjkjfdljfldkjfssdfsf

It should show as

dkjkj…sdfsf

I so far have this function:

function ellipsizeIt(text, length) {
if (text.length > length) { return ${text.substring(0, length)}...${text.substring(0, length)}; }
return text;
}

But its just repeating the string first five characters when I do:

ellipsizeIt(text, 5);

It will show as

dkjkj…dkjkj

Any way to do it so that it doesnt just repeat the first five characters in the end of the string and show the actual last 5 characters?

Problems in understanding javascript nested for loops

I try to understand nested for loops in javascript but it’s very confusing.

I have this code and I can’t understand how it works:

let n = 5;
for (let i = 0; i < n; i++) {
    for (let j = 0; j < i; j++) {
    console.log(j);
}}

In console I have : 0
1
0
1
2
0
1
2
3

And I’m trying to figure out which loop represent each number.

Converting HTML string into list of words

Given a HTML string, such as:

const htmlString = "
    <h1 style='background-color: red'>Homepage</h1>
    <h2>Welcome back!</h2>
"

How would one go about converting this into a list of words (including html tags), for example:

const output = ["<h1 style='background-color: red'>", "Homepage", "</h1>", "<h2>", "Welcome", "back", "!", "</h2>"]

I’ve tried regex, but run into issues when there are html-like elements within the plain text.

Trouble canva to image C#

Have been going through a process of being able to add in an image what I paint on a canvas.

I am working on the asp.net form and I rely on JavaScript to be able to paint the movements of the cursor on the canva.

<table id="Table8" class="table table-striped table-bordered table-hover" style="width: 100%" runat="server">
    <tr>
        <td>
            <label>Espacio habilitado para firma del cliente.</label></td>
    </tr>
    <tr>
        <td>
            <canvas id="Canvas1" runat="server" style="border: outset;"></canvas>
            <br />
            <asp:button id="Button1" runat="server" text="Limpiar Firma" onclick="limpiar_Click" />
            Fecha de Firma:
            <asp:label id="Label1" runat="server"></asp:label>
            <script src="/Scripts/scriptEntrega.js" type="text/javascript"></script>
            <script>
                function verimage() {
                    const canva = document.querySelector("pizarra");
                    const dataURI = cav.toDataURL('image/jpg');
                    Image2.src = dataURI;
                }
            </script>
        </td>
        <td>
            <asp:image id="Image3" runat="server" />
        </td>
    </tr>
</table>

So far everything works perfect, I can do the perfect painting process, but now I need to store the image, for which I am trying to convert the canvas into an image and later the image to convert it into an array.

In the same form I have a button, which when pressed calls from the C # codebehind a JavaScript function, with which I try to pass the canvas to the image, but nothing appears to me and on the contrary it deletes everything I paint.

<td style="text-align: center">
    <asp:Button ID="ButtonSubmit" class="btn btn-primary" runat="server" Text="Guardar" OnClick="ButtonSubmit_Click" />
</td>

event

 protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            string script = "window.onload = function() { verimage(); };";
            ClientScript.RegisterStartupScript(this.GetType(), "verimage", script, true);
        }

I do not know why the above happens, but if you could enlighten me, I would appreciate it.

Discord.js how use button several times

             const row = new MessageActionRow().addComponents(
                new MessageButton()
                .setCustomId("1")
                .setStyle("PRIMARY")
                .setLabel("button 1"),
                new MessageButton()
                .setCustomId("2")
                .setStyle("PRIMARY")
                .setLabel("button 2"),
                new MessageButton()
                .setCustomId("3")
                .setStyle("PRIMARY")
                .setLabel("button 3")
                );

                collected.reply({ content: "YEYEYEEE TEXT", components: [row], ephemeral: true})

                const filter = (interaction) => {
                    if(interaction.user.id === message.author.id) return true;
                    return interaction.reply({ content: "An error has occurred", ephemeral: true }) 
                }

                const collectorValue1 = message.channel.createMessageComponentCollector({filter, max: 1})

                collectorValue1.on("end", (ButtonInteraction) => {
                    const id = ButtonInteraction.first().customId;
                    if(id == '1') {
                        ButtonInteraction.first().reply({ content: "CONTENT", ephemeral: true })
                    } else if(id == '2') {
                        ButtonInteraction.first().reply({ content: "CONTENT", ephemeral: true })
                    } else if(id == '3') {
                        ButtonInteraction.first().reply({ content: "CONTENT.", ephemeral: true })

                    }
                })

I would like when the buttons are created they are multiple executable, however I can only use the button once, after that I always get the message “This interaction failed.” how can I make the buttons multiple executable?

how to get last weekday for a given date

I am trying to get the last weekday for a given date in my google sheets for which I have written the below custom function. If it is a saturday or sunday then i want to get the last friday which I assume is a weekday (leaving out edge cases where friday could be a holiday as well)

This does not work and I get the below ERROR. Can you please let me know where I am going wrong?

“An error occurred in the script, but there is no error code: Error: Cannot return an invalid date.”
In my

In my google sheets I am trying to call it as below
enter image description here

function lastBusinessDay(passedDate) {
  mydate = new Date(passedDate);
  console.log('date recieved ' + mydate);
  if(mydate.getDay()==1)
    return new Date(today.getFullYear(), today.getMonth(), today.getDate() - 2);
  else if(mydate.getDay()==6)
    return new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
  else
    return mydate;  
  
}

React Stacknavigator with Sidebar

i have a StackNavigator but want to display a sidebar like with the drawer navigation. I am using react-navigation 5.X.
Since the problem with the drawer navigator is with different params in the url not reloading the page.

Is there a nice solution for this problem?

How to call a function in a server side node file from a client side file

I have a Node.js file that contains a function which writes to local files. I need to call this function from a client side JavaScript file. How can you do this?

I have seen questions about how to call server side functions on an HTML event, but not just strait from a client side script at any time.

Here is the script to write to the local file:

function writeCreateFile(filePath, newValue, callback) {
  checkIfFileExists(filePath, function(exists) {
    if(exists){
      fs.writeFileSync(path.join(__dirname, filePath), newValue, 'utf-8')
    } else {
      fs.appendFileSync(path.join(__dirname, filePath),newValue);
    }
    callback();
  })

}

function checkIfFileExists(filePath, callback) {
  fs.readFile(filePath, 'utf-8', function(err, data) {
   callback(err);
 });
}

Has anyone seen a weird JavaScript multiplication error like this? 9.4 * 3.6 = 0.03127079174983367?

I’m converting from meters/second to kilometers/hour. Very straighforward, right?

enter image description here

So, 9.4 * 3.6 = 33.84, right? Well, step forward with the debugger, and…

enter image description here

0.03127079174983367!?

This is happening using Node.js v14.16.0. I’m going to update my Node.js version and see if that helps, but this is very weird. I’m using TypeScript, so I suppose this could also be a transpilation error.

If I use conditions.windSpeed = conditions.windSpeed * 3.6 the problem goes away.