Audio stopped playing after working several thousand times on line

The audio file, a 14 second mp3, is still at the google public drive as I can play the audio directly from the drive using the reference address from google chrome.

In my javascript, I define the audio source as shown:

<audio id="AveClip" preload>
    <source src="https://drive.google.com/uc?export=download&id=1mCd9HuDu2TqwRnlwe7LB4PbZkcJYdXLC" />
</audio> 

and the web page provides a button to play the audio:

<button style="font-size: 1.2em" onclick="document.getElementById('AveClip').play();">Ave:</button> 

When the button is pressed no audio is played.

The code has executed over 4000 times (web site accesses) without error and without changing the code it simply stopped playing at all when the button is pressed. I put in an alert both before and after the document.getElementById('AveClip').play(); on the button definition shown above and the alerts display so I know the code to access the the audio file within the program are getting executed but there is no audio. Hence I suspect the the preload is not happening. Is there a way to find out what is happening?

403 Forbidden Error when connecting React and Flask

Currently trying to connect some Flask code to my React website, but keep getting the 403 forbidden error.
Here’s my python file, api.py:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, origins="*")

@app.route('/api', methods = ['GET'])
def index():
    return {
        'name':'Hello World',
        'author': 'me',
        'hello': 'world'
    }
    
if __name__ == '__main__':
    app.run(debug = True)


While, here’s my react file that I’m using to fetch this information, CardPage.js,

import React from "react";
import Card from '../components/Card';
import { useState, useEffect } from "react";

function CardPage() {

    const [card, setCard] = useState([]);

    useEffect(() => {
        fetch('/api').then(response => {
            if(response.ok) {
            return response.json()
        }
    }).then(data => console.log(data))}, [])

    return(
        <>
        <Card></Card>
        </>
    )
}

export default CardPage

However, whenever I check my console, I’m consistently met with this error:
CardPage.js:10
GET http://localhost:3000/api net::ERR_ABORTED 403 (Forbidden)

Here is my package.json, as well:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://127.0.0.1:5000/",
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I’m completely stumped, to say the least. Any tips?

I’ve tried adding and removing CORS, along with changing the port in my app.run, but to no avail.

i have this problem when seeing the generated schedule on user it says “warning trying to access array offset on value of type null” [closed]

here’s the error

Warning: Trying to access array offset on value of type null in C:/xampp/htdocs/newfolder/scheduling/pages/faculty_home.php on line 74

Warning: Trying to access array offset on value of type null in C:/xampp/htdocs/newfolder/scheduling/pages/faculty_home.php on line 74

the code

Algolia Hit Component is not working with grid

