Responsive Arrow Text in Recharts Donut Chart react js

`I’m working on a React project where I’m using Re-charts to create a donuts chart. I have a custom label that I want to display as an arrow pointing to a specific section of the chart. The label(text and its above the arrow) should be responsive and adjust its size based on the chart’s dimensions. Here’s a simplified version of my code:


import React, { useCallback, useState } from 'react';

import {
  ResponsiveContainer,
  PieChart,
  Pie,
  Tooltip,
  Cell,
  Legend,
  Sector,
} from 'recharts';

const data = [
  { name: 'Group A', value: 400 },
  { name: 'Group B', value: 300 },
  { name: 'Group C', value: 300 },
  { name: 'Group D', value: 200 },
];
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];
const myStyles = {
  fontFamily: 'sans-serif',
  textAlign: 'center',
};

const mystyle = {
  gridContainer: {
    width: '100vw',
    height: '100vh',
  }
};


const renderActiveShape = (props: any) => {
  const RADIAN = Math.PI / 180;
  const {
    cx,
    cy,
    midAngle,
    innerRadius,
    outerRadius,
    startAngle,
    endAngle,
    fill,
    payload,
    percent,
    value
  } = props;
  const sin = Math.sin(-RADIAN * midAngle);
  const cos = Math.cos(-RADIAN * midAngle);
  const sx = cx + (outerRadius + 5) * cos;
  const sy = cy + (outerRadius + 5) * sin;
  const mx = cx + (outerRadius + 10) * cos;
  const my = cy + (outerRadius + 18) * sin;
  const ex = mx + (cos >= 0 ? 1 : -1) * 20;
  const ey = my;
  const textAnchor = cos >= 0 ? "start" : "end";
  const myCustomText = "abc"



  return (
    <g>
      <text className="heavy" x={cx} y={cy} dy={8} textAnchor="middle" fill={fill}>
        {myCustomText}
      </text>
      <Sector
        cx={cx}
        cy={cy}
        innerRadius={innerRadius}
        outerRadius={outerRadius}
        startAngle={startAngle}
        endAngle={endAngle}
        fill={fill}
      />

      <path
        d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`}
        stroke={fill}
        fill="none"

      />
      <circle cx={ex} cy={ey} r={2} fill={fill} stroke="none" />
      <text className="recharts-text recharts-label"
        x={ex + (cos >= 0 ? 1 : -1) * 12}
        y={ey}

        textAnchor={textAnchor}
        fill="#999"
        dominantBaseline="central"
      //  fontSize={fontSize}

      >
        <tspan alignmentBaseline="middle">Del 400</tspan>


      </text>
      {/* <text
          //style={{ fontWeight: "bold" }}
          x={ex + (cos >= 0 ? 1 : -1) * 12}
          y={ey}
          textAnchor={textAnchor}
          fill="#333"
        >{`PV ${value}`}</text> */}

    </g>
  );
};
const OrderAcceptedChart = () => {
  const [activeIndex, setActiveIndex] = useState(0);
  const onPieEnter = useCallback(
    (_: any, index: any) => {
      setActiveIndex(index);
    },
    [setActiveIndex]
  )

  return (
    <div className="chart rating">
      <div className="cardInner">
        <ResponsiveContainer width="100%" height={400}>
          <PieChart style={myStyles}>
            <Pie
              activeIndex={activeIndex}
              activeShape={renderActiveShape}
              inactiveShape={renderActiveShape}
              data={data}
              dataKey="value"
              nameKey="name"
              cx="50%"
              cy="50%"
              innerRadius={60}
              outerRadius={80}
              fill="#8884d8"
              paddingAngle={5}
              labelLine={false}
            // label
            // cornerRadius={40}
            >
              {data.map((entry, index) => (
                <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
              ))}
            </Pie>
            <Tooltip />
            <Legend />
          </PieChart>
        </ResponsiveContainer>
      </div>

    </div>
  );
};

export default OrderAcceptedChart;

Share image:
[1]: https://i.stack.imgur.com/7FIzq.png

React [17.0.2] State Batching

I understand that react 17 does not have state batching in async functions like an axios API call.

I have a ChildComponent that i am currently importing directly in my App.js

