Using Redux-Toolkit slice action with class components via connect HOC, does it require dispatch or not?

I have been working on an older code base with class components using Redux connect HOC. There are few RTK slices introduced before. I am abit confused as to why these 2 ways of using the action from the slice is working correctly (can see in Redux Toolkit that ways update the state and appear in the Actions panel (left hand side).

2 ways:

  1. with dispatch (updateAbc)
  2. without dispatch (updateXyz)

See example below

const mapDispatchToProps = (dispatch) => {
    return {
        updateAbc: (params) => dispatch(updateAbc(params)),
        updateXyz,
    }
}

Both are from the slice file:

const sampleSlice = createSlice({
   name: 'sample',
   initialState: {},
   reducers: {
      updateAbc: () => { /* do something */},
      updateXyz: () => { /* do something */}
   }
})
const { actions, reducer } = sampleSlice
export const {
    updateAbc,
    updateXyz,
} = actions

enter image description here

How come both are working or am I missing something or they are just both valid ways (but I don’t see how it dispatches it without the explicit call to dispatch)?

Why does canvas.toDataURL() and canvas.toBlob() produce corrupt images on Firefox?

On Chrome and Safari, I am not having problem generating a snapshot image of a video. However, I’ve been for hours trying several different things on Firefox, but the image always comes corrupted, with a “random color” each time.

Example minimal code – https://jsfiddle.net/4uy8j1bf/1/

Basically, I’m loading a video file into a <video element, and then draw it on a <canvas>, and from there, generate either a data URL or blob URL.

But, while Chrome and Safari have no problem getting the canvas image, Firefox always gives corrupt images, even if I seek / change the video time (any video).

The canvas image is drawn fine. It’s the generation of data/blob URL that doesn’t seem to work.

Do you know why? What can I do to get this working on Firefox?

Firefox:

Firefox - Canvas and Blob URL

Chrome:

Chrome - Canvas and Blob URL

The example code:

var _CANVAS = document.querySelector("#video-canvas");
var _CTX = _CANVAS.getContext("2d");
var _VIDEO = document.querySelector("#main-video");

$("#file").on('change', function() {

    // Object Url as the video source
    $("#main-video").attr('src', URL.createObjectURL($("#file")[0].files[0]));

    // Load the video and show it
    _VIDEO.load();
        _VIDEO.currentTime = 0;
        _VIDEO.play();

    // Load metadata of the video to get video duration and dimensions
    _VIDEO.addEventListener('loadedmetadata', function() {
        // Set canvas dimensions same as video dimensions
        _CANVAS.width = _VIDEO.videoWidth;
        _CANVAS.height = _VIDEO.videoHeight;
    });

    _VIDEO.addEventListener('canplay', function() {
        _CANVAS.style.display = 'inline';
        _CTX.drawImage(_VIDEO, 0, 0, _VIDEO.videoWidth, _VIDEO.videoHeight);
        
        // var dataUrl = _CANVAS.toDataURL('image/jpeg', 0.7);
        // $('body').append('<img src="'+dataUrl+'" />');
        
        _CANVAS.toBlob(blob => {
            if (blob) {
                const dataUrl = URL.createObjectURL(blob);
                $('body').append('<img src="'+dataUrl+'" />')
            } else {
                console.log('Error creating blob from canvas');
            }
        }, 'image/png');
    });
});

Is there a way to submit a form with multiple copies of the same fields (or component) in an organized way?

I’ve got the following component:

<script>
    export let componentID;

    console.log("component iD", componentID)
</script>

<div>
    <div class="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
        <div class="sm:col-span-3">
            <label class="label">
                <span class="label-text text-lg">Title</span>
            </label>
            <input type="text" name="track-title[][{componentID}]" class="input input-bordered input-lg w-full">
        </div>

        <div class="sm:col-span-1">
            <label class="label">
                <span class="label-text text-lg">Duration</span>
            </label>
            <input type="text" name="track-duration[][{componentID}]" class="input input-bordered input-lg w-full">
        </div>
    </div>
</div>

As you can see, this component contains only 2 input fields. I have the following route (+page.svelte) and what I want to do is to have multiple copies of the same component, something like this:

<script>
    import TrackForm from "../../components/forms/TrackForm.svelte";

</script>

<form method="POST">
    <TrackForm componentID="1" />

    <br/>
    <hr>
    <br/>
    <TrackForm componentID="2" />

    <button type="submit" class="btn-primary btn-wide btn-info mt-10">Save</button>
</form>

Eventually, the components will be added dynamically using a button, for now, this is a proof of concept.

The action in +page.server.js is not doing anything at the moment, just printing the submitted data:

export const actions = {
    default: async ({ request }) => {
        const data = Object.fromEntries(await request.formData());
        console.log("data:", data);

        return {}
    }
}

When submitting the form I’m getting the following:

data: {
  'track-title[][1]': 'aaaaa',
  'track-duration[][1]': '111',
  'track-title[][2]': 'vbbb',
  'track-duration[][2]': '2222'
}

What I’m wondering is whether there’s a way to automatically get the data in a better format, say:

[
   {
     "track-title": 'aaaaa',
     "track-duration": '111'
   },
   {
     "track-title": 'vbbb',
     "track-duration": '2222'
   }
]

or a library that does that.

react router not fetching data unless i reload

my idea is to set a login functionality where users could login and when submitting data the user would be redirected to home page, then his profile would show instead of login in the top corner, the problem seem that when i login and navigate to the home page and click on the profile, no data would be there unless i reload

in my server there is no data sent through the fetchToken function unless i reload even though i put loader to my page.

my submit function where i send data to backend and get back a token

async function handleSubmit(e: SyntheticEvent) {
    e.preventDefault();
    setSubmitting(true);
    // if no file selected set empty string to show error and don't send data
    if (!fileName) {
      setFileName("");
      setSubmitting(false);
      return;
    }
    const target = e.target as HTMLFormElement;
    const formData = new FormData(target);
    const response = await fetchLogin(formData);

    if (response.token) {
      localStorage.setItem("token", response.token);
      setSubmitting(false);
      
      navigate("..");
    } else {
      setError(response);
      setSubmitting(false);
    }
  }

my fetchLogin function

export async function fetchLogin(data: FormData) {
  try {
    const response = await fetch(`${URL}/onlineUsers/login`, {
      method: "POST",
      body: data,
    });
    const resData = await response.json()
    console.log(resData);
    
    return resData
  } catch (error) {
    // returns the error message if it exist
    return processError(error);
  }
}

my loader and login page

const LoginPage = () => {
  const data = useLoaderData() || {name:"",imageUrl:""}

   
  return (
    <div>
      <From  data={data as LoggedUserData}/>
    </div>
  );
};


export async function loginLoader() {
    const resData = await fetchToken()
    if(resData)return resData
    return;
}

my fetchToken function

export async function fetchToken(){
  const response = await fetch(`${URL}/onlineUsers/token`,{
    method:"POST",
    headers:{
      'Authorization':`Bearer ${token}`
    }
  })
  const resData = await response.json();
  return resData
}

in my backend, a fetch is sent but not with my token, what seems to be the problem? do i need to put my fetching function in redux state (thunk) ?

When trying to display fetched API data in react it isnt read, or i get an undefined error for the data

I am trying to display data of basketball players through a API fetch request in React. The API has data I can access such as firstname, lastname, teamname, teamlogo, and so on… I have the fetch request set up in my main App.jsx page and i then feed a prop i also have on App.jsx from my useState const named ‘players’, to the rendered cards page where i have simple cards logic to render the information of different players on each card. The issue is that i either get no errors and no displayed data from the API, or an error as follows for the first data property.

MultiplePlayerCards.jsx:59 Uncaught TypeError: Cannot read properties of undefined (reading ‘firstname’)

for clarity this is my App.jsx:

import { useState, useEffect } from "react";
import MultiplePlayerCards from "./components/MultiplePlayerCards";
import PlayerCard from "./components/PlayerCard";
import "./App.css";

const App = () => {
  const [players, setPlayers] = useState([]);

  useEffect(() => {
    const fetchMyEvents = async () => {
      try {
        const response = await fetch(
          "https://api-nba-v1.p.rapidapi.com/players/statistics?game=8133",
          {
            method: "GET",
            headers: {
              "x-rapidapi-key": "123456789",
              "x-rapidapi-host": "api-nba-v1.p.rapida pi.com",
            },
          },
        );

        if (response.ok) {
          const data = await response.json();
          setPlayers([data]);
        } else {
          throw new Error("Failed to fetch players");
        }
      } catch (error) {
        console.error("Error fetching players:", error);
      }
    };

    fetchMyEvents();
  }, []);

  return (
    <>
      <MultiplePlayerCards players={players} />
    </>
  );
};
export default App;

and the file where i have the mapping for each data property i want to display from the players, which is also fed into another card component, which i have for other purposes mainly animations.

import React from "react";
import { useState, useEffect } from "react";
import "./styles.css";
import PlayerCard from "./PlayerCard";
import { playerImages } from "../../player-images";

const MultiplePlayerCards = () => {
  return (
    <div className="app">
      <h1>NBA Player Stats</h1>
      <div className="car-container">
        {players && players.length > 0 ? (
          players.map((player, index) => (
            <PlayerCard
              key={index}
              firstName={player.player.firstname}
              lastName={player.player.lastName}
              fullName={`${firstName} ${lastName}`}
              teamName={player.player.teamName}
              teamLogo={player.player.teamLogo}
              points={player.player.points}
              assists={player.player.assists}
              rebounds={player.player.totReb}
              minutes={player.player.min}
              playerImage={playerImages[fullName]}
            />
          ))
        ) : (
          <p>No players found</p>
        )}
      </div>
    </div>
  );
};

export default MultiplePlayerCards;

so far I have tried to access firstname differently, with just player.firstname instead of player.player.firstname as this was the way i accessed it in a previous project where i just used vanilla JS, but still nothing worked.

returning the sums of the withdraws in bank accounts

I’m working on an exercise where I’m only allowed to use ‘for-loops’ for iterating through the material given. in this case bank accounts and return the sums of the widrawals in a new array, but if the account lacks withdrawals then have it return ‘0’

I’ve figured out how to return the sums of the bank accounts with withdraws I’m struggling trying to figure out how to return ‘0’ for the accounts with not withdraws the desired output should look like this
([300.68,0,5900,0,100]) but my function keeps returning this ([300.68,,5900,,100])
how can I make sure that any account without a “withdrawal” returns a 0?

this is what I Have so far

const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 0.0 },
  { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];



