Why does setInterval not prevent stack overflow

I have this piece of code in javascript which I believe should not lead to stack overflow but it does, because in setInterval, I introduce a statement to stop infinite recursion of another function

let setval = false;
let ctr = 0;

let f = function() {
    ctr++;
    if (setval == true) {
        return;
    }
    else {
        f();
    }
}
setTimeout(() => {
    setval = true;
}, 1);
f();

why does it behave this way? In 1 ms surely there cannot be 13985 calls to f(), which is the value of ctr.

How to make my content movable according to the Material UI drawer?

I want to move the content from Form.jsx according to the direction in which the drawer will move. When I click on the menu icon, the Drawer will be expanded but the content inside the body cannot be moved according to the drawer. How to make it enable here?

Before the drawer menu gets clicked:

enter image description here

After the drawer menu gets clicked:

enter image description here

Code is below:

Form.jsx

import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';

const DrawerHeader = styled('div')(({ theme }) => ({
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: theme.spacing(0, 1),
    ...theme.mixins.toolbar,
}));

export default function Form() {

    return (
        <Box component="main" sx={{ flexGrow: 1, p: 9 }}>
            <DrawerHeader />
            <TextField id="outlined-basic" label="Outlined" variant="outlined" />
            <TextField id="filled-basic" label="Filled" variant="filled" />
            <TextField id="standard-basic" label="Standard" variant="standard" />
        </Box>
    );
};

Drawer.jsx

import * as React from 'react';
import { styled, createTheme, ThemeProvider } from '@mui/material/styles';
import Box from '@mui/material/Box';
import MuiDrawer from '@mui/material/Drawer';
import MuiAppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import List from '@mui/material/List';
import CssBaseline from '@mui/material/CssBaseline';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import InboxIcon from '@mui/icons-material/MoveToInbox';
import MailIcon from '@mui/icons-material/Mail';
import { Link } from 'react-router-dom';

const drawerWidth = 240;

const openedMixin = (theme) => ({
  width: drawerWidth,
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.enteringScreen,
  }),
  overflowX: 'hidden',
});

const closedMixin = (theme) => ({
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  overflowX: 'hidden',
  width: `calc(${theme.spacing(7)} + 1px)`,
  [theme.breakpoints.up('sm')]: {
    width: `calc(${theme.spacing(8)} + 1px)`,
  },
});

const DrawerHeader = styled('div')(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'flex-end',
  padding: theme.spacing(0, 1),
  // necessary for content to be below app bar
  ...theme.mixins.toolbar,
}));

const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== 'open',
})(({ theme, open }) => ({
  zIndex: theme.zIndex.drawer + 1,
  background: "fb8500",
  transition: theme.transitions.create(['width', 'margin'], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  ...(open && {
    marginLeft: drawerWidth,
    width: `calc(100% - ${drawerWidth}px)`,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
  }),
}));

const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })(
  ({ theme, open }) => ({
    width: drawerWidth,
    flexShrink: 0,
    whiteSpace: 'nowrap',
    boxSizing: 'border-box',
    ...(open && {
      ...openedMixin(theme),
      '& .MuiDrawer-paper': openedMixin(theme),
    }),
    ...(!open && {
      ...closedMixin(theme),
      '& .MuiDrawer-paper': closedMixin(theme),
    }),
  }),
);

