R Shiny Mediafiles Won’t Stop Playing On Page Exit – Selector for HTML5 Audio play/pause?

I’m having an issue with my mediafiles in my Shiny app: I can’t get them to stop playing when the user navigates to a different page.

Background/dependencies:
I’m using shiny.router for basic routing between the app’s pages. I’m using shinyjs and jquery here and there to allow for some dynamic div appending and accordions.

Problem:
I’ve noticed that for some reason my </audio/> and </video/> files keep playing even when the user changes the page they’re on. This is strange as the audio element isn’t ‘visible’ to the user, and the page (and associated url) changes, yet the audio or video files from different pages continue playing.
The only way to ensure there is no overlap in the mediafiles playing is to make sure to ‘pause’ before exiting the page.
I would like to make this behavior automatic, and thought it was for default HTML5 audio controls. I suspect it may have to do with how shiny.router creates different ‘pages’, however, I’m not advanced enough in my JS and web dev knowledge to understand how these ‘pages’ are navigated between internally. It seems, though, as if they are all overlapping in some way and the ‘routing’ offered by the shiny.router package isn’t necessarily routing so much as it is hiding/revealing the different elements or ‘pages’.

Attempted solutions: My first thought was to use JQuery or Javascript to check, each time an audioplayer’s play/pause button is clicked, if any other audio elements are playing and pause them if they don’t match the ID of the clicked audioplayer’s play/pause button like this:

$(currentAudioPlayButtonID).clicked(  // when audio button clicked
  $("audio").each(                    // look at all audio elements
    if $(this).attr("id") != currentAudioPlayButtonID  
      $(this).pause()                 // 
  )
)

// OR invert the logic:

$(currentAudioPlayButtonID).clicked(  // when audio button clicked
  $("audio").each(                    // look at all audio elements
      $(this).pause()                 // pause all audio elements
  )
  currentAudioPlayButtonID.play()     // play the relevant audio
)

However, I’ve found that the play/pause toggler button that comes with the HTML5 audio element doesn’t seem to have a selector. I could create a new separate play/pause button with JQuery, however, I’d like to stick to using the simple element and its controls.
I found that there is the ‘.paused’ class that can be used to check if an HTML5 audio player is playing, however, I’m not sure how to use this in a function as I still ultimately would have no button to ‘trigger’ this ‘are other audios playing’ check. Would there potentially be a solution using $(document).load, where I would insert the ‘check’ code there?

If anyone has had a similar issue with shiny/shiny.router or may have any advice for how to ensure all other audio/video elements on the website are paused when a new one is clicked, I would deeply appreciate it! I think the answer may be simple but I am not very experienced in web dev and Shiny. Thank you for your help! I appreciate it.

Why isn’t my navbar.css not showing up in localhost page?

I am enrolled in a full stack web development course and currently learning react on the side to build a project for my portfolio in hopes of getting into a front end web developer position.

Found this 2 year old tutorial in which I thought was a decent start to learn: https://www.youtube.com/watch?v=QwarZBtFoFA&t=700s, and this is my third hurdle that I haven’t been able to get over.

No errors are showing up, I’ve tried changing tags around, moving/renaming, and searching for an answer but I can’t seem to get the right one.

TIA

components/Navbar.js

import React, { useState } from 'react';
import Logo from '../images/HHlogo.jpg';
import { Link } from 'react-router-dom';
import "../styles/Navbar.css";

function Navbar() {
  return (
    <div className="Navbar">
      <div className="leftSide">
        <img src={Logo} alt=',' />
      </div>
      <div className="rightSide">
        <Link to="/Home">Home </Link>
        <Link to="/About">About </Link>
        <Link to="/Classes">Classes </Link>
        <Link to="/Gallery">Gallery </Link>
        <Link to="/Trainer">Trainer </Link>
        <Link to="/Testimonial">Testimonial </Link>
        <Link to="/Contact">Contact </Link>
      </div>
    </div>
  );
}

export default Navbar

src/styles/Navbar.css

.navbar {
  width: 100%;
  height: 100px;
  background-color: #121619;
  display: flex;
  flex-direction: row;
}

.navbar .leftSide {
  flex: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  padding-left: 150px;
}

.navbar .leftSide img {
  width: 70px;
}