function itsSomething(array){
  let newArray = [];
  let total = [];
  for (let i = 0; i < array.length; i++){
  let numbs = array[i].withdrawals
   newArray.push(numbs||0 )
   let sum =0
   for (let x =0; x < newArray[i].length; x++){
  sum+=newArray[i][x]
  total[i]= sum
   
 }
 }



  return total
}


console.log(itsSomething(bankAccounts))

Why is newTabBrowser.contentDocument null?

Running the example code from the Firefox docs page about the Browser console.

https://firefox-source-docs.mozilla.org/devtools-user/browser_console/index.html

var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
newTabBrowser.addEventListener("load", function() {
 newTabBrowser.contentDocument.body.innerHTML = "<h1>this page has been eaten</h1>";
}, true);
newTabBrowser.contentDocument.location.href = "https://mozilla.org/";

Running it gives me the following error.

Uncaught TypeError: newTabBrowser.contentDocument is null
    <anonymous> debugger eval code:5
    getEvalResult resource://devtools/server/actors/webconsole/eval-with-debugger.js:306
    evalWithDebugger resource://devtools/server/actors/webconsole/eval-with-debugger.js:218
    evaluateJS resource://devtools/server/actors/webconsole.js:953
    evaluateJSAsync resource://devtools/server/actors/webconsole.js:846
    makeInfallible resource://devtools/shared/ThreadSafeDevToolsUtils.js:103
