React useffect infinite render or stale state

I am getting some posts from the server and every time i delete or add a post, i need to refresh the page for it to showcase the changes. This can be solved by adding posts in the dependency array but then an infinite render occurs.

useEffect(() => {
    const getUsersData = async () => {
      const results = await getUsers();
      setUsers(results.data);
      console.log(results.data);
    };

    const getPostData = async () => {
      const results = await getPosts();
      console.log(results.data);
      setPosts(
        results.data.sort((p1, p2) => {
          return new Date(p2.created_at) - new Date(p1.created_at);
        })
      );
    };

    getUsersData();
    getPostData();
  }, [posts]);

{post.user_id === user.result.user_id && (
              <DeleteIcon
                color="secondary"
                onClick={() =>
                  handleDelete(post.post_id, { user_id: user.result.user_id })
                }
              />
            )}

__

export const deletePost = async (postId, userId) => {
  await axios.delete(`${URL}/posts/${postId}`, { data: userId });
};

Get all elements between element type (h1’s) and wrap in div

I have the below structure:

<div class="wrapper">
    <h1>Header 1</h1>
    <h2>subtitle 1</h2>
    <p>aaa</p>
    <p>bbb</p>
    <p>ccc</p>
    <h2>subtitle2</h2>
    <p>ddd</p>

    <h1>Header 2</h1>
    <h2>subtitle 3</h2>
    <p>eee</p>
    <p>fff</p>

</div>

I want to select all the h1 and p elements between each h1 and wrap in a div, so I end up with:

<div class="wrapper">
    <div>
        <h1>Header 1</h1>
        <h2>subtitle 1</h2>
        <p>aaa</p>
        <p>bbb</p>
        <p>ccc</p>
        <h2>subtitle2</h2>
        <p>ddd</p>
    </div>

    <div>
        <h1>Header 2</h1>
        <h2>subtitle 3</h2>
        <p>eee</p>
        <p>fff</p>
    </div>
</div>

I’ve tried various things like the below, but none work perfectly:

$( "h1" ).prevUntil( "h1" ).wrapAll( "<div></div>" );

Proxy Object, assign dynamically

Using the Proxy Object to observe changes in an Object.

To propagate all changes to the observed object obj, the following method does the job.

However, it requires a double assignment, each time a value is changed.

Can it be avoided? Context with more details

/* Simplest Observer function */
const observe = (o, f) => new Proxy(o, { set: (a, b, c) => f(a, b, c) })

const obj = {
  foo: 0,
  bar: 1
};

const $obj = observe(obj, (target, prop, changes) => {
  /* Setting an assigment here on the observed object, like:
  * target.prop = changes
  * leads to a cyclical error */
  console.log("Change detected!", prop, changes)
})

/* Test: obj.foo had been altered with a new value, as expected */
$obj.foo = obj.foo = -10 // Hot start

/* No cyclical errors, it is the expected behavior,
* but, require a double assigment each time. */
setInterval(() => $obj.foo = obj.foo = obj.foo + 1, 3000)

NextJS module resolution error with multiple paths in my path resolution

Hi everyone šŸ™‚ I was hoping I could get some fresh eyes on a problem I’m running into on my project:

I have a NextJS (12.1.4) project using absolute imports, I also have an NPM package where I directly import the source files in my project (since it’s a library for shared components, internal use only). This package is called bs-components here.