.navbar .rightSide {
  flex: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar a {
  color: white;
  text-decoration: none;
  margin: 20px;
}

.navbar .rightSide button {
  background-color: transparent;
  border: none;
  color: white;
  cursor: pointer;
}

.navbar .rightSide svg {
  font-size: 40px;
}

.navbar #open {
  padding-left: 0px;
}
.navbar #open img {
  display: none;
}

.navbar #close img {
  display: inherit;
}

.navbar #open .hiddenLinks {
  display: inherit;
  margin-left: 30px;
}

.navbar #close .hiddenLinks {
  display: none;
}

.navbar #open a {
  width: 70px;
  margin: 5px;
}
@media only screen and (max-width: 900px) {
  .navbar .rightSide a {
    width: 70px;
  }
  .navbar .leftSide {
    padding-left: 50px;
  }
}

@media only screen and (max-width: 600px) {
  .navbar .rightSide a {
    display: none;
  }

  .navbar .rightSide {
    justify-content: flex-end;
    padding-right: 50px;
  }

  .navbar .rightSide button {
    display: inherit;
  }
}

@media only screen and (min-width: 600px) {
  .navbar .rightSide button {
    display: none;
  }

  .hiddenLinks {
    display: none;
  }
}

src/App.js

import React from 'react';
import Home from './pages/Home';
import './App.css';
import Navbar from './components/Navbar';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

function App() {
  return (
    <div className="App">
      <Router>
        <Navbar />
        <Routes>
          <Route path="/" exact component={Home} />
        </Routes>
      </Router>
    </div>


  );
}

export default App;

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Image slider by using html, css, js

Who knows how can I create an imagesSider that there are 3 images, and they use the whole width of the screen. There are 2 buttons for moving to the next / previous pic. I want one pic to be fixed on the center and other pics to be on the other side of the center pic. When I click the next button, the center pic goes to the right pic and the right pic goes to the left pic and the left pic goes to the center. It is a loop for rounding.

I know how to create an imagesSider in one frame, but there is a problem:
When the last picture is done, the program tries to back first pic by sliding between pics.
I don’t want to!

i cant understand how this javascript dupes program works [closed]

i have this program that turns all numbers inside an array(nums) in to negative numbers and if a number is already negative it turns it to a positive and puts it inside another array(arr).

let nums = [1,2,2,4];
let arr = [-1, -1];


for(let i of nums){
  if(nums[Math.abs(i)-1]<0){
    arr[0] = Math.abs(i);
  }else{
    nums[Math.abs(i)-1]*=-1;
  }
}

console.log(nums);

i have a problem understanding why this block of code turns every number inside the array of numbers
to a negative number except for the one that is duplicated, if anyone has an explanation thank you in advance.

LiquidJS not working as expected in Shopify

In my Shopify theme I am trying to apply some LiquidJS code. However, it’s not working as expected and no errors are present. I have the exact same code in my Liquid template as I have in this CodePen, but the result is nothing. The console.log(html) on line 20 in the CodePen is present in the log, but when I apply the code in my Shopify theme, the log is empty.

Can someone guide me to a solution or what I can look into?

How to compress an image and encode as text?

the following use case is the basis for the question:
Send an image as text through the wire? Doing it with the smallest size footprint.

I’m aware that to send binary data (the image) as text, the standard solution is to encode it to base64. However, as known, it increase the size by around 33%.

Is there a way to use compression and still send the image as text?

If I encode to base64 and then gzip, for example, will the gz buffer be again binary or will it be string?

Or the other way around, can I first gzip the image in memory, and then encode to base64 to send it through the network?

Obs: an example code in node.js would be appreciated.

Thanks.

Seeking help for the time analysis of a potential optimization of merge sort

Wrote this potentially more optimized version of merge sort. The code can be found here: https://github.com/AntonM-248/CodingInterviewPractice/blob/main/IK_Coursework/SortingAlgorithms/mergeAcross.js. I also copied it below. I’m looking for help with time analysis from someone who has more expertise. My thought process was that an array should probably be partially sorted anyway so what if instead of breaking the array down into arrays of size 1 and merging, why not just merge those partially sorted arrays. So for example if you have and array [1, 4, 2, 3], just merge [1, 4] and [2, 3]. It first scans the entire array once to get the positions of the partially sorted sections. Then it puts the start and end positions of those sections into a stack and uses the positions to merge while it scans through the array repeatedly. Then if there is any last remaining bit that hasn’t been merged that gets merged outside of the while loop. My time analysis for it was that it would be bounded between O[n] in the best case where the array is already sorted and O[nlogn] in the worst case where the array is reversed.