Im converting my next api to a algolia search, and hit component is a single component that renders foreach record, but i am unable to use grid, i will show how i was doing (it was working):


      { {propostas.length == 0 ? (
        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
          {timesToRenderPropostas.map((_, index) => (
            <SkeletonPropostas index={index} key={index} />
          ))}
        </div>
      ) : (
        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
          {propostas.map((proposta: any) => (
            <div key={proposta.id} className=" rounded-lg ">
              <div className="mx-auto mt-4 max-w-sm overflow-hidden rounded-2xl bg-white p-2">
                <p className="bg-white font-semibold text-gray-700">
                  {proposta.Categoria?.name}
                </p>
                <div className="mb-2 bg-white pt-2 text-lg font-bold">
                  {proposta.title}
                </div>
                <div>
                  {proposta.textComplete != null ? (
                    <h1 className="bg-white pl-2 font-semibold text-slate-500">
                      {proposta.textComplete}
                    </h1>
                  ) : (
                    <div></div>
                  )}
                </div>
                <div className=" bg-white pb-2 pt-4">
                  {proposta.Status?.name == "Sem dados" ? (
                    <span className="mb-2 mr-2 inline-block rounded-full bg-[#ACACAC] px-3 py-1 text-sm font-semibold text-white">
                      Sem Dados
                    </span>
                  ) : proposta.Status?.name == "Cumpriu" ? (
                    <span className="mb-2 mr-2 inline-block rounded-full bg-[#51A975] px-3 py-1 text-sm font-semibold text-white">
                      Cumpriu
                    </span>
                  ) : proposta.Status?.name == "Não cumpriu" ? (
                    <span className="mb-2 mr-2 inline-block rounded-full bg-[#FF4D4D] px-3 py-1 text-sm font-semibold text-white">
                      Não cumpriu
                    </span>
                  ) : proposta.Status?.name == "Em partes" ? (
                    <span className="mb-2 mr-2 inline-block rounded-full bg-[#FFBB5D] px-3 py-1 text-sm font-semibold text-white">
                      Em partes
                    </span>
                  ) : (
                    <p>.</p>
                  )}
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(proposta.title);
                      const showToastMessage = () => {
                        toast.success("Copiado", {
                          position: toast.POSITION.TOP_RIGHT,
                          autoClose: 1500,
                        });
                      };
                      showToastMessage();
                    }}
                    className="mb-2 mr-2 inline-block rounded-full bg-gray-300 px-3 py-1 text-sm font-semibold text-slate-700"
                  >
                    Copiar
                  </button>
                  <Link href={`/edit/proposta/${proposta.id}`}>
                    <span className="mb-2 mr-2 inline-block rounded-full bg-gray-300 px-3 py-1 text-sm font-semibold text-slate-700">
                      Editar
                    </span>
                  </Link>
                </div>
              </div>
            </div>
          ))}
          <ToastContainer />
        </div>
      )} 

with algolia it goes like that

variable:

  const Hit = ({ hit }) => (
    <div className="rounded-lg">
      <div className="mx-auto mt-4 max-w-sm overflow-hidden rounded-2xl bg-white p-2">
        <p className="bg-white font-semibold text-gray-700">
          {hit.Categoria?.name}
        </p>
        <div className="mb-2 bg-white pt-2 text-lg font-bold">
          {hit.title}
        </div>
        <div>
          {hit.textComplete != null ? (
            <h1 className="bg-white pl-2 font-semibold text-slate-500">
              {hit.textComplete}
            </h1>
          ) : (
            <div></div>
          )}
          <div className=" bg-white pb-2 pt-4">
            {hit.Status?.name == "Sem dados" ? (
              <span className="mb-2 mr-2 inline-block rounded-full bg-[#ACACAC] px-3 py-1 text-sm font-semibold text-white">
                Sem Dados
              </span>
            ) : hit.Status?.name == "Cumpriu" ? (
              <span className="mb-2 mr-2 inline-block rounded-full bg-[#51A975] px-3 py-1 text-sm font-semibold text-white">
                Cumpriu
              </span>
            ) : hit.Status?.name == "Não cumpriu" ? (
              <span className="mb-2 mr-2 inline-block rounded-full bg-[#FF4D4D] px-3 py-1 text-sm font-semibold text-white">
                Não cumpriu
              </span>
            ) : hit.Status?.name == "Em partes" ? (
              <span className="mb-2 mr-2 inline-block rounded-full bg-[#FFBB5D] px-3 py-1 text-sm font-semibold text-white">
                Em partes
              </span>
            ) : (
              <p>.</p>
            )}
            <button
              onClick={() => {
                navigator.clipboard.writeText(hit.title);
                const showToastMessage = () => {
                  toast.success("Copiado", {
                    position: toast.POSITION.TOP_RIGHT,
                    autoClose: 1500,
                  });
                };
                showToastMessage();
              }}
              className="mb-2 mr-2 inline-block rounded-full bg-gray-300 px-3 py-1 text-sm font-semibold text-slate-700"
            >
              Copiar
            </button>
            <Link href={`/edit/proposta/${hit.id}`}>
              <span className="mb-2 mr-2 inline-block rounded-full bg-gray-300 px-3 py-1 text-sm font-semibold text-slate-700">
                Editar
              </span>
            </Link>
          </div>
        </div>
      </div>
    </div>
  );