export default function MiniDrawer() {

  const PageList = [
    {
      id: 1,
      text: "Add new Donee",
      to: "/form",
    },
    {
      id: 2,
      text: "Donees",
      to: "/view",
    },
  ];

  // const theme = useTheme();
  const theme = createTheme({
    palette: {
      primary: {
        // Purple and green play nicely together.
        main: '#ffca3a',
      },
      secondary: {
        // This is green.A700 as hex.
        main: '#11cb5f',
      },
    },
  });

  const [open, setOpen] = React.useState(false);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  return (
    <ThemeProvider theme={theme}>
      <Box sx={{ display: 'flex' }}>
        <CssBaseline />
        <AppBar position="fixed" open={open}>
          <Toolbar>
            <IconButton
              color="inherit"
              aria-label="open drawer"
              onClick={handleDrawerOpen}
              edge="start"
              sx={{
                marginRight: 5,
                ...(open && { display: 'none' }),
              }}
            >
              <MenuIcon />
            </IconButton>
            <Typography variant="h6" noWrap component="div">
              Compassion Lanka Data Entry
            </Typography>
          </Toolbar>
        </AppBar>
        <Drawer variant="permanent" open={open}>
          <DrawerHeader>
            <IconButton onClick={handleDrawerClose}>
              {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
            </IconButton>
          </DrawerHeader>
          <Divider />
          <List>
            {PageList.map((text, index) => (
              <ListItem key={text.id} disablePadding sx={{ display: 'block' }}>
                <ListItemButton
                  sx={{
                    minHeight: 48,
                    justifyContent: open ? 'initial' : 'center',
                    px: 2.5,
                  }}
                  component={Link} to={text.to}
                >
                  <ListItemIcon
                    sx={{
                      minWidth: 0,
                      mr: open ? 3 : 'auto',
                      justifyContent: 'center',
                    }}
                  >
                    {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
                  </ListItemIcon>
                  <ListItemText primary={text.text} sx={{ opacity: open ? 1 : 0 }} />
                </ListItemButton>
              </ListItem>
            ))}
          </List>
          <Divider />
        </Drawer>
      </Box>
    </ThemeProvider>
  );
}

Accessing HTML Element after Adding with innerHtml

I am adding the data received as a result of a request to my page as follows.

showMovieInfo(movies) {
    this.tableDiv.innerHTML = "";

    movies.forEach(movie => {
        this.tableDiv.innerHTML += 
        `
        <table class="table align-middle mb-0 bg-white">
        <thead class="bg-light">
            <tr>
                <th>Movie Name</th>
                <th>Position</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <div class="d-flex align-items-center">
                        <img src="${movie.image}"
                            alt="" style="width: 120px; height: 120px" class="rounded-circle" />
                        <div class="ms-3">
                            <p class="fw-bold mb-1">${movie.title}</p>
                            <p class="text-muted mb-0">${movie.description}</p>
                        </div>
                    </div>
                </td>

                <td>
                    <button  type="button" id="showonmap" class="btn btn-link btn-sm btn-rounded">
                        Show on map
                    </button>
                </td>
            </tr>
        </tbody>
        </table>`

    });
}

then i want to add addEventListener to buttons with id=”showonmap”.But I am getting an error and when I click the buttons, any function does not work.

How to get innertext of heading on grid card click?

Please help me to get innerText of heading from grid card.

CSS File ;

.container1 {
  display: grid;
  grid-template-columns: auto auto auto auto;
  column-gap: 10px;
  justify-content: space-evenly;
}
.posts {
  width: 13rem;
  margin: 10px auto 10px auto;
  height: 17rem;
  background: white;
  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
  border-radius: 10px;
}
<div class="container1">
  <div class="posts">
    <h3>Heading 1</h3>
  </div>
  <div class="posts">
    <h3>Heading 2</h3>
  </div>
  <div class="posts">
    <h3>Heading 3</h3>
  </div>
  <div class="posts">
    <h3>Heading 4</h3>
  </div>
  <div class="posts">
    <h3>Heading 5</h3>
  </div>
  <div class="posts">
    <h3>Heading 6</h3>
  </div>
</div>

How can I get innerText of heading if I click on grid3 and so on through Javascript ?

Accessing PHP file in Vue3

The idea is to submit data to be store in my phpMyAdmin, but it doesn’t work. I am new using Vue3 CLI and I have been trying everything, but I can’t find the solution. I have installed jQuery and put it in the main.js as:

window.$ = window.jQuery = require('jquery');

I also trying to configure vue.config.js:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true
}), {
  devServer: {
    proxy: {
      '^/api/': {
        target: 'http://localhost:3000',
        changeOrigin: true, // so CORS doesn't bite us. 
      }
    }
  }
}

but it is not working.

This is the code that I am using:

<script>
// import data from "";

export default {
    name: 'SingupComp',
    data: function() {
    return {
      email: '',
      password: '',
      cp: '',
      type: '',
      msg: '',
      statusVal: '',
      statusText: '',
      headers: '',
      savingSuccessful: false
    }
  },
  methods: {

    postData: function(email, password) {
      //define url for api
      var postSQLApiURL = '../resources/apis.php/'

      var self = this;
      // POST request using fetch with error handling
      const requestOptions = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username:email,
          password:password
        })
      };

        fetch(postSQLApiURL, requestOptions)
        .then( response =>{
        //turning the response into the usable data
        return response.json( );})
        .then(data =>{
            //This is the data you wanted to get from url
         // Trying to avoid error when usin npm run server
        console.log(data);
        self.msg = "Data Inserted Successfully."  ;
        })
        .catch(error => {
        self.msg = 'There was an error!' + error;
        }); 
        
    }

  }
}

