Upload large file by chunks using File reader using Angular

I am trying to upload files and the current code supports file size upto 100MB and if the size of the file increases getting out of Memory screen in browser

private ProcessReadFile(file:File){
   return new Promise<void>(resolve=>{
        const reader= new FileReader();
        let content:any;
        reader.onloadend=()=>{
                     content=reader.result;
                     var fileContent=content.split('base64,')[1];
                    this.fileUpload.push({
                       Filecontent:fileContent;
                       FileType:file.Type
                     });
                 resolve;
         };
     reader.readAsDataUrl(file);
     });
  }

I came across some solutions where they are slicing the file into chunks and processing. I am not able to understand and achieve with the above method.

Can some one please suggest/help me to upload large data files.

Firebase React returns undefined on firebase.currentUser.displayName after refreshing page

I’m creating a new account in Signup.tsx and redirecting to the dashboard after success, this way

try {
            await auth.createUserWithEmailAndPassword(
              emailRef.current!.value,
              passwordRef.current!.value,
            );
            const user = firebase.auth().currentUser;
            await user?.updateProfile({
              displayName: nameRef.current?.value
            })
             navigate('/dashboard')
          } catch (error) {
            console.error(error);
          }
        }

And google auth is managed this way, googleAuth.tsx

import { auth, provider } from "../../../firebaseSetup";
import { NavigateFunction, useNavigate } from "react-router-dom"


const GoogleAuth = async(navigate: NavigateFunction) => {
    auth.signInWithPopup(provider).then(() => {
      if (auth.currentUser?.metadata?.creationTime !== auth.currentUser?.metadata?.lastSignInTime)
          {
            navigate('/dashboard');
          }
          else{
            navigate('/welcome')
          }
    }).catch((error) => {
      console.log(error.message)
    })
}
export default GoogleAuth

And in my dashboard’s navbar, I’m displaying the current user’s display name and profile pic if logged in via google this way
sidebar.tsx

import { auth } from "../../firebaseSetup";

export default sidebar(){
   const pic = auth.currentUser?.photoURL
   return(
      <Text>{auth.currentUser?.displayName}</Text>
      <Avatar size={'sm'} src={pic}/>
    )
}

All this works perfectly fine when users sign-in/up for the first time i.e that is when they are redirected from the landing page, but if the user refreshes or moves to another route, both text and avatar go blank.
I tried printing using

console.log(auth.currentUser?.displayName)

It returns the correct name the first time, but on refreshing it prints undefined.
I looked up and figured I need to be using useState and useEffect to manage current users, which I tried and failed. Can anyone tell me how do I retain the users name even on refreshing

Usng Metamask but get Error: Returned error: The method eth_sendTransaction does not exist/is not available

I want to call a payable function in a smart contract I deployed, but it does not work. This is the error I am getting:

Error: Returned error: The method eth_sendTransaction does not exist/is not available

The answer I could find is to just use a private key, because infura does not cater this method, however I want the user to sign the transaction to the smart contract with MetaMask.

This is my code:

export async function helloworld() {
  const rpcURL =
    "https://ropsten.infura.io/v3/KEY";
  const web3 = new Web3(rpcURL);
  let provider = window.ethereum;

  if (typeof provider !== "undefined") {
    provider
      .request({ method: "eth_requestAccounts" })
      .then((accounts) => {
        selectedAccount = accounts[0];
        console.log(`Selected account is ${selectedAccount}`);
      })
      .catch((err) => {
        console.log(err);
        return;
      });

    window.ethereum.on("accountsChanged", function (accounts) {
      selectedAccount = accounts[0];
      console.log(`Selected account changed to ${selectedAccount}`);
    });
  }

  const networkId = await web3.eth.net.getId();

  const thecontract = new web3.eth.Contract(
    simpleContractAbi,
    "0x50A404efF9A057900f87ad0E0dEfA0D485931464"
  );
  isInitialized = true;

  investit(thecontract, selectedAccount);
}

and this is the code that actually throws the error:

export const investit = async (thecontract, selectedAccount) => {
  if (!isInitialized) {
    await helloworld();
  }

  thecontract.methods
    .invest()
    .send({ from: selectedAccount, value: 10000 })
    .catch(function (err) {
      console.log(err);
    });
};