and the component:

   <InstantSearch
        searchClient={searchClient}
        indexName="propostas"
        onStateChange={onStateChange}
      >
        <SearchBox />
        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
          <Hits hitComponent={Hit} />
        </div>
      </InstantSearch>

how to make each hit record inside a grid of 3 elements, like the previous code?

what are the advantage of having each component as seperate npm package in UI design systems?

In a few UI components libraries, why are they making every component an individual npm package instead of having all the components as one whole package? What advantage does it give?

Here are some sample repos

github primer react – where each component is combined all together as one whole package

reach UI – where each component is a separate npm package.

What advantage does one have over the other? I guess both respect tree shaking and do not bundle the components that are not used when consumed. What is the principle behind it.

Two components with same animation values animating at different speeds

Using React Native I am trying to animate a header when the user scrolls up on a FlatList, however, my FlatList seems to be animating faster than my Header. Even though I am using the same values – any reason why?

Here is the code for the Header;

const animateTransform = {
    translateY: scrollOffset.interpolate({
      inputRange: [0, 57],
      outputRange: [0, -57],
      extrapolate: "clamp",
    }),
  };

const opacity = scrollOffset.interpolate({
  inputRange: [0, 57 / 1.25],
  outputRange: [1, 0],
  extrapolate: "clamp",
});

return (
  <Animated.View style={[safeAreaContainerStyle, { transform: [animateTransform] }]}>
    <Animated.View style={[containerStyle, { opacity }]}>
      <TouchableOpacity
        style={locationContainerStyle}
        onPress={pushCityScreen}>
        <Text style={exploringStyle}>Exploring</Text>
        <View style={cityContainerStyle}>
          <Text style={cityNameStyle}>{city[language].name}</Text>
          <Feather
            name="chevron-down"
            size={15}
            color={textColor}
          />
        </View>
      </TouchableOpacity>
    </Animated.View>
  </Animated.View>
)

Here is my code for the FlatList;

const marginTop = scrollOffsetY.interpolate({
    inputRange: [0, 57],
    outputRange: [0, -57],
    extrapolate: "clamp",
  });

  const onScroll = Animated.event([{ nativeEvent: { contentOffset: { y: scrollOffsetY } } }], {
    useNativeDriver: false,
  });

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <HomeHeader scrollOffset={scrollOffsetY} />
      {loading ? (
        <HomeSkeleton />
      ) : (
        <>
          <Animated.FlatList
            onScroll={onScroll}
            ListHeaderComponent={listHeaderComponent}
            data={venues}
            keyExtractor={(item) => item.id}
            renderItem={renderItem}
            ListFooterComponent={listFooterComponent}
            initialNumToRender={5}
            maxToRenderPerBatch={20}
            scrollEventThrottle={16}
            onEndReachedThreshold={0.5}
            refreshing={refreshing}
            onRefresh={onRefresh}
            style={{ marginTop: marginTop }}
            contentContainerStyle={{ paddingTop: 10 }}
            scrollIndicatorInsets={{ top: 10 }}
          />
          <StatusBar style={colorScheme === "light" ? "dark" : "light"} />
        </>
      )}
    </SafeAreaView>
  );

not able to run sendEmail.js in nodejs, using nodemailer (Error- Configuration property “EMAIL_SMTP” is not defined) –

i am trying to send mail using nodemailer and tried differnt hosts services but encountering this error

WARNING: No configurations found in configuration directory:/home/ayeen/manage/proj-ang/server/utils/config
WARNING: To disable this warning set SUPPRESS_NO_CONFIG_WARNING in the environment.
/home/ayeen/manage/proj-mang/server/node_modules/config/lib/config.js:182
throw new Error(‘Configuration property “‘ + property + ‘” is not defined’);
^