Here is my jsconfig.json file

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@bscom/*": ["node_modules/@company/bs-components/*"],
      "*": ["node_modules/@company/bs-components/*", "*"]
    }
  }
}

I will explain the intent behind my paths config here:

The first entry for @bscom/* will allow me to import modules from my library using a shorthand.

The second entry for * is intended so that the module resolution goes like this:

  • Look in the component library first for a module, so that absolute imports in the component library are respected.
  • If module is not found in the library, then resolve using the baseUrl as the starting point for resolution.

Unfortunately when using this config, absolute imports within the component library fail with the following error:

./node_modules/@company/bs-components/styling/resets.js:1:0
Module not found: Can't resolve 'constants/colors'

This happens in my NextJS _document.js file, so during the server render step.

There are no modules with that path in my main project which could cause a conflict.

Any suggestions would be greatly appreciated, thanks šŸ™‚

How to achieve a problem with context api

I have an API with a page limit of 10, so every time I pass a page number it returns me a list of 10. In my react project, I have the functionality to select the items from the list so if I select 2 items from page 1 and I want to select 10 items from page 2, How to hold page 1 items in context API and show those values when responses are changed when the page number is changed.

React Hooks – distribution of responsibilities (GRASP)

Introduction

I am implementing the analytics of my react app.

This is the structure of my project:

/
  components/
    Profile/
      EditProfileForm.js

  screens/
    Profile/
      EditProfile.js

  services/
    api/
      profile/
        editProfile.js

  hooks/
    profile/
      useEditProfile.js

The folder ‘services/api’ contains the code that interfaces with the server, that is, the code that calls my endpoints, parses the responses of my microservices… I mean, the interface/gateway.

I have created UI and Business Logic Hooks… this is an extra layer for cleaning the code of my components, or for executing certain business logic like if the user isn't premium, don't let him edit his profile.

Problem

Now, I am about to track the events of my app… I need to place a code, somewhere, for tracking the profile editions (and the respective errors).

I have decided to create helper methods inside my hooks… but maybe, they should be placed in the api methods…

What do you think? Following the low coupling, high cohesion, and controller patterns of GRASP, where should I place this code?

import analytics from  "../../services/api/analytics";

const trackProfileEditionError = (err) => {
   analytics.eventsLogger.EXCEPTION({
     description: err.message ?? "Error editing profile"
     fatal: false,
   });
}

My current solution

I see some of my business logic hooks as controllers (intermediaries between my interface and the algorithm that implements it).

In order to decouple the tracking part from the call to my edit-profile endpoint, I have decided to place the code as a helper of my custom hook. Like this:

/
  components/
    Profile/
      EditProfileForm.jsx

  screens/
    Profile/
      EditProfile.jsx

  services/
    api/
      profile/
        editProfile.js

  hooks/
    profile/
      helpers/
        analytics/
          trackProfileEditionError.js

      useEditProfile.jsx

Note: I know what a custom hook is… in the code of my custom hooks I have native hooks (useRef, useEffect, useCallback…), so they are not helper/utility functions.

Prisma get data with foreign key in sqlite DB

I have an SqlLite database that contains these models

model Product {
  id                    Int      @id @unique(map: "sqlite_autoindex_products_1") @default(autoincrement())
  label                 String
  description           String?
  price                 Int
  category_id           Int
  thumbnail_url         String?
  categories            Category @relation("categoriesToproducts", fields: [category_id], references: [id], onDelete: NoAction, onUpdate: NoAction)

  @@map("products")
}

model Category {
  id          Int       @id @unique(map: "sqlite_autoindex_categories_1") @default(autoincrement())
  index       Int?
  label       String
  description String?
  products    Product[] @relation("categoriesToproducts")

  @@map("categories")
}

I would like to get products list using :

async allProducts(): Promise<Product[] | null> {
  return this.prisma.product.findMany();
}

It returns Products raw data with category_Id field.

I would like to know if there is a way to get category mapped data inside Category table instead of only the id field ?

I have a solution is to get Category table data than loop on products list then replace category_id with the category object.

But I would like to know if there is a better way to map directly data when making request via Prisma client.

EJS is downloading page instead of displaying it

I’m trying to create a stripe payment which should redirect you to an ejs to make the payment on button click. But when I hit the button on my route, it downloads instead of displaying it. I tried to change the path in the html and also installed ejs via npm for webpack and created a “new HtmlWebpackPlugin” but nothing works, also I tried to change some code in my /views/main.js where stripe and express its placed. I created that main.js for a test before and it worked just fine, but my implementation atm sucks (newbie what can u ask). Thx for reading this.

  • HTML a href:

      <div class="section--hero__header__cart-content_buttons">
        <a href="#" id="clear-cart" class="btn">clear cart</a>
        <a href="http://localhost:3000/Home.ejs" class="btn btn-checkout"
          >checkout</a
        >
      </div>
    
  • Home.ejs(data-key: publishable key):

     <html>
        <title>Stripe Payment Demo</title>
        <body>
          <h3>Welcome to Payment Gateway</h3>
          <form action="payment" method="POST">
            <script
              src="//checkout.stripe.com/v2/checkout.js"
              class="stripe-button"
              data-key="pk_test_51Kkw9VCyczacwlgvlR72gi5YXdeVyz4i9E0b5PVfHDgxpQqPj1ITPCvhqU55aHuYFhyI1cZcWpxAm6hdy4Wzh09u001EwJqkZ1"
              data-amount="7000"
              data-currency="usd"
              data-name="Tenclop"
              data-description="Buy Backpacks"
              data-locale="auto"
            ></script>
          </form>
          <form>
            <input type="button" value="Back" onclick="history.back()" />
          </form>
        </body>
     </html>
    
  • main.js:

    const express = require("express");
      const bodyParser = require("body-parser");
      const path = require("path");
      const app = express();
    
      app.use(bodyParser.urlencoded({ extended: false }));
      app.use(bodyParser.json());
    
      const PUBLISHABLE_KEY =
        "pk_test_51Kkw9VCyczacwlgvlR72gi5YXdeVyz4i9E0b5PVfHDgxpQqPj1ITPCvhqU55aHuYFhyI1cZcWpxAm6hdy4Wzh09u001EwJqkZ1";
    
      const stripe = require("stripe")(SECRET_KEY);
    
      app.set("views", path.join(__dirname, ""));
      app.set("view engine", "ejs");
    
      const PORT = process.env.PORT || 3000;
    
      app.get("/", (req, res) => {
        // res.header("Content-Type", "text/html");
        // res.attachment();
        res.render("Home", {
          key: PUBLISHABLE_KEY,
        });
      });
    
      app.post("/payment", (req, res) => {
        stripe.customers
          .create({
            email: req.body.stripeEmail,
            source: req.body.stripeToken,
            name: "Tenclop",
            address: {
              line1: "TC 9/4 Old MES colony",
              postal_code: "0018",
              city: "Oslo",
              country: "Norway",
            },
          })
          .then((customer) => {
            return stripe.charges.create({
              amount: 7000, // Charing Rs 25
              description: "Backpacks",
              currency: "USD",
              customer: customer.id,
            });
          })
          .then((charge) => {
            res.send("Success"); // If no error occurs
          })
          .catch((err) => {
            res.send(err); // If some error occurs
          });
      });
    
      app.listen(PORT, () => {
        console.log(`App is listening on ${PORT}`);
      });
    
  • webpack, thats all i added about ejs:

 plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: "./src/index.html",
    }),

    new HtmlWebpackPlugin({
      filename: "shop.html",
      template: "./src/shop.html",
    }),

    new HtmlWebpackPlugin({
      filename: "/Home.ejs",
      template: "./src/views/Home.ejs",
    }),
  ],

Uncaught TypeError: Cannot set properties of undefined (setting ‘display’)

I’m making a progress bar for my music react-app. I want to make the progress-indicator to show up whenever the user hover on the progress-bar-container. But I face with this error: Uncaught TypeError: Cannot set properties of undefined (setting ‘display’)

My Javascript:

document.getElementsByClassName('rhap_progress-container')[0].onmouseover = function(){
  document.getElementsByClassName('rhap_progress-indicator').style.display = "block";
}
document.getElementsByClassName('rhap_progress-container')[0].onmouseout = function(){
  document.getElementsByClassName('rhap_progress-indicator').style.display = "none";
}

My html:

<div class="rhap_progress-container" aria-label="Audio progress control" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="24.67" tabindex="0">
  <div class="rhap_progress-bar ">
    <div class="rhap_progress-indicator" style="left: 24.67%;"></div>
    <div class="rhap_progress-filled" style="width: 24.67%;"></div>
  </div>
</div>

My css:

.rhap_progress-indicator {
  display: none;
  width: 18px !important;
  height: 18px !important;
  border: 3px solid #232530;
  top: -7 px !important;
  box-shadow: none !important;
  opacity: 1 !important;
  content: url('./img/outlined-progress-indicator.png');
}

what is the fastest way to reset chess board for chess engine?

I am programming chess engine with minimax, I use 120part array representation for board. for every posibile move I have to create copy of this array which is really slow without using bitboard can I fasten this boardcopy part because generally I need to copy same Array over and over again for better representation in code this looks like this.

pisces.forEach(pisce=>{
    pisce.forEach(move=>{
          let copy=[...board]
          //other stuff
          board=copy
    })
})

if there is not any different method than which is fastest way to create copy of the array? and last I was thinking that I could create string and somehow than split it would that be faster?(I have no idea if I could menage doing it with string)

ApexCharts Performance Problems

first – I am relatively new to programming. Sorry for that. Now to my problem.

We have an area chart from Apex with about 11.000 data points per axis. Now the problem is that the chart just takes a long time to load. Even if you change the range, the chart takes a long time to unfold again.

What I have already tried:
Animations disabled
Area chart -> Line chart
Parkers to 0
Labels off

I have found another site where the charts run absolutely smoothly. Does anyone here have experience or can tell me how to get the charts to run more smoothly? Or is that simply not possible?

Many greetings

Like / Dislike System with MongoDb

I’m working on a like/dislike system on an API that works with mongoDB and nodejs and the user is supposed to be able to perform these actions:

  • Like the sauce once ( like = 1) and add the user id in a “usersLiked” array
  • Cancel his like ( like = 0) and remove the user id from the “usersLiked” array
  • Dislike the sauce once (like = -1) and add the user id in an array “usersDisliked”
  • Cancel his dislike (like = 0) and supposedly removed the user id from the “usersDisliked” array

The logic of the system like / dislike

I managed to make the user like the sauce, cancel his like and dislike the sauce.

But I am completely blocked on the dislike cancellation because when I try to use again the updateOne method in the condition where we have to cancel the like / dislike I have this error:

Cannot set headers after they are sent to the client

How could Improve the code ?

I’m learning little by little to use the backend commands and here I’m facing a wall.

Uncaught TypeError: Cannot read properties of undefined (reading ‘seriesTypes’)

What’s the problem in my code?

pay attention to the word function

enter image description here

enter image description here

enter image description here

    <script type="text/javascript">
  (function(m,e,t,r,i,k,a){m[i]=m[i]function(){(m[i].a=m[i].a[]).push(arguments)};
  m[i].l=1*new Date();k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
  (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

  ym(87351386, "init", {
       clickmap:true,
       trackLinks:true,
       accurateTrackBounce:true
  });
</script>

User image to Discord Embed

I want the image that a user sends to be fetched and put into an embed that the bot will then send. As the image must be a url and the person sends an image, I don’t know how I can transform this image into a url.
When doing the command, the embed send but without the image. This is what i’ve tried but it didn’t work :

const plotEmbed = new Discord.MessageEmbed() 
                        .setTitle(`Purchase of the plot n°${plotId}`)
                        .setColor("GREEN")
                        .setDescription(`Purchase of plot ${plotId} for ${days} days.`)
                        .setImage(message.attachments.first.url)
                        .setTimestamp()
message.channel.send({ embeds: [pEmbed]})

If someone could get me an advice on what I should try because I don’t really know…
Thanks for reading.