React mapStateToProps state calling reducers infinitely

const mapDispatchToProps = dispatch => ({
  getUsers: (payload) => dispatch({ type: "USERS", payload: payload })
});

const mapStateToProps= state => ({
  ctr: state.TestReducer,
  users: state.Users
})  

const Dashboard = (props) => { 
  axios.get("https://jsonplaceholder.typicode.com/users")
    .then(function(response) {
      props.getUsers(response.data);
    });

  return (
    <h1>hello dashboard</h1>
  )
}

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);

When I add the Users reducer in mapStateToProps, in browser console reducers from redux logger are executing infinitely as shown here enter image description here

I want to store the Users that I get from axios to the User reducer. And those users I want to access using state in mapStateToProps so that I can use as props users. But the problem is redux logger infinitely logs state in my web browser console as shown in the image.

How to stop this?

I tried many ways but did not find a proper solution.

Why can’t host my own copy of MathJax locally?

With cdn service to render latex in html.

   <!DOCTYPE html>
   <html>
   <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width">
   <script type="text/javascript" async
     src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML">
   </script>
   <script type="text/x-mathjax-config">
   MathJax.Hub.Config({
     tex2jax: {inlineMath: [['$','$'], ['\(','\)']]},
   });
   </script>
   </head>
   <body>
   First of all, we can "relax" the $forall$-Introduction rule : $A to B vdash A to forall x B$, provided that $x$ is not *free* in $A$.
   </body>
   </html>

All latex shows fine in html.
enter image description here

I want to deploy the mathjax service locally.

Download the MathJax.js directly ,MathJax.js can open with the link: 127.0.0.1/wp/MathJax.js,set the src as below:

<script type="text/javascript" async
     src="http://127.0.0.1/wp/MathJax.js?config=TeX-MML-AM_CHTML">
</script>

latex can’t be shown.
enter image description here

Maybe some useful files haven’t download,so i git all mathjax’s file as the mathjax official document(mathjax official document) denote,and copy all of them to apache’s document directory.

git clone https://github.com/mathjax/MathJax.git mathjax

tex-chtml can open in the url http://127.0.0.1/mathjax/es5/tex-chtml.js,write the html:

   <!DOCTYPE html>
   <html>
   <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width">
   <script type="text/javascript" async
     src="http://127.0.0.1/mathjax/es5/tex-chtml.js?config=TeX-MML-AM_CHTML">
   </script>
   <script type="text/x-mathjax-config">
   MathJax.Hub.Config({
     tex2jax: {inlineMath: [['$','$'], ['\(','\)']]},
   });
   </script>
   </head>
   <body>
   First of all, we can "relax" the $forall$-Introduction rule : $A to B vdash A to forall x B$, provided that $x$ is not *free* in $A$.
   </body>
   </html>

Restart my apache,no error info on firefox’s debug,but the line haven’t been rendered by mathjax.

enter image description here

How to fix it?

Best Practice for Exporting Default Functions in React with TypeScript?

I am currently studying React with TypeScript and have come across two different ways to export a default function component. Here are the two examples:

  1. Exporting the function separately:
function PriceListPage() {
    return (<></>);
}

export default PriceListPage;
  1. Exporting the function directly during declaration:
export default function PriceListPage() {
    return (<></>);
}

Both seem to work the same way, and I haven’t noticed any technical differences in behavior.

My questions are:

  • Are there any technical differences between these two approaches?
  • Are there any best practices, conventions, or recommendations from the React or TypeScript community that favor one style over the other?

I am the Full Stack Software Engineer of a new upcoming large single page frontend project and have decided to use React with TypeScript. As part of setting up code styling with best practices, I’d like to know if there are also any practical differences between these styles, and if one should be preferred for maintainability.

Any insights into which method is more commonly used or why one might be preferred would be greatly appreciated!

TypeScript type for functions that only accept an object type

Is there a way to define a TypeScript type where only functions taking a single object argument are assignable to it? For example:

type RestrictToObjectParam = any; // TODO

let fun: RestrictToObjectParam;
fun = (arg: object) => {};                 // OK
fun = (arg: {}) => {};                     // OK
fun = (arg: {str: string}) => {};          // OK
fun = (arg: {obj: {}, num: number}) => {}; // OK
fun = (arg: number) => {};                 // ERROR

Something like (arg: object) => any won’t work because the third example isn’t assignable to it. I’ve tried other things like:

  • <T extends object>(arg: T) => any to constrain the argument type
  • T extends object ? (arg: T) => void : never to distribute the argument type

but those seem to just boil down to (arg: object) => any.