Error: Configuration property “EMAIL_SMTP” is not defined

i have json file at config which is
default.json

{
    "PORT": 5000,
    "URL": "PROJECT-URL",
    "EMAIL_SMTP": {
        "HOST": "smtp.elasticemail.com",
        "AUTH": {
            "USER": "***[email protected]",
            "PASS": "*******"
        },
        "PORT": 252
    },
    "SEND_SMS": {
        "TWILIO_SID": "*********",
        "TWILIO_TOKEN": "********",
        "TWILIO_NUMBER": "+*****"
    },
    "DB_URI": "********"
}

and sendEmail.js have this code simpily to send mail

import nodelmailer from "nodemailer";
import config from "config"
// import fs from "fs/promises";

const { HOST, AUTH, PORT } = config.get("EMAIL_SMTP");

async function sendMail(emailData) {
    try {
        let transporter = nodelmailer.createTransport({

            host: HOST,
            port: PORT,
            secure: true,
            auth: {
                user: AUTH["USER"],
                pass: AUTH["PASS"]
            }
        });

        let info = await transporter.sendMail({
            from: `"AD sol" <${AUTH["USER"]}>`,
            subject: emailData.subject, // Subject line
            to: emailData.to,
            html: emailData.body
        });
        console.log("EMAIL SENT");
//         await fs.appendFile("logs/emaillogs.txt", `${info.messageId}
// `);
    } catch (error) {
        console.log(error);
    }
}

// sendMail()
sendMail({
    subject: "User Account Verification - Test",
    to: "ayeen0410gmail.com",
    body: "Testing "
});
export default sendMail;

I thought it was host error and tried differnt host services but encounterd same error.

Xenova Transformers JS automatic-speech-recognition is generating nonsense text

I’m trying to implement STT functionality in my NodeJS app using @xenova/transformers and whisper-tiny using the pipeline, e.g.:

const transcriber = await pipeline(
      "automatic-speech-recognition",
      "Xenova/whisper-tiny.en",
      {
        progress_callback: (...args: any) => {
          console.log("Progress:", ...args);
        },
      }
    );

It works perfectly with speech-only audios but fails with mixed ones, e.g., music + speech. In that case, the resulting text is a cut audio version. So, I tried it with a different file. I downloaded “Ted 60” from Hugging Face and added music to the beginning of the audio, and it works as it should. So, the problem might be my audio file.

The only difference I noticed is that the “Ted 60” sample is 48000Hz, so I generated my audio again with that rate – but that didn’t help at all, and, this time, it started to give me a bunch of nonsense text, nothing to do with the file content.

So, I’d like to know how I should create that file. I’m using FFmpeg to do it; here’s a snippet of my code:

  const stream = ytdl(`https://www.youtube.com/watch?v=${id}`, {
    filter: "audioonly",
  });

 // some logic here

  return new Promise((resolve, reject) => {
    ffmpeg(stream)
      .audioFrequency(48000)
      .toFormat("wav")
      .save(filePath)
      .on("end", () => {
        console.log(`Downloaded: ${title}`);
        resolve(true);
      })
      .on("error", (err) => {
        console.error(`Error on downloading ${title}: ${err.message}`);
        reject(err);
      });
  });

Any help would be very appreciated.

How to get m3u8 playlist from yotube video link?

In the past, I was able to get m3u8 playlist links using Chrome developer tools while checking network tab.

I’ve tried to get it today, but I wasn’t able to find it. I’ve spent almost whole day trying to find it. I’ve read many articles but without any luck.

enter image description here

This is not working anymore. It doesn’t show anything. But as youtube-dl is still working, I am positive about it can be done somehow but hidden somewhere.

Anyone dealt with this recently?

React adding extra bracket to json prevent data from saving

I am trying to send data to the server to save with fetch in react but react is adding extra square brackets to the json and server is throwing an error.