function merge_across(arr) {
  let stack = getSortedSectionsStack(arr);
  let tempStack = [];
  while(stack.length > 3) {
    let end2 = stack.pop();
    let start2 = stack.pop();
    let end = stack.pop();
    let start = stack.pop();
    merge_two_sections(start, end, start2, end2, arr);
    tempStack.push(end2);
    tempStack.push(start);
    if(stack.length == 0) {
      while(tempStack.length > 3) {
        stack.push(tempStack.pop());
        stack.push(tempStack.pop());
        stack.push(tempStack.pop());
        stack.push(tempStack.pop());
      }
    }
  }
  let start = 0;
  let end = find_end_of_sort(start, arr);
  let start2 = end + 1;
  let end2 = find_end_of_sort(start2, arr);
  if(start2 < arr.length) {
    merge_two_sections(start, end, start2, end2, arr);
  }
  return arr;
}

function merge_two_sections(start, end, start2, end2, arr) {
  let merged_section = new Array(end2 - start + 1);
  let merge_index = 0;
  let original_start = start;
  while(start <= end && start2 <= end2) {
    if(arr[start] < arr[start2]) {
      merged_section[merge_index] = arr[start];
      start++;
    }
    else if(arr[start2] <= arr[start]) {
      merged_section[merge_index] = arr[start2];
      start2++;
    }
    merge_index++;
  }
  while(start <= end) {
    merged_section[merge_index] = arr[start];
    start++;
    merge_index++;
  }
  while(start2 <= end2) {
    merged_section[merge_index] = arr[start2];
    start2++;
    merge_index++;
  }
  for(let i = 0; i < merged_section.length; i++) {
    arr[original_start] = merged_section[i];
    original_start++;
  }
}

function find_end_of_sort(start, arr) {
  while(start < arr.length - 1 && arr[start] < arr[start + 1]) {
    start++;
  }
  return start;
}

Continuous Api calls with chrome extension

Beginner web developer here I am creating a password manager and I thought it would be cool to create a chrome extension for it. So far I have been able to make progess but now I’m wondering if there’s a more efficent way I can do it. I used set interval to constanty grab the id_token
(a jtw token) from the deployed site that is in local storage and then with the token I can make an api request to the graphl endpoint (the jwt is use in the bearer for auth). Like I said it works but in terms of perfoance and optimization I was wonder if there was a cleaning way to do things

I was think of using chrome.create.alarm but I want it so that the the user doesnt have to for instance log back into the chrome extension and to from my understanding creating the alarm requries some sort of button click and the minimum interval is 1 minute

export const getBearerKey = async () => {
  const deployedSite = await chrome.tabs.query({ url: 'https://passwordmanager-zep7.onrender.com/*' });
  const page = deployedSite[0];
  if (page) {
chrome.scripting.executeScript({
  target: { tabId: page.id },
  function: () => {
     setInterval(()=>{
    const token = localStorage.getItem('id_token');
    chrome.storage.local.set({ bearerKey: token });
     },1000)

  },
});

  } 
};