import React, { useEffect, useState } from "react";
import axios from "axios";
export default () => {
  const [state1, setState1] = useState();
  const [state2, setState2] = useState();
  const [state3, setState3] = useState();
  const [state4, setState4] = useState();

  console.count("Chile rendered");

  useEffect(() => {
    axios
      .get(
        "https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=1"
      )
      .then(function (response) {
        // handle success
        console.log(response);
        setState1("asdf");
        setState2("asdf");
        setState3("asdf");
        setState4("asdf");

        setState1("asdf");
        setState2("asdf");
        setState3("asdf");
        setState4("asdf");
      });
  }, []);
  
  return (
    <div>
      <h1>This is Child Component</h1>
    </div>
  );
};

THE MAIN ISSUE
This is the Screenshot of the console.
Console SS

WHY IS THERE AN EXTRA CONSOLE LOG, THE ONE THAT IS NUMBERED 6

and when i remove the extra four duplicate set of setStates that console/render does not show up, also even if i repeat just one setState there is an extra render.
React seems to be not caring for if i have repeated/duplicated one setState or all four.

How to Improve Coding Problem Retention as a Beginner in Python

Is it common for beginners to encounter situations where they solve a problem one day but then forget how they solved it the next day?
I find myself in a situation where, at times, I’m able to solve a coding problem entirely on my own, but the very next day, I struggle to recall how I achieved that solution. Is there a method or approach I can use to overcome this issue and retain my problem-solving skills consistently?

How do i over come that or is there something am doing wrong ?

How do I write a selector (querySelectorAll) for nested rules (CSS)?

Suppose I have the following CSS:

#potionButtonContainer > .potionCellDiv .potionButton, #potionButtonContainer > .potionCellDiv .potionButtonDisabled, #potionButtonContainer > .potionCellDiv .potionButtonActive { background-color: rebeccapurple }

This can be written shorter to avoid repetition:

#potionButtonContainer > .potionCellDiv { & .potionButton, & .potionButtonDisabled, & .potionButtonActive { background-color: rebeccapurple } }

or

#potionButtonContainer > .potionCellDiv { .potionButton, .potionButtonDisabled, .potionButtonActive { background-color: rebeccapurple } }

How can I use/write such a shortened selector with querySelectorAll? Perhaps that is not possible at all?

When I write

document.styleSheets[0].insertRule("#potionButtonContainer > .potionCellDiv { .potionButton, .potionButtonDisabled, .potionButtonActive { background-color: rebeccapurple } }")

and then query that rule via


document.styleSheets[0].cssRules[0].selectorText

it gives me '#potionButtonContainer > .potionCellDiv'. This rule has a nested rule

document.styleSheets[0].cssRules[0].cssRules[0]

with selectorText being '.potionButton, .potionButtonDisabled, .potionButtonActive'.

So maybe I have to either use a selector with repetition or nest those querySelectorAll?

By now I stick with

#potionButtonContainer > .potionCellDiv .potionButton, #potionButtonContainer > .potionCellDiv .potionButtonDisabled, #potionButtonContainer > .potionCellDiv .potionButtonActive

in javascript.

Axios API call returned 200 but Redux Toolkit state stopped at pending

I have a react frontend with strapi backend using axios for api call and redux toolkit for state management. I have several api calls to the backend, it worked fine for the others. However for this one, it returned 200 code as in the strapi logs, but had a wrong state in the redux createasyncthunk, resulting in no action.payload returning to the frontend.

Here is the api call. The “api” is imported from another file creating an axios instance using axios.create and the necessary configs. When I console.log in the .then() of the api call, it logged the data successfully.

getCategoryYears = (categoryID, categoryName, sortOrder) => {
        const params = {
            filters: {
                id: { $eq: categoryID },
                name: { $eq: categoryName },
            },
            'fields[0]': 'id',
            'fields[1]': 'name',
            populate: {
                years: {
                    fields: ['id', 'year'],
                    sort: [`year:${sortOrder}`],
                },
            },
        };

        return api.get(`/api/categories`, { params });
    };

Here is the redux createasyncthunk. The problem is this createasyncthunk didn’t proceed to fulfilled state. I have redux devtools installed in my chrome. It only showed up to pending state.

export const getCategoryYears = createAsyncThunk(
    'category/getCategoryYears',
    async ({ categoryID, categoryName, sortOrder }, thunkAPI) => {
        try {
            const res = await CategoryAPI.getCategoryYears(categoryID, categoryName, sortOrder);
            return res.data;
        } catch (e) {
            if (e.response) {
                const res = await e.response.data;
                e.code = res.code;
                return thunkAPI.rejectWithValue(serializeError(e));
            }
            throw e;
        }
    }
);