const [answers, setAnswers] = useState([{ QuestId:0, Ans:"",correct:false }]);
    const handleAddInput = () => {
      setAnswers([...answers, { QuestId:0, Ans:"",correct:false }]);
    };

fetch("http://localhost:57030/api/answers", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(answers),
    })
      .then(res => res.json())
      .then(res => {
          console.log(res);
        },
        (error) => {
          alert("Failed" + error);
        }
      );

JSON created

[{"QuestId":1100,"Ans":"fffff","correct":false},{"QuestId":1100,"Ans":"fffff","correct":false},{"QuestId":1100,"Ans":"ffff","correct":false}]

The square brackets at the start and the end are not needed.

Angular-AppComponent error. How solve it?

I have a problem with my Angular project. In my app.module.ts the code is below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BmiModule } from './bmi/bmi.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BmiModule
  ],
  providers: [],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule { }

My app.component.ts is below:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';


@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})

export class AppComponent {
  title = 'WP4_HF_004';
}

My app.component.html:

<h1>BMI kalkulátor</h1>
<p>Ez egy BMI kalkulátor. A lenti 4 gomb segítségével lehet módosítani a súly- és magasságparamétereket.
    <app-bmi-calculator></app-bmi-calculator>
</p>

I got an error in app.module.ts:

Component AppComponent is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?

If I didn’t import my AppComponent in app.module.ts I get an error in app.component.html:

‘app-bmi-calculator’ is not a known element:

  1. If ‘app-bmi-calculator’ is an Angular component, then verify that it is included in the ‘@Component.imports’ of this component.
  2. If ‘app-bmi-calculator’ is a Web Component then add ‘CUSTOM_ELEMENTS_SCHEMA’ to the ‘@Component.schemas’ of this component to suppress this message.ngtsc(-998001)
    app.component.ts(4, 5):

Error occurs in the template of component AppComponent.

I searched the problem on the internet but I didn’t find the solve.

Can we change the div next to the left menu side bar t the page we want [closed]

This situation kina look a like when we using React Router Dom in React, i have a left menu side bar and in the right a div it contain mainpage.html contactus.html and go on, when i clicked it only changed the mainpage.html into contacus.html like when we use React Router in react but instead of react we using it in html css

i dont know, can somebody help me pls

Reactjs – Mock multiple useRefs react testing library

I have created a custom hook that I am going to use to build a custom scroll component. The hook works however I am failing to cover it with unit test.

I believe it’s because I am not mocking the useRef correctly but there might be other things as well that I am missing. I have checked many articles and posts but couldn’t find an answer to my problem.

This is the hook I have created:

export const useScrollArea = () => {
  const containerRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const scrollBarThumbRef = useRef<HTMLDivElement>(null);
  const [isScrollable, setIsScrollable] = useState(false);

  const isOverflowing = useCallback(() => {
    if (!containerRef.current || !contentRef.current) {
      return false;
    }

    const isContentOverflowing =
      contentRef.current.scrollHeight > containerRef.current.clientHeight;

    setIsScrollable(isContentOverflowing);
  }, []);

  const updateThumbPosition = useCallback(() => {
    const scrollRatio =
      containerRef.current.scrollTop /
      (contentRef.current.scrollHeight - containerRef.current.clientHeight);

    const thumbTop =
      scrollRatio *
      (containerRef.current.clientHeight -
        scrollBarThumbRef.current.clientHeight);

    scrollBarThumbRef.current.style.transform = `translateY(${thumbTop}px)`;
  }, []);

  const scroll = (direction: ScrollDirection) => {
    if (
      !containerRef?.current ||
      !contentRef?.current ||
      !scrollBarThumbRef?.current ||
      !isScrollable
    ) {
      return;
    }

    const maxScrollPosition =
      contentRef.current.scrollHeight - containerRef.current.clientHeight;
    let newScrollPosition =
      containerRef.current.scrollTop +
      (direction === 'up' ? -1 : 1) * SCROLL_STEP;

    newScrollPosition = Math.max(
      0,
      Math.min(newScrollPosition, maxScrollPosition)
    );

    containerRef.current.scroll({ top: newScrollPosition });

    updateThumbPosition();
  };

  useEffect(() => {
    isOverflowing();
  }, [isOverflowing]);

  return {
    scroll,
    isScrollable,
    contentRef,
    containerRef,
    scrollBarThumbRef
  };
};