</script>

The php file is store in src/resources/apis.php

It sends me this error:

POST http://localhost:8080/resources/apis.php/ 404 (Not Found)
postData    @   Singup.vue?5cf3:73
onClick._cache.<computed>._cache.<computed> @   Singup.vue?5cf3:23
callWithErrorHandling   @   runtime-core.esm-bundler.js?d2dd:155
callWithAsyncErrorHandling  @   runtime-core.esm-bundler.js?d2dd:164
invoker

This is the line 73 in Singup.vue (the whole code is above):

fetch(postSQLApiURL, requestOptions)

Thanks in advanced.

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘address’)

I am getting an error on my component. Can someone help to solve this?
I’m work in vue 3 version.
Getting an error:
“Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘address’)”
Does anyone have any insights?
profile.vue

<template>
<div>
         <div class="col col-lg-12 col-xl-12" v-for="(_postData, index) in postData" v- 
         bind:key="index">

             <h1>{{ _postData.id.address }}</h1>

         </div>
</div>
</template>

script

data() {
    return {
      postData: {},
      postPagination: {
        filter_data: [],
        page_no: 1,
        limit: 5
      }
    }
  },
getPost() {
      try {
        CreatorService.getAllMedia(this.postPagination)
          .then((response) => {
            if (response.status === true) {
              this.postData = response.data
            }
          })
          .catch((error) => {
            this.isPostLoading = false
            this.errorLog(error)
          })
      } catch (e) {
        this.errorTryLog(e)
      }
    }

response

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }  
]

Error Image
enter image description here

How does Vue.js know when the event is triggered at js file?

I’m trying to implement Wallet Connect to our project(Vue.js), form here: https://docs.walletconnect.com/quick-start/dapps/web3-provider

I implement a UI, when the user clicks the image(walletconnect.svg) and scan it, the event(accountsChanged) will detect it, and return the account, and vue.js will receive the response and store it to vuex.

But how do I detect the event(disconnect)? because this action may happen when the user clicks disconnect in another app, not on our website. So how does Vue.js know when the event(disconnect) is triggered?

Vue.js

<template>
    <v-list>
        <v-list-item
            @click="connect"
        >
        <v-list-item-avatar tile>
            <v-img :src="require('@/assets/walletconnect.svg')" />
        </v-list-item-avatar>
        </v-list-item>
    </v-list>
</template>

<script>
  export default {
    methods: {
      async connect () {
        const accounts = await this.$api.walletConnect.connectWalletConnect()
        // dispatch to vuex
      },
    },
  }
</script>

JS file

import Web3 from 'web3'
import WalletConnectProvider from '@walletconnect/web3-provider'

let web3 = null
let provider = null
let account

const initWeb3 = (provider) => {
  try {
    web3 = new Web3(provider)
  } catch (e) {
    console.error(e)
  }
}

export default () => ({
  async connectWalletConnect () {
    provider = new WalletConnectProvider({
      infuraId: 'xxxxxxxxxxxxxxxxxxxx',
    })

    // Subscribe to accounts change
    provider.on('accountsChanged', (accounts) => {
      account = accounts[0]
    })

    // Subscribe to session disconnection
    provider.on('disconnect', (code, reason) => {
      // How does Vue.js know when the event(disconnect) is triggered?
    })

    await provider.enable()
    initWeb3(provider)
    return account
  },
})

I’m following a tutorial and get an uncaught Syntax error in promise while the code in the video works just fine, Please look into it

I’m a learner on currently following a YouTube tutorial on JS, And the below code worked fine in the video, but I get an error message

error:
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Console log shows the line which has the code console.log("finished!"); as the line with the error

The JS code:

  const requestObj = {
    firstName: "Humaid",
    lastName: "Ahamed",
    categories: ["nerdy"],
  };
  return requestObj;
};

const buildRequestUrl = (requestData) => {
  `http://api.icndb.com/jokes/random?firstName=${requestData.firstName}&lastName=${requestData.lastName}&limitTo=${requestData.categories}`;
};

const requestJokeAnotherMethod = async (url) => {
  const Response = await fetch(url);
  const jsonResponse = await Response.json();
  const joke = jsonResponse.value.joke;
  postJokeToPage(joke);
};

const postJokeToPage = (joke) => {
  console.log(joke);
};