Here is the redux slice.

        builder.addCase(getCategoryYears.pending, (state, action) => {
            state.catYearLoading = true;
        })

        builder.addCase(getCategoryYears.fulfilled, (state, action) => {
            state.catYearLoading = false;
            state.years = action.payload.data.attributes.years.data;
        })

        builder.addCase(getCategoryYears.rejected, (state, action) => {
            state.catYearLoading = false;
            state.specialError = {
                message: action.payload.message,
                status: action.payload.status,
            };
        })

Here is where I called it in frontend. Cause the redux state is not fulfilled, the console.log here shows nothing.

    useEffect(() => {
        if (!categoryID || !categoryName) {
            navigate(`/photo-gallery-category`)
        } else {
            dispatch(getCategoryYears({ categoryID,categoryName,sortOrder}))
                .then(unwrapResult)
                .then((res) => {
                    console.log(res)
                })
                .catch((e) => {
                    // console.log(e)
                    if (e.status == '404') {
                        navigate(`/photo-gallery-category`)
                    }
                })
        }
    }, [categoryID, categoryName, sortOrder])

the backend logs indicating 200 also, and when I tested the exact url in postman, it worked fine.

[2023-09-17 19:18:57.987] http: GET /api/categories?filters[id][$eq]=31&filters[name][$eq]=Events+and+Appearances&fields[0]=id&fields[1]=name&populate[years][fields][0]=id&populate[years][fields][1]=year&populate[years][sort][0]=year:desc (105 ms) 200

At first, I was wondering if it had to do with the serialization of axios params nested objects, tried some suggestions but didn’t work. As the backend logs showed the correct url and returned 200, I am now confused and don’t know where has gone wrong. Does anyone know why the state behaved liked this? Many thanks.

Laravel livewire render not working RateYo plugin

I’m using jQuery RateYo plugin for showing star ratings on my product card. First time when the page loads it work perfectly, But when I sort value by Livewire it will not showing star rating. In my livewire component render method I use this

$this->dispatchBrowserEvent('contentChanged');

And into my blade I try this

window.addEventListener('contentChanged', (e) => {      
for (let index = 1; index <= 5; index++) {
    $(".rating_" + index).rateYo({
        rating: index,
        normalFill: "#CCC",
        ratedFill: "#FFC700",
        spacing: "5px",
        fullStar: true,
        starWidth: "16px"
    });
}

});
But it’s not working. Can anyone tell me how to show rating properly after livewire component render?

I tried to dispaly card with rating without page load by Livewire. But it’s not working. It only work when page is reload.

Detect clicked button Print / Cancel and run script accordningly

I want to detect that if a user clicked cancel button or print, so based on that button pressed i want to run separate scripts.
What i have done works when the print window closed.
any help is appreciated.

function printImage(imgSrc) {
    var staffno = "<?php echo $staffno; ?>";
    
    var printWindow = window.open('', '', 'width=600,height=600');
    printWindow.document.open();
    printWindow.document.write('<html><body>');
    printWindow.document.write('<div class="pagerA">');
    printWindow.document.write('<img style="margin-top: -8px; margin-left: -8px;" src="' + imgSrc + '" width="105%" />');
    printWindow.document.write('</div>');
    printWindow.document.write('<div class="pagerA">');
    printWindow.document.write('<img src="../../../images/idBacks.jpg" width="100%" />');
    printWindow.document.write('</div>');
    printWindow.document.write('</body></html>');
    printWindow.document.close();

    // Directly open the print preview dialog
    printWindow.print();

    // Check if the print window is closed periodically
    var checkPrintWindow = setInterval(function() {
        if (printWindow.closed) {
            console.log('Print window closed');
            clearInterval(checkPrintWindow); // Stop checking once closed
        }
    }, 1000); // Check every 1 second
}

I get an error when I connect with the https module in the API I created with Express.js

I wrote an API for my website’s contact form using Node.js, I host the API on AWS Lightshail, I got my SSL certificates from Cloudflare for free, and after 5-6 hours after starting the API, an error appears in the console, this error does not prevent the API from running. But I can’t find the cause, if anyone knows the solution, I would be grateful if you could help me.