These are some of the unit tests I have created:

const mockContainerRef = {
  current: {
    clientHeight: 100,
    scrollTop: 0,
    scroll: jest.fn()
  }
};

const mockContentRef = {
  current: {
    scrollHeight: 200
  }
};

const mockScrollBarThumbRef = {
  current: {
    clientHeight: 50,
    style: {
      transform: ''
    }
  }
};

jest.mock('react', () => ({
  ...jest.requireActual('react'),
  useRef: jest
    .fn()
    .mockImplementationOnce(() => mockContainerRef)
    .mockImplementationOnce(() => mockContentRef)
    .mockImplementationOnce(() => mockScrollBarThumbRef)
}));

describe('useScrollArea', () => {
  it('should return `isScrollable` as true when content is overflowing', () => {
    const { result } = renderHook(() => useScrollArea());

    expect(result.current.isScrollable).toBe(true);
  });

  it('should return `isScrollable` as false when content is not overflowing', () => {
    mockContentRef.current.scrollHeight = 50;

    const { result } = renderHook(() => useScrollArea());

    expect(result.current.isScrollable).toBe(false);
  });

  it('should scroll down', () => {
    mockContainerRef.current.scrollTop = 100;

    const { result } = renderHook(() => useScrollArea());

    act(() => {
      result.current.scroll('down');
    });

    expect(mockContainerRef.current.scroll).toHaveBeenCalledWith({ top: 40 });
  });
});

Unfortunately, I keep getting errors such as:

TypeError: Cannot read properties of undefined (reading 'current')

or the hook not returning the expected outcome.

resizeable Window not expand fully due to flex-grow

I’m designing a layout similar to the sidebar of the CodePen. While I’ve managed to replicate most of its behavior, I’m facing an issue when sliding windows upwards—everything works smoothly. However, when sliding downwards, the containers at the bottom fail to expand fully, unlike the demonstration in the provided code. Could someone point out where I might be making an error and help me rectify it?

function handleEditorWindowResize () {

    const parent = document.querySelector("aside")
    const editorWindows = document.querySelectorAll("aside > div")
    const labelHeight = document.querySelector(".lang-label")
        .getBoundingClientRect().height-4

    const handleResize = (ele)=> {
        let startY =0, height = 0;
        
        const disableInteraction = (ele, state)=> {
            if(state) {
                ele.style.userSelect = 'none';
                ele.style.pointerEvents = 'none';
            } else {
                ele.style.removeProperty('user-select');
                ele.style.removeProperty('pointer-events');
            }
        }

        const handleMouseDown = (e)=> {
            startY = e.clientY - 2; // 2 coming from cuz we have 2px border of hr in css
            height = ele.previousElementSibling.getBoundingClientRect().height;

            editorWindows.forEach((ele) => {
                disableInteraction(ele, true)
            });

            window.addEventListener("mousemove", handleMouseMove);
            window.addEventListener("mouseup", handleMouseUp);

            ele.style.borderWidth = `5px`;

        }
        
        const handleMouseMove = (e)=> {
            const dy = e.clientY - startY;
            const h = ((height + dy) * 100) / parent.getBoundingClientRect().height;
            ele.previousElementSibling.style.height = `calc(max(${h}%, ${labelHeight}px)`;

            editorWindows.forEach(win=> {
                if(
                    win === ele.nextElementSibling 
                ) {
                    win.style.flex = '1';
                    win.style.height = `${win.clientHeight}px`;
                } else {
                    win.style.removeProperty("flex")
                    win.style.height = `${win.clientHeight}px`
                }
            })
        }   
        
        const handleMouseUp = (e)=> {
            editorWindows.forEach(ele => disableInteraction(ele, false));
            window.removeEventListener("mousemove", handleMouseMove);
            window.removeEventListener("mouseup", handleMouseUp);
            ele.style.borderWidth = `2px`;
        }

        ele.addEventListener("mousedown",handleMouseDown);
    }

    document.querySelectorAll("aside > .h-divider")
        .forEach(ele => handleResize(ele));
}