debugger eval code:5:1
    <anonymous> debugger eval code:5

Why is the contentDocument null?

I tried running the above code. According to the docs, “It adds a listener to the currently selected tab’s load event that will eat the new page, then loads a new page.” Instead it generates an Uncaught TypeError: newTabBrowser.contentDocument is null.

Is this right way to solve Two Crystal Balls problem?

I had lecture about this problem and as I understand, I have to find the lowest point from which this ball will break. I thought of using binary search to get O(logN) time complexity. If the ball breaks on the index and breaks again on the index – 1, we simply continue the search until we find an index where it breaks and the one to the left does not.

function two_crystals(data : boolean[]) : number {
  let first_index = 0;
  let last_index = data.length - 1;

  while(first_index <= last_index){
    let mid_index = Math.floor((last_index + first_index) / 2);

    if (data[mid_index]) {
      // Check if it doesn't break at the previous floor
      if (mid_index === 0 || !data[mid_index - 1]) {
        return mid_index;
      }
      // Continue searching in the lower half
      last_index = mid_index - 1;
    } else {
      // Continue searching in the upper half
      first_index = mid_index + 1;
    }
  
  }
  
  return -1
}

Maybe I didn’t understand the problem correctly, but I think this option is better

Rotate an HLS stream into Landscape Mode