const processJokeRequest = async () => {
  const requestData = getDataFromForm();
  const requestUrl = buildRequestUrl(requestData);
  await requestJokeAnotherMethod(requestUrl);
  console.log("finished!");
};

processJokeRequest();```

Thanks in Advance

node-postgres current_date gives me yesterday as current date

I am using the npm library pg to print the current date, however it gives the date of yesterday with the time set to 21:00:00.000Z.


const { Client } = require('pg')
const client = new Client();
(async function fn() {
    await client.connect();
    const res = await client.query("SELECT current_date");
    const rows = res.rows;
    /** @type { Date } */
    const dt = rows[0]['current_date'];
    console.log(dt); // 2022-06-04T21:00:00.000Z
    await client.end();
})();

When I issue the command from psql I get the correct current date (“2022-06-05”).

SELECT current_date;

My timezone is UTC+03 so I am guessing it has to do with why I am getting this kind of date, but beyond that I dont know.

Kindly help explain.

What is the Reason You Should Choose NestJS as Your Backend Framework?

NestJS is a much better choice than ExpressJS when starting a new Node.js project because it is based on a clear architecture with a few simple components (controllers, modules and providers). This makes it simple to divide applications into microservices.
NestJS is designed to enable the development of scalable, testable, and loosely coupled applications. It is compatible with PostgreSQL, MongoDB, and MySQL databases. NestJS comes pre-configured with dependency injection.
NestJS is fully-featured and flexible thanks to its growing ecosystem and progressive, providing functionality that includes JS features and design patterns. There are loads of examples, recipes, and code sources to be found in the NestJS documentation.
Developers who choose to use NestJS are already ahead of the game. The only thing you need to get started is to create a new app and you are ready to begin development. This framework gives you a major advantage early on, and also helps you progress further by properly structuring your app.

The NestJS applications are maintainable and long-lasting because they use modern solutions and technologies. GraphQL, WebSockets, and microservices.

How do I render the response data from axios in Reactjs

I am using axios to get data from a url. I am then storing the fetched data in post using setPost(). Once the data is stored in post, I am then decoding the data using a function getData() which further assigns the decoded data to metar using setMetar(). The user enters data in an input and clicks on the submit button to get the decoded data. The problem is that it takes 2 clicks to get the decoded data instead of 1. Here’s my code:

import React, { useState, useEffect, useReducer, useCallback } from "react";
import "./Search.css";
import axios from "axios";
import parseMETAR from "metar";

let dataList = "";

const Search = () => {
  const [post, setPost] = useState(null);
  
  const [icao, setIcao] = useState("");
  const [metar, setMetar] = useState("");
  

  useEffect(() => {
    getData(icao);
  }, []);

  const getData = (code) => {
    try {
      console.log(code);
      const url = `Some url`;
      console.log(url);
      axios.get(url).then((response) => {
        setPost(response.data);  
        getMetar();
      });
      
    } catch (err) {
      console.log(err);
    }
  };


  const getMetar = () => {
    // decode the raw text
    setMetar(mtr);
  };

  const handleInputChange = (e) => {
    setIcao(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    getData(icao);
  };

  return (
    <div className="search-div">
      <h2>Search METAR</h2>
      <form>
        <input
          type="text"
          placeholder="Enter ICAO"
          onChange={(e) => handleInputChange(e)}
        />
        <button onClick={(e) => handleSubmit(e)}>Get Metar</button>
      </form>

      <h3>METAR: {metar.length > 0 && metar}</h3>
    </div>
  );
};

export default Search;

As soon as the button is clicked, the console shows the correct data stored in the icao. But, metar‘s value is not rendered. How do I wait for axios to get the fetched data? If this is not a problem, how do I force the Search component to re render after the update functions of each useState variables?

How to toggle series of an apex chart from a component but the chart is in another component?

I’m working with Apexchart. I’m having 2 components. The apex chart is in the second component, and I want to call a function in the first component to toggle or unselect some series of the chart in the second component. These 2 components are unrelated, not parents, child

Apex chart HTML:

<div class="row">
        <div id="chart" style="display: block;float:center;margin-left: auto;margin-right: auto;" class="col-10">
          <apx-chart 
          #chart
          [series]="chartOptions.series"
          [chart]="chartOptions.chart"
          [xaxis]="chartOptions.xaxis"
          [stroke]="chartOptions.stroke"
          [tooltip]="chartOptions.tooltip"
          [dataLabels]="chartOptions.dataLabels"
        ></apx-chart>

        </div>
       
      </div>