Is this possible? I might be misunderstanding how function types in TypeScript work in general.

How to properly import custom css and js files in Vue.js project

I have a paid admin dashboard template which in an HTML form, so I’m in the process of converting it to Vue.

How can I import the css and js properly in Vue?
Like jQuery, bootstrap bundles, perfect-scrollbar etc?

Is the only solution is put them in public folder and attach each manually in the index.html because when I tried to import them, they are considered as module.

This is my attempt. It works on npm run dev but once built and deploy the dist to server, it now errors because the links are still pointing to src

App.vue:

<script setup>
    import { onMounted } from 'vue'
    import { loadExternalScripts } from './utils/scriptLoader';

    onMounted(() => {
        const scripts = [
            '/src/assets/js/plugins/jquery-3.3.1.min.js',
            '/src/assets/js/plugins/bootstrap.bundle.min.js',
            '/src/assets/js/plugins/perfect-scrollbar.min.js',
        ];

        loadExternalScripts(scripts)
            .then(() => {
                console.log('All external scripts loaded successfully');
                // Now you can safely use any jQuery or Bootstrap functions here
            })
            .catch((error) => {
                console.error('Error loading external scripts:', error);
            });
    });
</script>

<template>
    <router-view />
</template>

<style scoped></style>

scriptLoader.js

const loadedScripts = new Set();

export function loadExternalScripts(scripts) {
    return new Promise((resolve, reject) => {
        const loadScript = (index) => {
            if (index >= scripts.length) {
                resolve(); // Resolve when all scripts are loaded
                return;
            }

            const src = scripts[index];
            if (loadedScripts.has(src)) {
                loadScript(index + 1); // Skip already loaded scripts
                return;
            }

            const script = document.createElement('script');
            script.src = src;
            script.onload = () => {
                loadedScripts.add(src);
                loadScript(index + 1); // Load next script
            };
            script.onerror = () => reject(new Error(`Script load error: ${src}`));
            document.head.appendChild(script);
        };

        loadScript(0); // Start loading scripts from the first one
    });
}

API data not getting passed through to main function because it is asynchronous

I am making a website which displays the news data using reactjs.

This is my code:

import Header from './components/header';
import Footer from './components/footer';
import Chart from './components/chart';
import Headline from './components/headline';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';

const apiUrl = `https://api.thenewsapi.com/v1/news/top?api_token=${apiKey}&locale=us&limit=1`

function apiCall(){
  fetch(apiUrl, {
    method: 'GET'
  })
    .then(response => response.json())  // Parsing the JSON response
    .then(data => {
      var headlines = data.data[0].title;  // Handling the response data
      console.log(headlines)
    })
    .catch(error => {
      console.error('Error:', error);  // Handling errors
    });
}

function App() {

  var headlines = apiCall();;


  return (
    <div className="App">
      <Header></Header>
      <Container>
        <Row>
          <Col><Chart></Chart></Col>
          <Col><Headline headline = {headlines}></Headline></Col>
        </Row>
    </Container>
      <Footer></Footer>
    </div>
  );
}

export default App;

I am successfully able to retrieve the data from the api by checking using a console.log, however I can’t get the data into my App function, as the api is asynchronous. I have tried adding the async tag behind the api function but I am met with an error:

“Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.”

I am not passing an object, just a var (such as “new asteroid discovered next to earth!”).

Any answers are appreciated.

How can get First character of string of any html tag and bind to other tag in php or js?

How can I achieve the below scenario with php?

Case 1

Input : <h2>Test text <img src="./test.png" /></h2>
Output : <span>T</span><h2>est text <img src="./test.png" /></h2>

Case 2

Input : <p>Test text</h2>
Output : <span>T</span><p>est text</p>

Case 3

Input - <h2><img src="./test.png" /> Test text </h2>
Output - <span>T</span><h2><img src="./test.png" /> est text</h2>

In the input html may be there are so many tags will included. I want any of first block holding the html

I have tried below code

<?php
$firstLetter = strip_tags(get_sub_field('text'));
$firstLetter = $firstLetter[0];
?>
<div class="capLetter"><?php echo $firstLetter; ?></div>
<?php echo substr(get_sub_field('text'), 4); ?>

Attempting to display a sorted array of objects to HTML with Javascript

I am working on a glass assignment where I need to make write a Loop. I made an array of objects for houses. I created a For Loop to sort the array by the price of the houses. The array displays in the console of the webpage but not in the actual webpage. Below are the extracts of what the console shows, what the webpage shows, and my code.