Error below:

(node:5532) Warning: An error event has already been emitted on the socket. Please use the destroy method on the socket while handling a 'clientError' event. at warnUnclosedSocket (node:_http_server:839:11) at TLSSocket.socketOnError (node:_http_server:853:5) at onParserExecuteCommon (node:_http_server:888:19) at onParserExecute (node:_http_server:809:3)

Here are the modules I use (in case they are the cause of the problem) and how I use the HTTPS module;

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const rateLimit = require('express-rate-limit');

const cors = require('cors');
const crypto = require('crypto');

const chalk = require("chalk");
const figlet = require('figlet');
const moment = require('moment');

const https = require('https');
const fs = require('fs');
const axios = require('axios');

const app = express();

const options = {
    key: fs.readFileSync('./ssl/private-key.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem'),
};

const server = https.createServer(options, app);

server.listen(443, () => {    
    
    console.log(chalk.magenta(`[API]: `) + chalk.green('PORT : [' + PORT + ']'))

});

How to save Json response on puppeteer JS

We can launch browser in controlled environment on Node.js for example:

 const puppeteer = require('puppeteer');
 (async () => {
   const browser = await puppeteer.launch({
     headless: true
   });
   const page = await browser.newPage();
   await page.goto('https://www.oddsportal.com/');
   await page.setViewport({ width: 1920, height: 941 });
      await page.waitForSelector('.flex:nth-child(2) > .bg-gray-extra_dark > .h-     [16px]');
   await page.click('.flex:nth-child(2) > .bg-gray-extra_dark > .h-[16px]');
   await browser.close();
 })(); 

Usually browser generated a lot of Json-files, for example

Json response

How to save this response? Directly with Puppeteer or with Chrome Developer Tools.
If I understand this is two different methods.

Not-found page in next 13

I have huge problem with understanding with folder routing in next, but idk how to make custom 404 page.
directory of project

and i need to make not-found visible for all project. when i move it into ./app, it told me that i need to create layout, i make it, instead that i have layouts in (root) and (auth) (yeah i understand that this is can broke cause … layout + … layout just throw err.)
how to save my directories with layouts (root, auth) and add not-found.tsx in ./app without layouting or other method?

Scrape modern website by executing Javascript in Python without Selenium

I would like to scrape data from edreams.it for learning purposes and I would like to avoid using selenium. Searching through the web I got to know about requests-html having full JavaScript support and so being able to execute scripts. However, as soon as I run the following

from requests_html import HTMLSession

session = HTMLSession()
url = "https://www.edreams.it"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}                                                                                         
r = session.get(url=url, headers=headers)
r.html.render(sleep=2)
r.html.html

I get back