handleEditorWindowResize()
:root {
  /*
    Source: 
      https://colorhunt.co/palette/191919750e21e3651dbed754
  */
  --black: #111;
  --maroon: rgb(117, 14, 33);
  --orange: rgb(227, 101, 29);
  --green: rgb(190, 215, 84);
  --text-color: rgba(255,255,255,1);
  --light-text-color: rgba(255,255,255,0.8);
  --overlay-color: rgba(255,255,255,0.1);

  --gray-100: #111;
  --gray-400: #444;
}

body, html {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
}

main {
  display: flex;
  width: 100%;
  height: 100%;
}

.divider {
  background-color: var(--gray-400);
  cursor: ew-resize;
  height: 100%;
  width: 8px;
}

aside {
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

aside > div {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: calc(100% / 3);
  position: relative;
}  

aside > div:last-child {
  /* flex: 1; */
  /* height: auto; */
}

aside > .h-divider {
  border: 2px solid var(--gray-400);
  position: sticky;
  cursor: row-resize;
}

aside textarea {
  overflow-y: auto;
  min-width: 100%;
  max-width: 100%;
  flex:1;
  padding: 0.5rem;
  font-size: 0.8em;
  background: var(--black);
  border: none;
  font-weight: 300;
  border-bottom: 1px solid var(--gray-400);
  background: var(--gray-100);
  color: var(--light-text-color);
}

aside textarea:focus { outline: none; }

.lang-label {
  padding: 0.3rem;
  background-color: var(--maroon);
  font-weight: 700;
  display: flex;
  align-items: center; 
  gap: 0.3rem;
  position: relative;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  
  <!-- main layout -->

  <main>
    <!-- code -->
    <aside>
      <div>
        <div class="lang-label">
          HTML
        </div>
        <textarea data-lang="html"></textarea>
      </div>
      <span class="h-divider"></span>

      <div>
        <div class="lang-label">
          CSS
        </div>
        <textarea data-lang="css"></textarea>
      </div>
      
      <span class="h-divider"></span>

      <div>
        <div class="lang-label">
          JS
        </div>
        <textarea data-lang="js"></textarea>
      </div>
    </aside>
  </main>
</body>
</html>

Issue with Axios Interceptors Not Updating State in React After JWT Renewal

In my setup, I’m using Axios interceptors to handle the JWT renewal process. The interceptor catches the failed request due to an expired token, successfully renews the token, and then retries the original request with the new token. Although the retried request completes successfully, the response from this request doesn’t seem to update my component’s state via setData.

// Axios interceptor setup in providers.tsx
api.instance.interceptors.response.use(
  (response) => response,
  async (error) => {
    // ... error handling and token renewal logic ...
    return api.instance(originalRequest); // Retrying the request
  },
);

// React component
const TestPage = () => {
  const [data, setData] = useState([]);

  const fetchData = () => {
    // API call using Axios
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      <Button onClick={fetchData}>Fetch Data</Button>
      {data.map((item, index) => (
        <p key={index}>{item.name}</p> // Example rendering
      ))}
    </div>
  );
};

Questions:

  1. Why is the state not being updated with the data from the retried request?
  2. Is there a better approach to handle JWT renewal and state management in React with Axios interceptors?

I’m wondering if I’m missing something obvious or if there’s a more effective pattern to handle this. Any insights or suggestions would be greatly appreciated.

Thank you in advance!