console log

  1. (4) [{…}, {…}, {…}, {…}]

    1. 0: {id: ‘house4’, stories: 1, squareFoot: 1130, color: ‘white’, year: 1961, …}

    2. 1: {id: ‘house1’, stories: 1, squareFoot: 1285, color: ‘beige’, year: 2018, …}

    3. 2: {id: ‘house2’, stories: 1, squareFoot: 1560, color: ‘brown’, year: 1983, …}

    4. 3: {id: ‘house3’, stories: 2, squareFoot: 2975, color: ‘tan’, year: 2008, …}

    5. length: 4

    6. [[Prototype]]: Array(0)

webpage

[object Object],[object Object],[object Object],[object Object]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <p id ="houses"></p>

  <script>

  let houses = [{id:"house1", stories:1, squareFoot:1285, color:"beige", year:2018, bedrooms:3, bathrooms:2, price:285000},
                {id:"house2", stories:1, squareFoot:1560, color:"brown", year:1983, bedrooms:3, bathrooms:3, price:345000}, 
                {id:"house3", stories:2, squareFoot:2975, color:"tan", year:2008, bedrooms:4, bathrooms:3, price:415000}, 
                {id:"house4", stories:1, squareFoot:1130, color:"white", year:1961, bedrooms:2, bathrooms:2, price:215000}];

  for (i=0; i<1; i++) {
    houses.sort((a, b) => a.price - b.price);
    document.getElementById("houses").innerHTML=houses;
    }
  //console.log(houses);

  </script>

</body>
</html>

I have watched several videos about sorting arrays, but they all only display to the console log. I tried to modify my code to be similar to the example used in my lecture video as well, but still no output. Any help would be appreciated. Thank you.

A proper way to persist selected item in Nuxt using cookies

I want to persist a selected item after page reload. I need to click on the item from the fetched data list and open the item details on /item-details route. To be able to persist the data after page reload in SSR I assume I need to use cookie. Therefore, in Nuxt I can use useCookie for that:

const selectItem = (id: number) => {
    useCookie('selectedItem').value = (id - 1).toString();
};

The array indexing starts from 0 in Js and from 1 in Postgres db that I use. I’m not sure if I should I store the ID starting from 0 in the database, so that there’s no need to subtract 1 as in the example or keep it as it is.

Then, in the template I click on the item and call the function, passing the item ID I get from v-for="item in items?.data":

@click="selectItem(item.id)"

After that, in item details /pages/item-details/[id].vue I need to use this selected item to display item characteristics:

// template
<span>{{item?.color}}</span

// script
const { items } = useStoreItem();

const id = useCookie('selectedItem');
const itemId = Number(id.value);
const item = items.value ? items.value[itemId] : null;

It feel like the whole process is cumbersome and not quite straightforward: I need to convert something to string and then to number etc. I’m not sure if I’m doing everything right and if it’s how it should work or is it all wrong and there’s a more proper solution in Nuxt.

I’m looking for a possible solution.

Is it possible to slot the style of a shadowRoot?

I’m experimenting with Vanilla custom elements and it doesn’t seem possible to slot a style tag:

class MyElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: "open"});
  }
  connectedCallback() {
    this.shadowRoot.append(document.getElementById('my-element-template').content.cloneNode(true));
  }
}
window.customElements.define("my-element", MyElement);
<template id="my-element-template">
  <slot name="my-style">
    <style>
      p { color: red; }
    </style>
  </slot>
  <p>Why am I still red instead of green?</p>
</template>

<my-element>
  <style slot="my-style">
    p { color: green; }
  </style>
</my-element>

How do I handle 429 errors from eleventy-fetch?

I’m making a request with eleventy-fetch like this:

let response = await EleventyFetch(url, {
    duration: "1h",
    type: "json"
  });

However, sometimes it fails with an error:

Bad response for [url] (429): Too Many Requests (via Error)

I know that I’m requesting too often, so I want to build exponential backoff. However, my initial attempt didn’t work:

let response;
let attempts = 0;
const maxAttempts = 5;

while (attempts < maxAttempts) {
  try {
    response = await EleventyFetch(url, {
      duration: "1h",
      type: "json"
    });
    break; // If request is successful, exit the loop
  } catch (err) {
    if (err.response && err.response.status === 429) {
      attempts++;
      const waitTime = Math.pow(2, attempts) * 1000; // Exponential backoff
      console.warn(`Rate limit exceeded. Retrying in ${waitTime / 1000} seconds...`);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    } else {
      throw err; // If it's not a 429 error, rethrow the error
    }
  }
}

The error is still being thrown and the exponential backoff never happens. What have I done wrong?

blur image and show text on hover?