'<!DOCTYPE html>
<html>
    <head>n
        <title>Service Unavailable</title>n
        <style type="text/css">body { text-align: center; padding: 150px; }h1 { font-size: 40px; }body { font: 16px Helvetica, sans-serif; color: #333; }#error { display: block; text-align: left; width: 650px; margin: 0 auto; }</style>n
    </head>n
    <body>n
        <div id="error">n
            <h1>Oops! Something went wrong</h1>n
        <div>n
        <hr>n
        <p>Please contact your administrator with the error code: 0.ac641102.1694944919.1bb3d9c9</p>n
        </div>n</div>nn
    </body>
</html>'

Can anybody suggest a strategy to get around such block or point me to a useful resource? For instance, I’m thinking about a way to setup the headers properly so as to get a working response. Thank you!

Here are the versions of the relevant packages I’m using. With such setup I am able to avoid some compatibility issues arising between some versions of websockets and pyppeteer.

  • pyppeteer 1.0.2
  • requests-html 0.10.0
  • websocket-client 1.6.3
  • websockets 10.0

Chrome devtools: long GPU task. How to investigate?

I’m experimenting with Phaser.js and wrote a simple game. It runs smoothly, but from time to time I see a sudden frame drop. Nothing happens to cause this. No explosions, additional calculations, or anything like that. It’s running as usual, then freezing, and then everything’s back to normal.

The Performance tab shows this:

dev tools

The main JS thread is idling, and generally nothing’s going on, except for the long GPU task that comes out of nowhere. Unfortunately, there’s no detailed information available for it. Is there a way to investigate what’s going on there?

So far I’ve tried to play with different Phaser.js settings, such as render options and resolution, but that changed nothing at all. It’s difficult to do anything without knowing what causes the issue.

Why I’m getting EBUSY: resource busy or locked, open errno: -4082 error when build storybook 7 in next.js 13?

I want to build storybook but I got this error in my project:

[Error: EBUSY: resource busy or locked, open 'C:UsersaliDesktopWorksDesign Systemsprojectsstorybook-test2node_modules.cachestorybookdev-servera5a8bf6e622aef57065c6498611f40c911543d7d-a21314dc303cf26dabba6bf4a8fd381e47e44e94'] {
  errno: -4082,
  code: 'EBUSY',
  syscall: 'open',
  path: 'C:\Users\ali\Desktop\Works\Design Systems\projects\storybook-test2\node_modules\.cache\storybook\dev-server\a5a8bf6e622aef57065c6498611f40c911543d7d-a21314dc303cf26dabba6bf4a8fd381e47e44e94'
}

I cleared cache files then tried again build but it didn’t work. How can I solve this problem?
My packacge.json details:

{
  "name": "storybook-test2",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "storybook": "storybook dev -p 6006",
    "build-storybook": "storybook build"
  },
  "dependencies": {
    "@types/node": "20.5.9",
    "@types/react": "18.2.21",
    "@types/react-dom": "18.2.7",
    "eslint": "8.48.0",
    "eslint-config-next": "13.4.19",
    "next": "13.4.19",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "typescript": "5.2.2"
  },
  "devDependencies": {
    "@storybook/addon-essentials": "^7.4.0",
    "@storybook/addon-interactions": "^7.4.0",
    "@storybook/addon-links": "^7.4.0",
    "@storybook/addon-onboarding": "^1.0.8",
    "@storybook/blocks": "^7.4.0",
    "@storybook/nextjs": "^7.4.0",
    "@storybook/react": "^7.4.0",
    "@storybook/testing-library": "^0.2.0",
    "eslint-plugin-storybook": "^0.6.13",
    "storybook": "^7.4.0"
  }
}

Unable to send requests to backend API within NextAuth authorize function using credentials provider in Next.js

I am using NextAuth.js version 4 and have set up a custom authorize function using the CredentialsProvider to handle login. The API endpoint for login is working correctly, but when I attempt to make a request to the backend API server within the authorize function, it doesn’t seem to reach the API, and instead, I receive an error. I have provided the code for the route.ts file where the NextAuth configuration is set up.

I tried this:
in route.js file:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "email", placeholder: "Email" },
        password: {
          label: "Password",
          type: "password",
          placeholder: "Password",
        },
      },
      async authorize(credentials, req) {
        console.log(credentials);
        try {
          const res = await fetch("http://localhost:8000/auth/login/", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ ...credentials }),
          });
          if (!res.ok) {
            throw new Error("Incorrect credentials");
          }
          const data = await res.json();
          const user = data.user;
          console.log(data);
          if (user) {
            return Promise.resolve({
              id: user.pk,
              name: user.username,
              email: user.email,
              first_name: user.first_name,
              last_name: user.last_name,
              accessToken: data.access,
              refreshToken: data.refresh,
            });
          } else {
            return null;
          }
        } catch (error) {
          throw new Error("Credentials are incorrect");
        }
      },
    }),
  ],
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

I suspect that the issue may be related to how the API request is being made within the authorize function. Can someone guide me on what could be the mistake or why the request is not reaching the backend API? Any help or suggestions would be greatly appreciated. Thank you!

Mapbox GL JS in Chrome and Safari. Safari gives me an error while Chrome doesnt. How to fix?

I am get the following errors in SAFARI, however, not such errors are given in Chrome. My polygons dont work in Safari 🙁

Failed to load resource: the server responded with a status of 404 (Not Found)

https://api.mapbox.com/v4/[username].cpcvsbnk/11/1807/798.vector.pbf?sku=1014HAcymQWYX&access_token=pk.[token].IFlXQEMHIfmqrkeZ_U1Xcg

There are about 20 lines of errors all of similar type in safari. None in Chrome. My chrome mapbox map works well. In Safari, one polygon type is showing but the popup onclick is not working.

cpcvsbnk/11/1807/798. 

but also:

cpcvsbnk/11/1807/798
cpcvsbnk/11/1806/799
cpcvsbnk/10/903/398
etc

What is this error and how to fix?