I’ve got an HLS format (M3u8 file) video that I would like to show to users on a web site.

Some of the videos are taken in vertical (portrait) mode, others are in landscape (horizontal) mode.

Ideally I’d be able to do something on the web client side to rotate the videos and display them “right side up”

I’m actually interested in being able to do this mid stream, without making mobile viewers rotate their phones or desktop viewers not really having an option.

I could generate new HLS assets based on new rotated mp4 files that I create let’s say with FFMPEG, but I’d rather just have something on the display side on web.

Currently using just the default Mux player in React to do this, trying to apply a -90 CSS transform is also shifting the video player controls, which looks very strange.

Looking for a lightweight client side solution, although if none exists I can do a more heavy server side flow.

javascript: data submit from button randomly not working

I am setting up an e-commerce webshop, and would like to have the buttons either show “Add to cart” in red or “Added to cart” in green. I have a working shop without this feature, and a working single button that changes color and text (via SVG and a lot of CSS). When I combine the two, it sometimes works, and sometimes doesn’t, and I don’t find the reason for that.

HTML:

<div class="toolbar">
            <h1 class="brand">Shop</h1>
            <p>
                <a href="cart.php">
                    Cart items:
                    <span id="count">0</span>, Price:
                    <span id="sum">0</span>
                </a>
            </p>
        </div>
    <div class="products">
                <div class="product">
                    <h3>Product one</h3>
                    <p>Price: 2000</p>
       <button data-id="1" data-price="2000" data-title="Product one" class="add-to-cart-button">
            <svg class="add-to-cart-box box-1" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="24" height="24" rx="2" fill="#ffffff"/></svg>
            <svg class="add-to-cart-box box-2" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="24" height="24" rx="2" fill="#ffffff"/></svg>
            <svg class="cart-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
            <svg class="tick" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path fill="#ffffff" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM9.29 16.29L5.7 12.7c-.39-.39-.39-1.02 0-1.41.39-.39 1.02-.39 1.41 0L10 14.17l6.88-6.88c.39-.39 1.02-.39 1.41 0 .39.39.39 1.02 0 1.41l-7.59 7.59c-.38.39-1.02.39-1.41 0z"/></svg>
            <span class="add-to-cart">Add to cart</span>
            <span class="added-to-cart">Added to cart</span>
        </button>
                </div>
            </div>

There are several such “Product” entries (currently Product one … Product four).

Javascript:

let count = 0;
let sum = 0;
let cart = {};

if (localStorage.getItem("count")) {
    count = parseInt(localStorage.getItem("count"));
}

if (localStorage.getItem("sum")) {
    sum = parseInt(localStorage.getItem("sum"));
}

if (localStorage.getItem("cart")) {
    cart = JSON.parse(localStorage.getItem("cart"));
}

updateCart();

let btns = document.querySelectorAll(".products button");

for (let i = 0; i < btns.length; i++) {
    let btn = btns[i];
    btn.addEventListener("click", add);
}