I have this grid with 3 columns, and when i click one of the divs it’ll go down a row and span the whole row, it also closes back up when i click on it again. Also, when I open a different div, it’ll close all the other ones if theyre open. so that there’s only one open at a time

how do I make it so that when I hover on it, it’ll blur the div and show “Click for more info” in the middle? i was thinking of adding a div with the text on each one but that seems too repetitive.. is there an easier way to do it?

document.querySelectorAll('#gridALBUM > div').forEach((D,_,A)=>
  {
  D.addEventListener('click', e=>
    {
    if (D.classList.toggle('span'))
      A.forEach(d =>{ if(d!=D) d.classList.remove('span') });
    })
  })
#gridALBUM {
  margin: 50px auto;
  max-width: 908px;
  display: grid;
  grid-gap: 0 4px;
  grid-template-columns: repeat(3, 300px);
  grid-auto-flow: dense;
  background-color: lightblue;
}

#gridALBUM > div {
  border  : 1px solid black;
  display : flex;
}

#gridALBUM > div:not(.span) > div {
  display : none; 
 }

#gridALBUM > div.span {
  grid-column      : 1 / 4;
  background-color : #47479c;
}
<div id="gridALBUM">
  <div id="one"   ><h1>1</h1> <div><h2> one   </h2></div></div>
  <div id="two"   ><h1>2</h1> <div><h2> two   </h2></div></div> 
  <div id="three" ><h1>3</h1> <div><h2> three </h2></div></div>
  <div id="four"  ><h1>4</h1> <div><h2> four  </h2></div></div>
  <div id="five"  ><h1>5</h1> <div><h2> five  </h2></div></div>
  <div id="six"   ><h1>6</h1> <div><h2> six   </h2></div></div>
  <div id="seven" ><h1>7</h1> <div><h2> seven </h2></div></div>
  <div id="eight" ><h1>8</h1> <div><h2> eight </h2></div></div>
  <div id="nine"  ><h1>9</h1> <div><h2> nine  </h2></div></div>
  <div id="ten"   ><h1>10</h1><div><h2> ten   </h2></div></div>
</div>

Android App without Android Studio or React Native?

I’m new to Android Application Development, so please correct me if I’m saying something dumb.
I’ve been trying to develop an Android App since a month now, but I haven’t made any progress.
In the first two week, I tried React Native with Expo, but I cancelled that out because:

  • I tried to bundle my App into an apk. After debugging and searching for OS and Software error fixes, I managed to squeeze out an .apk, but it failed to run correctly on my Android Device. JS simply seems to complicated to me, because of it’s oversimplifications. I’m a C++ developer, so I’m used to have complete control over my programs, especially the memory. I miss that in JS.
    After React Native with Expo, I tried Android Studio. Had to abandon that too, because:
  • Android Studio simply doesn’t like AMD CPUs. I tried to do all Hyper-V and other stuff, but none of that did work, as the Emulator simply didn’t even show up.
  • Trying to connect to my physical device:
    • Scanning the QR code, I got an error on my Desktop saying that it wasn’t able to connect.
    • Pairing trough PIN, my Computer wasn’t even able to find my Phone, even tough they were connected to the same network, without any proxy or VPN.

In summary, I’m looking for something which works out-of-the-box with options for Firebase and Networking.

Here are my Hardware Specs:

  • OS: Windows 10 Pro, fully updated
  • RAM: 48GB DDR4
  • CPU: AMD Ryzen 5 5600 with Raden Graphics
  • GPU: RTX4060 8GB
  • ROM: 1TB nvme, 500GB free.

get_theme_file_uri does not work for scripts…

Im trying to turn a web template into a static WordPress theme and get_theme_file_uri resolves in the url/the files instead of wp-content/themes/thetheme/js/plugins/swiper.min.js

so instead of looking for the file here:
http://learning-test.local/wp-content/themes/TERAFORMED/js/plugins/swiper.min.js

it looks for the file here:
http://learning-test.local/js/plugins/swiper.min.js

However when i log it in the debug file i see it resolves to http://learning-test.local/wp-content/themes/TERAFORMED/js/plugins/swiper.min.js

it also doesn’t work on a hosting…

I am speechless this looks impossible to be happening according to chatgpt and claude(im new to wordpress development)

The url on which this is happening: zanixa.merchsolution.net

I tried everything I know, i double checked the urls I added debuging and im looking at the debug file and i can’t believe what im seeing, the error log logs the right url but the url is wrong in the browser…

PS: My only theory is that it should be something in the js file but i don’t see anything wrong there

here is my theme:
https://github.com/apexdigitalreaper/apex-digital-theme/tree/main/teraformed