I am completely lost, since if I use the normal window.ethereum.request (https://docs.metamask.io/guide/sending-transactions.html#example) to send a transaction, metamask opens up and I can sign it. With the contract call it simply does not work.

Do you know the reason? How can I fix this?

Cheers!

Why am i getting this error “react Invalid hook call. Hooks can only be called inside of the body of a function component” in the following code?

import React,{ useEffect, useState} from 'react';
import { useLocation } from 'react-router-dom';
import ReactPlayer from 'react-player';

import { useResultContext } from '../contexts/ResultContextProvider';
import { Loading } from './Loading';

export const Results = () => {
  const {getResults, results, isLoading, searchTerm} = useResultContext();
  const location = useLocation();
  const [num, setNum] = useState(10);

  const changeNum=()=>{
    setNum(num+10);
    console.log(num)
    Results();
}

  useEffect(()=>{
    if(searchTerm){
    if (location.pathname ==='/videos') {
      getResults(`/search/q=${searchTerm} videos&num=${num}`)
    }else{
      getResults(`${location.pathname}/q=${searchTerm}&num=${num}`)
    }
  }
  },[location.pathname, searchTerm, num, getResults]);


  if (isLoading) return <Loading/>;

  switch (location.pathname) {
    case '/search':
      return (<><div className='flex flex-wrap justify-between space-y-6 sm:px-56 overflow-hidden pb-4 '>
        {
          results?.results?.map(({link, title, description}, index)=>(
            <div key={index} className='md:w-3/5 w-full'>
              <a href={link} target="_blank" rel="noreferrer">
                <p className='text-sm text-green-700'>
                  {link.length>50? link.substring(0,50): link}
                </p>
                <p className='text-lg hover:underline dark:text-blue-300 text-blue-700'>
                  {title}
                </p>
              </a>
              {description.length>15?
                <p>
                  {description}
                </p>:''}
            </div>
          ))
        }
      </div>
      <div onClick={changeNum} className='absolute bg-gray-200 border border-gray-400 py-3 px-10 rounded-full -mt-5 left-96 cursor-pointer active:bg-gray-300 dark:bg-gray-700 '>
        More Results
      </div>
      </>)
    case '/images':
      return (<>
      <div className='flex flex-wrap justify-center items-center '>
          {results?.image_results?.map(({image, link}, index)=>(
          <a className='sm:p-3 p-5' href={link.href} key={index} target='_blank' rel='noreferrer'>
                <img className='w-64' src={image.src} alt={link.title} loading='lazy' />
                <p className=' w-full break-words text-sm mt-2'>
                  {link.title.substring(0,40)}
                </p>
              </a>))}
        </div>
        <div onClick={changeNum} className='absolute bg-gray-200 border border-gray-400 py-3 px-10 rounded-full -mt-5 left-96 cursor-pointer active:bg-gray-300 dark:bg-gray-700 '>
        More Results
      </div>
        </>);
    case '/videos':
      return (
        <div className='flex flex-wrap justify-center'>
          {results?.results?.map(({additional_links}, index)=>(
            <div key={index} className='m-2'>
              {additional_links?.[0]?.href && <ReactPlayer url={additional_links?.[0]?.href} config={{ youtube: { playerVars: { origin: 'https://www.youtube.com' }}}} controls width='355px' height='200px'/>}
            </div>
          ))}
        </div>
      );
    case '/news':
      return (<div className='flex flex-wrap justify-between space-y-6 sm:px-56 overflow-hidden '>
      {
        results?.entries?.map(({link,id, title})=>(
          <div key={id} className='md:w-3/5 w-full'>
            <a href={link} target="_blank" rel="noreferrer" className='hover:text-underline'>
              <p className='text-sm text-green-700'>
                {link.length>40? link.substring(0,40): link}
              </p>
              <p className='text-lg hover:underline dark:text-blue-300 text-blue-700'>
                {title}
              </p>
            </a>
          </div>
        ))
      }
    </div>);
    default: return 'ERROR';
  }
  
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I’ve started learning react and it’s been two days i have been unable to get around this.

I’m trying to make google search engine clone and in this project i’m getting results using google search api and displaying 10 results at first and want then to increase by 10 every time when i click on ‘More Results’ button which calls ‘changeNum’ function which uses ‘setNum’ to add 10 value to ‘num’ every time function is called by clicking on button.

Using Axios and Pokemon API to display more than one Pokemon of same type

so I’m trying to randomly generate a Pokemon and then five more Pokemon of the same type to display on a web page. So far, this is what I have:

const pokemonName = document.querySelector(".pokemon-name");
const pokemonImage = document.querySelector(".pokemon-image");

function getPokemon() {
  const pokemonArr = []
  const random = Math.floor(Math.random() * 256 + 1)
  axios.get("https://pokeapi.co/api/v2/pokemon/1" + random)
  .then(function (response) {
    pokemonName.innerHTML = response.data.forms[0].name;
    pokemonImage.src = response.data.sprites.front_default;
    pokemonArr.push(pokemonName.innerHTML)
  })
  .catch(function (error) {
    pokemonName.innerHTML = "An error has occurred.";
    pokemonImage.src = "";
  });
}

I’ve managed to display a Pokemon although it’s still finnicky. My thought process was to append the name and image to an array or object but I’m having issues trying to apply that logic. This is my first time being introduced to the concept of APIs and using Axios. Would I be able to use a loop? How do I even go about comparing the types of Pokemon in the API?

Pokemon API: https://pokeapi.co/

Apexcharts Heatmap: display exact x value on hover for each series data

I’m trying to create a heatmap using apexcharts that shows frequency of activites each week in a year (Check the github contributions heatmap). My goal is to display a tooltip that shows the specific date, week day, and frequency value whenever the user hovers on a cell. Example:

 ------------
| 2022-02-20 |
| ---------- |
| Sunday: 40 |
 ------------

This is what I have attempted so far:

var options = {
    series: [],
    chart: {
      height: 350,
      type: 'heatmap',
    },
    dataLabels: {
      enabled: true
    },
    xaxis: {
      labels: {
        show: false
      },
      tooltip: {
        enabled: false,
      },
    },
    tooltip: {
      shared: false,
      followCursor: true,
      intersect: false,
      x: {
        show: true,
        format: 'dd MMM'
      },
    }
};

Here is a simplified sample series:

var series = [
    {
    name: 'Sunday',
    data: [{
        x: '2022-02-20',
        y: 40
        }]
    },
    {
    name: 'Monday',
    data: [{
        x: '2022-02-21',
        y: 0
        }]
    },
    {
    name: 'Tuesday',
    data: [{
        x: '2022-02-22',
        y: 5
        }]
    },
    {
    name: 'Wednesday',
    data: [{
        x: '2022-02-23',
        y: 100
        }]
    },
    {
      name: 'Thursday',
      data: [{
        x: '2022-02-24',
        y: 17
      }]
    },
    {
      name: 'Friday',
      data: [{
        x: '2022-02-25',
        y: 4
      }]
    },
    {
      name: 'Saturday',
      data: [{
        x: '2022-02-26',
        y: 90
      }]
    },
];
options.series = series;

What happens here is that the apexcharts displays a heatmap for the week of 2022-02-20 (Sunday) to 2022-02-26 (Saturday) vertically from bottom to top (it seems it displays in reverse order). If the user hovers to the Sunday cell it displays the exact tooltip that I provided at the beginning with the values 2022-02-20, Sunday, and 40. However, when the user hovers on cells Monday – Saturday, the tooltip displays the correct values except for the x value. It still displays 2022-02-20.

From what I understand, the chart treats the first x value in a column as the column’s category. This means regardless on whether the user hovers to Saturday, or Friday, it will display the Sunday’s x value. What can I do to display the actual x value of the hovered cell?

why users and newUser are not equal? [duplicate]

const users = [
    {name:'John',age:24},
    {name:'Victor',age:28}
];

const newUser = JSON.parse(JSON.stringify(users));
console.log(users);
console.log(newUser);
console.log(typeof(users));
console.log(typeof(newUser));
console.log(users==newUser)

OUTPUT:

[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
object
object
false

object users and newUser have exactly same items and values.
They why users==newUser is false?

Looping through Nested json object with unwanted characters

Below is a fraction of what I exported from WordPress database as .json file, I want to be able to iterate over the whole data with special attention to statutory_fees.
In a nutshell, I want to be able to access st_type: Land Survey, meanwhile, the I can currently access pid: 25

const data = [
  {
    "pid": "25",
    "plotstatus": "Completed",

    "statutory_fees": "[{"st_type":"Land Survey Plan","landsurveyplanamount":"150000","landsurveyplanamountpaid":"0","landsurveyplanfeebalance":"150000","landsurveyplanfeestatus":"Not Completed"},{"st_type":"Legal Fee","legalfeeamount":"50000","legalfeeamountpaid":"0","legalfeefeebalance":"50000","legalfeefeestatus":"Not Completed"},{"st_type":"Development\/Electrification Fee","development\/electrificationfeeamount":"200000","development\/electrificationfeeamountpaid":"0","development\/electrificationfeefeebalance":"200000","development\/electrificationfeefeestatus":"Not Completed"},{"st_type":"Registration Form Fee","registrationformfeeamount":"2000","registrationformfeeamountpaid":"0","registrationformfeefeebalance":"2000","registrationformfeefeestatus":"Not Completed"}]",

    "contract_of_sale": "Not Collected",
    "deed_of_assignmen": "Not Collected",
},
{
    "pid": "25",
    "plotstatus": "Completed",

    "statutory_fees": "[{"st_type":"Land Survey Plan","landsurveyplanamount":"150000","landsurveyplanamountpaid":"150000","landsurveyplanfeebalance":"0","landsurveyplanfeestatus":"Completed"},{"st_type":"Legal Fee","legalfeeamount":"50000","legalfeeamountpaid":"50000","legalfeefeebalance":"0","legalfeefeestatus":"Completed"},{"st_type":"Development\/Electrification Fee","development\/electrificationfeeamount":"300000","development\/electrificationfeeamountpaid":"0","development\/electrificationfeefeebalance":"300000","development\/electrificationfeefeestatus":"Not Completed"},{"st_type":"Registration Form Fee","registrationformfeeamount":"2000","registrationformfeeamountpaid":"0","registrationformfeefeebalance":"2000","registrationformfeefeestatus":"Not Completed"}]",


    "contract_of_sale": "Not Collected",
    "deed_of_assignmen": "Not Collected",
    
}
]

I have tried the following ways:

 let purfi = []
  data.forEach(elem => {
        JSON.stringify(elem.statutory_fees).replace(/\/g, '')
        purfi.push(elem)
    })

let veri = []
purfi.forEach(a=>{
    JSON.parse(a.statutory_fees)
    veri.push(a)
})

veri.forEach(a=>{
  console.log(a.statutory_fees[0].st_type // undefined
})


Any help will go a long way.

Getting “Uncaught (in promise) SyntaxError: Unexpected token I in JSON at position 0” error when executing delete request


//Route 4 : Delete an existing note using DELETE "api/notes/deletenote". Login required
router.delete("/deletenote/:id", fetchuser, async (req, res) => {
  try {
    //find the note to be updated and update it
    let note = await Note.findById(req.params.id); //find note by id
    if (!note) {
      return res.status(404).send("Note Not found");
    } //If note is not found

    //allow deletion only if the user own the note

    if (note.user.toString() !== req.user.id) {
      return res.status(401).send("Not allowed");
    }      

    note = await Note.findByIdAndDelete(req.params.id, function (err, docs) { 
      if (err){ 
          console.log(err) 
      } 
      else{ 
          console.log("Deleted : ", docs); 
      } 
  });
    res.json({ Success: "Note has been deleted", note: note });
  } catch (error) {
    console.log(error.meassage);
    res.status(500).send("Internal server error");
  }
});

This is the code for the delete request in my backend and I am getting Uncaught (in promise) SyntaxError: Unexpected token I in JSON at position 0 error in my console and when I tested the request in thunderclient, its not working.

Please help me to resolve this problem.

Are MobX actions allowed to show a confirm dialog, or navigate to a new screen? More generally, can actions touch ui?

I am refactoring MobX in large-scale applications. Since it is big, making the code clean is very important.

There is an action that does the following (simplified):

@action myAction() {
  var data = await api.getSomeDataFromServer();
  
  if (data.warnUser) {
    var userAgrees = await showConfirmDialog('Hey, are you really sure?'); // #1
    if (!userAgrees) return;
  }

  someOperations(data);

  Navigator.push('/another_page'); // #2
}

I am worried whether the #1 and #2 are OK or not. The reason is that, IMHO mobx has a UI - action - state triad (as is seen in the figure below by the mobx book). Thus, Actions should modify the State instead of the UI directly. But in #1, the Action directly shows a dialog – which is UI; in #2, the Action directly navigates to another page – which is also UI related.

In short, can MobX’s actions directly “touch” and manipulate the uis?

I have made some searches about this and is quite confused now. Thanks for any suggestions!

Remark: I tag it as both Flutter and JavaScript, because indeed I am using Flutter but this question applies to the JS version of MobX as well.

Remark: Following is the diagram from the mobx book.

enter image description here

Re-enter fullscreen mode after a JavaScript alert call

I have this web page that is already in fullscreen mode. Now, when testing with Google Chrome, if I make a call to the alert function, the page would quit fullscreen mode.

While I understand that this might be standard behavior, I would still like to make the page re-enter fullscreen mode after quitting it. I now have this function:

function enterFullScreen() {
    let element = document.documentElement;
    if (element.requestFullscreen) {
        element.requestFullscreen();
    }
    else if (element["mozRequestFullScreen"]) {
        element["mozRequestFullScreen"]();
    }
    else if (element["webkitRequestFullscreen"]) {
        element["webkitRequestFullscreen"]();
    }
    else if (element["msRequestFullscreen"]) {
        element["msRequestFullscreen"]();
    }
}

It works fine when I run it directly in the console, but when I put it after the alert call, believing it would make the page re-enter fullscreen mode, it ceases to work:

elem.onclick = function () {
    alert("something");
    enterFullScreen(); // Nothing happens what-so-ever. No errors either.
}

What might be the problem to this?

Create html DOM element using object in javascript without jQuery

I’m wondering if there is an “easy” way to create a big DOM object by specifying the attributes in a json?

I know it’s possible to do this with appendChild and/or innerHTML, but for this object in question, it looks quite messy.

The goal is to create this HTML object from the bottom up in javascript:

<div className="p-2">
    <div className="d-flex p-2 bg-dark2-35">
        <div className="Popover h-3">
            <div className="pfp" style="background-image: url('/data/images/PP/1.png')"></div>
        </div>
        <div className="d-grid ms-2 w-100">
            <p><b className="lead text-blue">Username</b> — <i>2020-01-16 19:29:34</i></p>
            <p className="text-white">some comment text</p>
        </div>
    </div>
</div>

I was wondering if it’s possible to do something like this (I know it doesn’t work):

let comment = document.getElementById("comment-section");
let elm = {
    className: "p-2",
    appendChild(node) {
        classList.add("d-flex", "p-2", "bg-dark2-35"),
        appendChild(node2){
            classList.add("Popover", "h-3"),
            // ... and so on
        }
    }
}
comment.appendChild(elm);

Is there an easy way to do this in pure JS? Would I have to make a function to achieve this? or maybe go as far as to import a library?

The question is a bit similar to Create DOM element from Object in javascript, but I’m completely lost when it comes to this many childrens, with childrens and so on

I’m a bit of a newbie when it comes to JavaScript. The question might come off as strange

Using typeof in conditionals is returning the wrong value [duplicate]

I am not well versed in JS at all and am getting ready to pull my hair out regarding this issue. The issue at high level: I have to grab all values from a dropdown and randomly pick one of them to enter in a dropdown field. Then I have to verify if the field value that got saved is the same as the one I entered.

Three values are possible: “True”, “False”, or “None Available”. Where “None” also gets saved as “False” after the fact. Therefore, when the field is saved, only two values are displayed: “True” or “False”.

I have the setup as following:

        let dropdownVal = ["True", "False", "None Available"];
        let randomVal = dropdownVal[Math.floor(Math.random() * dropdownVal.length)];

        //I enter the value resulting from randomVal into the dropdown field using xpath.

        let evalDropdownVal = (typeof randomVal == 'None Available') || (typeof randomVal == 'False') ? "False" : "True"

        //Here I grab the xpath for the "saved" field and evaluate whether the values match.

What keeps happening is, the evalDropdownVal keeps evaluating the opposite. I.e if the value is True, it evaluates it as False and my final matching keeps failing due to that.

I apologize in advance if I butchered the format of the question or didn’t give enough information.

Getting all classes from one element and adding them to another element in vanilla JavaScript

I’m trying to get all classes from one element, then add them to another element created dynamically. I was originally stuck on how to do this, but as I was typing out this question, I worked out a solution. However, it seems a bit verbose. Is there a way to do this same thing more efficiently, i.e. with fewer lines of code?

    let classes = this.nextElementSibling.classList;      // get classes from target element
    classes += '';                                        // convert classlist object to string
    let class_array = classes.split(' ');                 // convert string to array
    const my_div = document.createElement('div');         // create a new div
    for(i=0; i<class_array.length; i++) {                 // loop through array and add classes to the div
      my_div.classList.add(class_array[i]);
    }

Thanks in advance.