function add(event) {
    let price = Number(event.target.dataset.price);
    let title = event.target.dataset.title;
    let id = event.target.dataset.id;

if (id in cart) {
    cart[id].qty++;
} else {
    let cartItem = {
        title: title,
        price: price,
        qty: 1
    };
    cart[id] = cartItem
}

    count++;
    sum += price;

    console.log(cart);

    localStorage.setItem("cart", JSON.stringify(cart));
    updateCart();
}

function updateCart() {
    document.getElementById("sum").textContent = sum;
    document.getElementById("count").textContent = count;
    localStorage.setItem("sum", sum);
    localStorage.setItem("count", count);
}

addToCartButton = document.querySelectorAll(".add-to-cart-button");

document.querySelectorAll('.add-to-cart-button').forEach(function(addToCartButton) {
    addToCartButton.addEventListener('click', function() {
        addToCartButton.classList.add('added');
    });
});

I currently have four entries, and when I click the corresponding buttons, some get stored in localStorage correctly (= price, title, qty), and with some, only the click is stored in localStorage (qty). When I delete localStorage and repeat the procedure, different items get stored. I couldn’t find any pattern in the behavior.

It seems that once an item is not stored correctly, clicking the corresponding button will only increase the number of qty entries that are “unassigned”.

How can I make this stable?

Download PDF is not working in Safari browser only

Download PDF JavaScript function is not working only in Safari browser. However it is working fine for other browsers like Chrome, Edge etc. We tried the below code from the aura component. It doesn’t seem to work.

    const linkSource = `data:application/pdf;base64,${base64}`;
    var downloadLink = document.createElement('a');
    var fileName = objId;
    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();

How can I read each file in a directory and directly run a function in node readdir?

my understanding of fs.readdir in node is that it reads all files in a directory asynchronously, but only makes them available as an array once they’re all fulfilled. Is it possible to run a function on each file as soon as that individual file is ready (i.e. not to wait for all of them)?

My current implementation is as follows:

fs.readdir(DIR, async (err, files) => {
      if(err) console.log(err)
      const promises = files.map(file => doSomething(file))
      try {
        await Promise.allSettled(promises);
      } catch (error) {
        console.error('Error processing array:', error);
      }  
})

which runs doSomething on each file asynchronously but that still waits for all files to be determined first

Postgres copy to STDOUT hangs indefinetly

I have a script that runs COPY on postgres to STDOUT. This stream is consumed by nodejs into a readable. This readable is passed to pipeline which writes to a csv file locally. I am using nodePG and nodePG-copy-stream to handle creating the postgres client and copy stream. Lastly, I execute my script with bun. I attached my example read/write code below.

const saveCopyStreamToFile = async (
  pgPool: pg.Pool,
  copyQuery: string,
  fileName: string
) => {
  console.log(fileName);
  const client = await pgPool.connect();
  const readable = client.query(copyTo(copyQuery));

  const writeable = createWriteStream(`${os.homedir()}/cms/${fileName}`, {
    highWaterMark: 64 * 1024
  });

  try {
    await pipeline(readable, writeable);
  } finally {
    client.release();
  }
};

The Issue: On a certain table, the copy stream hangs indefinetly. I attached event listeners and the read stream never sends a close event. It does recieve data events and chunks. When I inspect the file, I can see the data begins to break randomly when writing a row in the csv. For example, XYZ utilizes a configuH djid is a cell in the csv where the break begins. Interestingly, a different package postgresjs works fine on this table, but runs into the same issue on a different table. Lastly, I inspected the pg_stat_activity table and can see the process in there stuck in the idle state.

Expected: I can write the postgres copy stream to a csv file locally.

NodePg: https://node-postgres.com/
PostgresJs: https://github.com/porsager/postgres

Next JS not taking multiple props for FontAwesome icon

<FontAwesomeIcon icon={faTableCells, faSharp, faRegular} />
I am trying to add faSharp, faRegular to the source about.

But unfortunately my application is screaming. I need them because they are defaults of the exact table cells with no border-radius added.

I tried what is above and does not work