export const checkLoginStatus = async (bearerKey) => {

      const graphqlEndpoint = 'https://passwordmanager-zep7.onrender.com/graphql';
      const graphqlQuery = `query Me {
        me {
          _id
          username
          email
          password {
            _id
            text
            length
            uppercase
            lowercase
            number
            specialCharacter
          }
          accounts {
            _id
            username
            email
            websiteUrl
            notes
            created
            updated
          }
        }
      }`;

      try {
        const response = await fetch(graphqlEndpoint, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${bearerKey}`
          },
          body: JSON.stringify({
            query: graphqlQuery,
          }),
        });

        const { data } = await response.json();
        chrome.storage.local.set({user:data})
      } catch (error) {
        console.error('GraphQL Error:', error);
      }
    }

import { checkAccounts } from "./api/checkAccounts.js"
chrome.runtime.onInstalled.addListener(details=>{
     setInterval(()=>{
getBearerKey()
  chrome.storage.local.get(['bearerKey'], (result) => {
    const {bearerKey}=result
    checkLoginStatus(bearerKey)
  });
       checkAccounts() 
     },1000)
      

})  

Convert object from tree format to array format

I have an object, I need to parse and put in another object from format 1 to format 2.

Format 1:

let mydata=[{
    "_children": {
        "5": {
            "_children": {
                "7": {
                    "_children": {},
                    "id": "7",
                    "name": "subject11",
                    "parentID": 5
                },
                "10": {
                    "_children": {},
                    "id": "10",
                    "name": "subject12",
                    "parentID": 5
                }
            },
            "id": "5",
            "name": "subject1",
            "parentID": null
        },
        "6": {
            "_children": {
                "8": {
                    "_children": {},
                    "id": "8",
                    "name": "subject21",
                    "parentID": 6
                },
                "9": {
                    "_children": {},
                    "id": "9",
                    "name": "subject22",
                    "parentID": 6
                }
            },
            "id": "6",
            "name": "subject2",
            "parentID": null
        }
    }
}]

Format 2:

let endresult=[
    {"id":7,    "name":"subject11",   "parent":"subject1"},
    {"id":10,   "name":"subject12",   "parent":"subject1"}
    {"id":8,    "name":"subject21",   "parent":"subject2"},
    {"id":9,    "name":"subject22",   "parent":"subject2"},  
]

Do you have any idea?

Javascript audio file only playing for 2 seconds, then cutting off

So basically, I am retreating blobs from an SQL database and decoding them in base64, using the blob as the SRC attribute.
There is a PHP function to retreat a blob, which will later be recalled after the current song ends wrapped in a JavaScript function (so that it will be callable again), and a line of code setting the SRC for the HTML element as the decoded blob.

The problem is that whenever a song is randomly picked, it plays for a moment, then stops. If i set an ONENDED attribute recalling the function, same happens, only times infinite.
NOTE: no console errors!

Here is the code:

function songGenerationJS() {
    let song = document.getElementById("song");

    <?php 
        function generateSong() {
            $conn=mysqli_connect("localhost", "root", "","radio fusionrock");
            $req = $conn->query("SELECT * FROM `tracks` ORDER BY RAND() LIMIT 1");
            $song = mysqli_fetch_assoc($req); 
            $conn->close();                       
        
            return $song;
        }
    $song = generateSong();
?>

song.attributes.src="data:audio/mp3;base64,<?php echo base64_encode($song['Src']);?>"  
song.play();

}

I need to convert JQUERY code to Vanilla JS

I’m a wordpress developer, I know nothing from JS yet. I have found a way to make a marquee loop but I need the code in vanilla JS

this is what I have:

HTML:

<div class="marquee">
  <div class="bar">

    <a href="www.google.com">DIGITAL MARKETING ·</a>
    <a href="www.google.com">BRANDING ·</a>
    <a href="www.google.com">GRAPHIC DESIGN </a>
    <a href="www.google.com">WEBSITE DESIGN + DEVELOPMENT ·</a>
    <a href="www.google.com">SITE MAINTENANCE ·</a>
    <a href="www.google.com">SEO MARKETING ·</a>
    <a href="www.google.com">SOCIAL MEDIA MARKETING ·</a>
    <a href="www.google.com">PHOTOGRAPHY ·</a>
    <a href="www.google.com">DIGITAL MARKETING ·</a>
    <a href="www.google.com">BRANDING ·</a>
    <a href="www.google.com">GRAPHIC DESIGN ·</a>
    <a href="www.google.com">WEBSITE DESIGN + DEVELOPMENT ·</a>
    <a href="www.google.com">SITE MAINTENANCE ·</a>
    <a href="www.google.com">SEO MARKETING ·</a>
    <a href="www.google.com">SOCIAL MEDIA MARKETING ·</a>
    <a href="www.google.com">PHOTOGRAPHY ·</a>
  </div>
</div>

CSS:

.bar a{
  text-decoration: none;
  color: black;
}

.marquee {
  overflow: hidden;
  border: 1px solid #ccc;
  background: #ccc;
}

JQUERY:

$('.marquee').marquee({
    //speed in milliseconds of the marquee
    duration: 15000,
    //gap in pixels between the tickers
    gap: 10,
    //time in milliseconds before the marquee will start animating
    delayBeforeStart: 0,
    //'left' or 'right'
    direction: 'left',
    //true or false - should the marquee be duplicated to show an effect of continues flow
    duplicated: true
});

I tried chatgpt but withouth JS knowledge I don’t find it possible

Exception: Action not allowed

I am trying to create a google apps script mail merge that pulls data from a google sheets to populate fields in a google document. I am receiving the following error:

Exception: action not allowed

I am the owner of all scripts, sheets, and docs involved in this script. I read something about being logged into multiple google accounts causing this issue, but I logged out of my personal google account (this script is with for work account), so that I had only one account active, and the issue persisted.

Here is my code:

function createLetters() {
  //Ids for docs and sheets 
  var docTemplateId = "1PBm3Oghmtf7ZPWolCIY9xGkEyW3l3jR4_3olDDaBvMk";
  var docFinalId = "1fgg_nX-IaN4xOwN7rwey3EX_pGatF136P8GlG0u299w";
  var docFinalId = DocumentApp.create('El Letters').getId();
  var ssID = "1DlWAglK8IJwLtBSH-kUtg3rH6bmuS-MGhl0R7JalM5Q";

  //Get the docs and sheet 
  var docTemplate = DocumentApp.openById(docTemplateId);
  var docFinal = DocumentApp.openById(docFinalId);
  var sheet = SpreadsheetApp.openById(ssID).getSheetByName("ELPA Scores");

  var data = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn()).getValues();
  Logger.log(data)
  var templateParagraphs = docTemplate.getBody().getParagraphs();
  
  docFinal.getBody().clear()

  

   for(var i =0;i < data.length;i++){
    createMailMerge(data[i][0],data[i][1],data[i][2],data[i][3],data[i][4],data[i][5],data[i][6],data[i][7],data[i][8],data[i][9],templateParagraphs,docFinal)
  }
}

function createMailMerge(
  firstname,
  lastname,
  school,
  level,
  r,
  w,
  s,
  l,
  status,
  test_date,
  templateParagraphs,
  docFinal){

    templateParagraphs.forEach(function(p){
      docFinal.getBody().appendParagraph(p.copy()
            .replaceText("{{first_name}}", firstname)
            .replaceText('{{last_name}}', lastname)
            .replaceText("{{school}}", school)
            .replaceText("{{level}}",level)
            .replaceText("{{r}}", r)
            .replaceText("{{w}}", w)
            .replaceText("{{s}}", s)
            .replaceText("{{l}}", l)
            .replaceText("{{status}}",status)
            .replaceText("{{test_date}}", test_date)
            //.replaceText("{{contacted_date}}", contacted_date)
          )
        });

      docFinal.getBody().appendPageBreak()
 
}

This feels like a fairly straightforward script, so I’m not sure why I’m encountering this issue. Do I need to incorporate a way to have it get more permissions?

Problem when clicking on a button or any UI Element in metronic Keenthemes

I’am using Keenthemes metronic demo 1 , when i try to click a button,dropdown or use any other UI element ( with interaction event) it wouldnt work unless i refresh the whole page,
i tried to inspect it , i have seen that when i click no event is triggered , but after i refresh the page and click i saw changes made in code behind.Any help please .
I imported the css,js files like this :
in index.html file i put this
enter image description here

and i put the js files in angular.json file
enter image description here

React-hook-form’s handleSubmit is getting called when uploading file but haven’t clicked submit

I have multiple choices of documents for the user to upload, and other text input fields too. When I upload a file, the onSubmit function in SignUp.tsx is getting called (i can see the log statement is executed in the onSubmit func) , even when I didn’t hit the submit button of the form. I have verified that the files are infact uploading, as they are in the payload as seen from the console statement in the onSubmit function.

SignUp.tsx:

import { useCallback, useState } from 'react';
import { useForm } from 'react-hook-form';
import FormProvider from './hook-form/FormProvider';
import RHFInput from './hook-form/RHFInput';
import DocUpload from './DocUpload';

const Documents = [
    {
        name: 'doc-certificate',
        label: 'Certificate',
    },
    {
        name: 'doc-license',
        label: 'License',
    },
    {
        name: 'doc-examResult',
        label: 'Exam Result',
    },
]

type SelectedFiles = {
    [key: string]: File | null;
};

export default function DriverSignUp() {
    const methods = useForm();
    const { handleSubmit } = methods;

    const [selectedFiles, setSelectedFiles] = useState<SelectedFiles>({});

    const handleFileChange = (name: string, file: File | null) => {
        const newSelectedFiles: SelectedFiles = { ...selectedFiles };

        if (file) {
            newSelectedFiles[name] = file;
        } else {
            delete newSelectedFiles[name];
        }
        setSelectedFiles(newSelectedFiles);
    };


    const onSubmit = (data: any) => {
        const formDataWithFiles = { ...data, ...selectedFiles };
        console.log(formDataWithFiles); // this gets executed when i try to submit files, but haven't hit the submit button yet
    };

    return (
        <FormProvider methods={ methods } onSubmit={ handleSubmit(onSubmit) } className = "grid grid-cols-10 gap-4" >
            {/* Left col */ }
            <div className="col-span-6 p-4" >
                // text inputs for name, email, etc, like
                <RHFInput name="homeAddress" type="text" />

            </div>

            {/* Right col */ }
            <div className="col-span-4 p-4">
                <h2 className="text-2xl font-bold mb-4">Documents</h2>

                <div className="mb-4 flex flex-col gap-2">
                    {Documents.map((doc) => (
                        <DocUpload key={doc.name} name={doc.name} label={doc.label} onFileChange={handleFileChange} />
                    ))}
                </div>
                <button type="submit" className="bg-blue-500 text-white px-4 py-2 rounded">
                    Submit
                </button>
            </div>
        </FormProvider>
    );
};


DocUpload.tsx:

import { useRef, useState, ChangeEvent } from "react";

interface DocUploadProps {
    name: string;
    label: string;
    onFileChange: (name: string, file: File | null) => void;
}

export default function DocUpload({ name, label, onFileChange }: DocUploadProps) {
    const hiddenInputRef = useRef<HTMLInputElement>(null);

    const [file, setFile] = useState<File | null>(null);

    const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
        // const newFile = event.target.files && event.target.files[0];
        const newFile = event.currentTarget.files && event.currentTarget.files[0];

        if (newFile) {
            onFileChange(name, newFile);
            setFile(newFile);
        }
    };

    const onUpload = () => {
        hiddenInputRef.current?.click();
    };

    const onView = () => {
        if (file) {
            const fileURL = URL.createObjectURL(file);
            window.open(fileURL, "_blank");
        }
    };

    const onRemoveFile = () => {
        onFileChange(name, null);
        setFile(null);
    };

    const uploadButtonLabel = file ? `Change ${label}` : label;

    return (
        <div>
            <input
                type="file"
                name={name}
                className="hidden"
                ref={hiddenInputRef}
                onChange={handleFileChange}
            />

            <button className="bg-blue-500 text-white px-4 py-2 rounded" onClick={onUpload}>
                {uploadButtonLabel}
            </button>

            {file && (
                <>
                    <span className="ml-2 cursor-pointer text-blue-500 underline" onClick={onView}>
                        View
                    </span>
                    <span className="ml-2 cursor-pointer text-red-500 underline" onClick={onRemoveFile}>
                        Remove
                    </span>
                </>
            )}
        </div>
    );
};

FormProvider.tsx:

import { FormProvider as Form } from 'react-hook-form';

interface FormProviderProps {
    children: React.ReactNode;
    methods: any;
    onSubmit?: any;
    className?: string;
}

export default function FormProvider({ children, onSubmit, methods, className }: FormProviderProps) {
    return (
        <Form {...methods}>
            <form onSubmit={onSubmit} className={className}>{children}</form>
        </Form>
    );
}

example of how i use the text field RHFInput.tsx:

import { useFormContext, Controller } from 'react-hook-form';
import { InputHTMLAttributes } from 'react';

export interface RHFInputProps extends InputHTMLAttributes<HTMLInputElement> {
    name: string;
}

export default function RHFInput({ name, ...other }: RHFInputProps) {
    const { control } = useFormContext();

    return (
        <Controller
            name={name}
            control={control}
            render={({ field }) => (
                <input
                    {...field}
                    {...other}
                    value={field.value || ''}
                    className={`p-2 border border-gray-300 rounded w-full text-black leading-tight focus:outline-none focus:border-indigo-500 ${other.className}`}
                />
            )}
        />
    );
}

How properly unmount state within ComponentWillUnmount to avoid memory leaks?

I pass a component state as a prop to another component. It is really large.
Do I have to reset the state while parent component unmounted.
Just want to avoid memory leaks

componentDidMount(){
    fetch({ /* ... */ })
      .then(res => res.json())
      .then((responseData) => {
        this.setState({
          result: responseData.meta.data
        })
      })
  }
  
  componentWillUnmount(){
    this.setState({
      result: undefined // IS THAT RIGHT APPROACH?
    })
  }

  render() {
    return (
        <DataComponent data={this.state.result}>

        </DataComponent>
    );
  }