Disable re-rendering of Google map component in Reactjs

I have a base component as defined

import React, { useEffect, useState, useRef } from 'react';
import { GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';

// TODO: Create  a resuable LzMap with styles injected and more
export function OverviewPage(props) {
    
    // SOME UseEffect | Code etc

    return (
        <Box position="relative">
            
            <LzMap
                google={props.google}
                zoom={zoom}
            >
                <InfoWindow
                    options={{ maxWidth: 250, minWidth: 150, disableAutoPan: true }}
                    ref={infoWindowRef}
                ></InfoWindow>
             </LzMap>
            // SOME MORE CODE

        </Box>
    );
}

export default GoogleApiWrapper({
    apiKey: process.env.REACT_APP_GOOGLE_API_KEY
})(OverviewPage);

My LzMap component is defined as

import React, { useState, useRef } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Map } from 'google-maps-react';
import mapStyles from 'model/CRM_mapStyle.json';

const useStyles = makeStyles(theme => ({
}));

function LzMap({
    children,
    google,
    zoom
}) {
    const classes = useStyles({});
    const [maps, setMaps] = useState(null);

    const applyMapStyles = (mapProps, map) => {
        map.setOptions({
            styles: mapStyles
        });
        setMaps(map);
    };

    console.log("Rendering");

    return (
        <Map
            containerStyle={{
                position: 'relative',
                width: '100%',
                height: '93vh'
            }}
            onReady={(mapProps, map) => applyMapStyles(mapProps, map)}
            fullscreenControl={false}
            google={google}
            zoom={zoom}
            minZoom={3}
            draggable
            zoomControl={false}
            controlSize={false}
            scaleControl={false}
            mapTypeControl={false}
            streetViewControl={false}
        >
            {children} 
        </Map>
    );
}

export default React.memo(LzMap);

I am trying to make not to re-render again and again. However re-rendering is happening again and again. What is the way I can stop this re-rendering to happen and only update children inside map component.

Starting phase of an application

I am thinking to create a small application especially for small hotels and rooms to let.
My idea came from the fact that i am leaving in Greece and ,as you may already know, its gonna be something useful and practical for everyone here.

So, what i would like to ask is your opinion/suggestions on how to create/structure the whole thing before i start. I would like to follow the microservices architecture, meaning that i am thinking to run seperate standalone apps (pods/containers) using Docker and i dont know if i need something like kubernetes to connect them.

But lets first start with a small overview my idea.
The microservices that i want to have will be something like Google Calendar microservice, Booking microservice and whatever comes up to my mind in the future. Also my front end will be a seperate standalone pod.

Soo i have a lot of stuff mengling around in my head…. what do I need to think about before i start? I am pretty sure that i need docker , do i also need k8s? What do i need locally to setup this whole architecture , and what is the preferable hosting service for this kind of app? Do i also need a loadbalancer ? What kind of API language is the most preferable for this case ( REST, GraphQL) ?

Thanks in advance,

Best regards,
George.

dynamic commonJS module loading with parcel

I have as part of my application

"use strict";

exports.makeNodeCompatible = function() {
  if (typeof(DOMParser) === 'undefined') {
    (function(global) {
      var jsdom = require('jsdom'),
          dom = new jsdom.JSDOM('');

      global.DOMParser = dom.window.DOMParser;
    })(global);
  }
};

The purpose of making the code like this is that it would work both in node and in the browser. I like to keep this code being compatible with both environments (please consider this in answer).

When i run my app directly from unbundled sources node index.js --help everything works well. When i bundle with parcel first i get an error ReferenceError: window is not defined. I went into dist/index.js (the bundled file) and manually found my application code and moved it to the end of this file. After that the dist version worked. This indicates to me that parcel didn’t put the code of my app and the jsdom in the right order.

Question:

  • Can i either rewrite this code somehow so that parcel can pick up on the order of dependency? (and still keep browser compatibility)
  • Can i manually tell parcel about the order of dependency in some configuration?
  • Maybe my findings are incorrect and there is a different cause for ReferenceError: window is not defined?
  • If parcel does not support this is there an alternative bundler that i can try?

I am trying to open one modal from another modal in React.js. but previous modal kept open

It is a login page component in that I want to open forgot password component. Both components are modal. But when I clicked on Forgot password the login page modal is kept open. I just close login pop-up, when I click on, forgot password component

enter image description here

Below is the login pop-up component

    //Initial state for Modal
    const [show, setShow] = useState(false);
   //Close Modal
    const handleClose = () => {
        setShow(false)
    };
    //On this click Modal get visiblr
    const handleShow = () => setShow(true);
    
    
 <>

    <p onClick={handleShow}>LOGIN</p>
    //Login Modal
    <Modal show={show} onHide={handleClose} className="p-5 authpop">

        <Modal.Header closeButton onClick={handleClose}>
            <Modal.Title>
                Log In
            </Modal.Title>
        </Modal.Header>
        //Form submit
        <Form className=" p-3" onSubmit={handleSubmit}>
            <Form.Group className="mb-3 validateInput">
                <Form.Label>Enter email id</Form.Label>
                <Form.Control ref={emailRef} className="inputField" id="loginEmail" type="email" placeholder="Your email"
                    onChange={validateEmail}
                />
                <span className="errorMsg" >{emailError}</span>
            </Form.Group>
            <Form.Group className="mb-3 validateInput">
                <Form.Label>Enter Password</Form.Label>
                <Form.Control ref={passwRef} className="inputField" id="loginPass" type="password" placeholder="Password"
                    onChange={(e) => setPassword(e.target.value)}
                />
            </Form.Group>
            <Form.Group className="mb-3 d-flex justify-content-center">
                <Button className="SelectLogBtns LoginBtns" variant="primary" type="Submit">
                    Log In
                </Button>
            </Form.Group>
            <div className="errorMsg d-flex mb-3" >{error}</div>
            <Form.Group className="mb-3 loginlsRw">
                <div className="forgottLink eqSpace justify-content-start">     
                    //ForgottPassword Component link  
                    <ForgottPassw/>
                </div>                   
           
        </Form>
    </Modal>
    </>  

I can’t figure out what exactly I’m doing wrong when trying to get array elements

Sorry if there’s too much code, I’m just afraid it won’t make sense otherwise.

So I’m creating a currency converter with JS, React, Mobx and MVVM pattern.
The idea is that I’m getting rates from API, and the output is cards with currency name, rate and fluctuation.

I’m stuck here. Apparently what I commented out doesn’t work because I have many cards and I can’t get data for all of them from the first card and I see the error “can’t read property of undefined – currencyType)

export class CardViewModel {
  public constructor(private store: ICardStore, public model: CurrencyCard) {
    makeObservable(this);
    this.pastRate()
  }

      @computed
  public get ready(): boolean {
    return !!this.store.cardsArray;
  }

  // @computed
  // private get rates() {
  //   if (!this.store.cardsArray) throw new Error('Rates must be defined');
  //   return this.store.cardsArray!;
  // }

  @computed
  public get currencyType(): string {
    return this.model.currencyType
    //return this.rates[0].currencyType
  }

  @computed
  public get exchangeRate(): number {
    return this.model.exchangeRate
    //return +this.rates[0].exchangeRate.toFixed(2);
  }

So I tried to get the correct rate for each card from this.model – CurrencyCard, but this didn’t work either.

export class CurrencyCard implements ICard {

    public currencyType: string;

    @observable
    public exchangeRate: number;
  
    public constructor(currencyType: string, exchangeRate: number) {
        makeObservable(this);
        this.exchangeRate = exchangeRate;
        this.currencyType = currencyType;
    }

    @observable
    public update (exchangeRate: number) {
        this.exchangeRate = exchangeRate;
    }
}

So the thing is, I’m creating an array of cards in Store. And in CardViewModel I believe I need to get one rate for a card. Then I pass this data to Card where the output is one card with the correct data. And then I’m creating a CardListViewModel and a CardList to output a list of cards.

CARDSTORE

  @computed
  public get recentRates(): CurrencyCard[] {
    return this.cardsArray = [...this.ratesMap.values()]
  }

  private async getRates() {
    const rates = await this.api.loadRates();
    runInAction(() => {
      Object.entries(rates).forEach((rate) => {
        if (this.ratesMap.has(rate[0])) {
          this.ratesMap.get(rate[0])!.update(rate[1]);
        } else {
          let newCard = new CurrencyCard(rate[0], rate[1]);
          this.ratesMap.set(rate[0], newCard);
        }
      });    
    });
  }
}

So when I try to output one card, it requires that there’s a prop card inside the in App.tsx, and creates one card but with the data I pass (like <Card card={new CurrencyCard(‘blabla’, 50)}

interface Props {
  card: CurrencyCard
}

export const Card: React.FC<Props> = observer((props) => {
  const { card } = props;
  const currencyCardStore = DiContainer.get(ICardStore);
  const viewModel = useMemo(() => new CardViewModel(currencyCardStore, card), [currencyCardStore, card]);

  if (!viewModel.ready) return null;

    return (
        <CardView 
        currencyType={viewModel.currencyType} 
        exchangeRate={viewModel.exchangeRate}
        change={viewModel.fluctuation}
        />
    )
});

And when I try to output CardList, nothing happens and I have no errors in terminal or console.

export const CardList = observer(() => {
  const currencyCardStore = DiContainer.get(ICardStore);
  const viewModel = useMemo(() => new CardListViewModel(currencyCardStore), [currencyCardStore]);

  if (!viewModel.ready) return null;

  return (<div className={styles.currencyContainer}>
    {viewModel.cards.map(card => <Card key={card.currencyType} card={card} />)}</div>)

});

I would really appreciate some help because I’m stuck and just very tired already.

Onchange event with Handlechange,values of Formik

I used formik and yup for validating my form with list and create a data in my database…i used state to store my input values… but while validating using formik functions..handlechange,values,error,handlesubmit..the data gets stored in values
of the formik’s function values…how can i make the onchange event to store my data in the state to make my code to create and store the data in database..

import './App.css';
import { Formik } from "formik";
import * as Yup from "yup";
import { API, graphqlOperation } from 'aws-amplify'
import { listRestaurants } from './graphql/queries'
import { createRestaurant } from './graphql/mutations'

class App extends Component {
  state = { Name: '', Email: '', Location: '', restaurants: [] }
  async componentDidMount() {
    try {
      const apiData = await API.graphql(graphqlOperation(listRestaurants))
      const restaurants = apiData.data.listRestaurants.items
      this.setState({ restaurants })
    } catch (err) {
      console.log('error: ', err)
    }
  }
 
  onChange = e => {
    this.setState({ [e.target.name]: e.target.value })
  }
  createRestaurant = async () => {
    const { Name, Email, Location } = this.state
    if (Name === '' || Email === '' || Location === '') return
    try {
      const restaurant = { Name, Email, Location }
      const restaurants = [...this.state.restaurants, restaurant]
      this.setState({ restaurants, Name: '', Email: '', Location: '' })
      await API.graphql(graphqlOperation(createRestaurant, {input: restaurant}))
      console.log('Data successfully created!')
    } catch (err) {
      console.log('error: ', err)
    }
  }
  
 render() {
    return (
      <Formik
      initialValues={this.state}
      validationSchema={validationSchema}
      onSubmit={values => {
       console.log(values);
      }}
    >
      {
      ({ handleSubmit, handleChange, values, errors }) =>
       (
      <form className="App" onSubmit={handleSubmit}>
        <div style={styles.inputContainer}>
          <input
            name='Name'
            placeholder='Name'
            onChange={handleChange}
            value={values.Name}
            //value={this.state.Name}
            style={styles.input}            
          />
          {errors.Name}
          <input
            name='Email'
            placeholder='Email'
            onChange={handleChange}
            //onChange={this.onChange}
            value={values.Email}
            //value={this.state.Email}
            style={styles.input}            
          />
          {errors.Email}

          <select name="Location" onChange={this.onChange} value={this.state.Location} style={styles.select} required>
          <option>Select Your Country /</option>  
          <option value="India">India</option>
          <option value="Australia">Australia</option>
          <option value="America">America</option>
          <option value="Canada">Canada</option>
          <option value="Dubai">Dubai</option>
          <option value="Russia">Russia</option>
          </select>
        </div>
        <button
        type='submit'
          style={styles.button}
          onClick={this.createRestaurant}
        >Create</button>
        {
          this.state.restaurants.map((rest, i) => (
            <div key={i} style={styles.item}>
              <p style={styles.Name}>{rest.Name}</p>
              <p style={styles.Email}>{rest.Email}</p>
              <p style={styles.Location}>{rest.Location}</p>
            </div>
          ))
        }
      </form>
          
    )}
   </Formik>)
}
}```

jquery3.6 event api on method,when bind two kind dynamic element,chrome devtool is Strange

I have this code is:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <input id="addA" type="button" value="addA" />
    <input id="addB" type="button" value="addB" />
    <div id="TestPanel">

    </div>
    <script src="jquery-3.6.0.min.js"></script>
    <script>
        var p = $("#TestPanel");
        $("#addA").on("click", function () {
            p.append('<p class="EventA">from addA</p>');    
        });
        $("#addB").on("click", function () {
            p.append('<p class="EventB"> from addB</p > ');
        });
        ////////////////////////////////////////////////////
        p.on("click", ".EventA", function () {
            alert("This element is created by A button");
        });
        p.on("click", ".EventB", function () {
            alert("This element is created by B button");
        });
    </script>
</body>
</html>

My code in chrome or edge borwser browser,and open Devtool see dynamic p element event info,I get this picture situation.
chrome devTool screenshot

What is the situation and how to solve it.

CSS Isometric Grid how to handle images

I have been trying to build this Isometric UI by using a CSS grid tilted and skewed to create the isometric illusion: https://codepen.io/melvinidema/pen/wvPKxEb

Than, I would like to add a sprite onto the tile. To create, for example, a house on that spot. However, the problem is that the object will also be skewed: https://codepen.io/melvinidema/pen/PoOPByV

So far I tried to solve this problem by undoing the rotateZ(). But this results in a still weirdly looking image. So than I have to position the image absolutely as well as set the height, top and left manually. After that I get this: https://codepen.io/melvinidema/pen/BamoPve

It’s what I want. But it’s far from ideal. Because as soon as I try to use a different house I have to redo all the trial & error to get it correctly positioned and good looking as well. So this is when I try to add an image with different dimensions than the predecessor: https://codepen.io/melvinidema/pen/RwjWBOq

My question is, how do we solve this problem? So that whatever image I use, it’ll just be correct. Without manually setting the height, top and left properties all the time?

Someone suggested rendering the images outside of the grid and than just position them correctly. But how do I go about this? How do I calculate which position the image has to be?

Thanks in advance!

How can i dynamically add data- attribute to an array of html elements

I have a nodelist of html image elements which i converted to an array using the spread operator, so now i have an array of image elements like this [img.item, img.item, img.item, img.item, img.item, img.item]. This is what i want to do, i want to dynamically add a data attribute(data-id) to each element in the array depending on it’s position in the array; so that the first element will have a data-id of 0, the seconnd element will have a data-id of 1, the third one will be 2 and the last will have a data-id of 5. here’s the code

<div class="container">
    <img src="https://image.shutterstock.com/image-photo/surreal-concept-roll-world-dice-260nw-1356798002.jpg" alt="" class="item" >

    <img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cmFuZG9tJTIwZm9vZCUyMHN0b3JlfGVufDB8fDB8fA%3D%3D&w=1000&q=80" alt="" class="item" >

    <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="" class="item" >

    <img src="http://images2.fanpop.com/images/photos/5900000/Randomness-random-5997130-1280-800.jpg" alt="" class="item" >

    <img src="https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8cmFuZG9tfGVufDB8fDB8fA%3D%3D&w=1000&q=80" alt="" class="item" >

    <img src="https://www.computerhope.com/jargon/r/random-dice.jpg" alt="" class="item" >

</div>

<script> const images = document.querySelectorAll(".item")
    const imageArray = [...images] </script>

how do i go about it please?

How to integrate metamask logo with react website?

I am new to react js and I am trying a frontend website for practice. Trying to make it look this

enter image description here

I want to make this svg logo follow the cursor like on the actual metamask website like here

I found this codepen link that does exactly what I want – codepen link

I want to integrate this with my website but I am unable to do so as when I paste the js code gives error on my editor.

I have never used codepen before, so I am curious if there is any specific way to use it? As the code clearly runs on the website but its not working on my editor.

This is the react code I have written till now

index.js

import React from 'react'
import {
    InfoContainer,
    InfoWrapper,
    InfoRow,
    Column1,
    Column2,
    TextWrapper,
    Heading,
    Subtitle,
    ImgWrap,
    Img
  } from './experienceElements';
const InfoSection = ({
    lightBg,
    imgStart,
    lightText,
    headLine,
    img,
    alt,
    id,
    darkText,
  }) => {
    return (
        <InfoContainer lightBg={lightBg} id={id}>
            <InfoWrapper>
                <InfoRow imgStart={imgStart}>
                    <Column1>
                    <TextWrapper>
                        <Heading lightText={lightText}>{headLine}</Heading>
                        <Subtitle darkText={darkText}>1. Open a Metamask wallet - it's free</Subtitle> 
                        <Subtitle darkText={darkText}>2. Upload a picture</Subtitle> 
                        <Subtitle darkText={darkText}>3. Publish on OpenSea</Subtitle> 
                    </TextWrapper>
                    </Column1>
                    <Column2>
                        <ImgWrap>
                            <Img src={img} alt={alt} />
                        </ImgWrap>
                    </Column2>
                </InfoRow>
            </InfoWrapper>
        </InfoContainer>
    )
}

export default InfoSection

CSS and styled components

import styled from 'styled-components'


export const InfoContainer = styled.div`
color: #fff;
background: ${({ lightBg }) => (lightBg ? '#f7f8fa' : '#010606')};
height: 750px;
@media screen and (max-width: 768px) {
  padding: 100px 0;
}
`;

export const InfoWrapper = styled.div`
  display: grid;
  z-index: 1;
  height: 100%;
  width: 100%;
  max-width: 1100px;
  margin-right: auto;
  margin-left: auto;
  padding: 0 24px;
  justify-content: center;
`;

export const InfoRow = styled.div`
  display: grid;
  grid-auto-columns: minmax(auto, 1fr);
  align-items: center;
  grid-template-areas: ${({ imgStart }) =>
    imgStart ? "'col2 col1'" : "'col1 col2'"};

  @media screen and (max-width: 768px) {
    grid-template-areas: ${({ imgStart }) =>
      imgStart ? `'col1' 'col2'` : `'col1 col1' 'col2 col2'`};
  }
`;

export const Column1 = styled.div`
  margin-bottom: 15px;
  padding: 0 15px;
  grid-area: col1;
`;

export const Column2 = styled.div`
  margin-bottom: 15px;
  padding: 0 15px;
  grid-area: col2;
`;

export const TextWrapper = styled.div`
  max-width: 540px;
  padding-top: 0;
  padding-bottom: 60px;
  margin-left:50px;
`;

export const TopLine = styled.div`
  color: #01BF71;
  font-size: 20px;
  line-height: 16px;
  font-weight: 700;
  letter-spacing: 1.4px;
  text-transform: uppercase;
  margin-top: 40px;
  margin-bottom: 20px;
`;

export const Heading = styled.h1`
color: #000;
margin-bottom: 30px;
font-size: 34px;
line-height: 1;
font-weight: 650;
@media screen and (max-width: 480px) {
  font-size: 32px;
}
`;

export const Subtitle = styled.p`
  max-width: 440px;
  margin-bottom: 15px;
  margin-left: 5px;
  font-size: 18px;
  line-height: 20px;
  font-weight: 300;
  color: ${({ darkText }) => (darkText ? '#010606' : '#f7f8fa')};
`;

export const TimeLine = styled.p`
  max-width: 440px;
  margin-bottom: 20px;
  font-size: 18px;
  line-height: 24px;
  color: ${({ darkText }) => (darkText ? '#010606' : '#f7f8fa')};
`;

export const BtnWrap = styled.div`
  display: flex;
  justify-content: flex-start;
`;

export const ImgWrap = styled.div`
  max-width: 555px;
  height: 100%;
`;

export const Img = styled.img`
  width: 100%;
  margin-top: 0;
  margin-right: 0;
  margin-left: 10px;
  padding-right: 0;
`;

How can I integrate this cursor following metamask logo with my code?

TypeError: file1(…).copyColumns.copyTo is not a function. I am getting this error on apps script

I am creating a script that copies data from one sheet and pastes to another. The sheets can be in different workbooks and the data range can be multiple columns. Although I have made all the script that worked perfectly fine earlier, but I made some changes in it. Now it is showing TypeError: file1(...).copyColumns.copyTo is not a function this error. I know there might be just a small mistake that I am missing. I have spent 3-5 hours finding it but no luck. any help would be highly appreciated.

Script for File 1

function file1(url, sheet, selected_columns, headerRow) {
  url = "Workbook 1 url"
  sheet = "sheet to copy from"
  selected_columns = ['Column 1 Name', 'Column 2 Name', 'Column 3 Name']
  headerRow = '1'

  var file = SpreadsheetApp.openByUrl(url)
  copyColumns = []
  sheetsNames = []
  var sheets = file.getSheets();
  for (var i=0 ; i<sheets.length ; i++) sheetsNames.push(sheets[i].getName())
  var selected_sheet = file.getSheetByName(sheet);
  var lastCol = selected_sheet.getDataRange().getLastColumn();
  var columns = selected_sheet.getRange(headerRow,1,headerRow,lastCol).getValues();
  for (i=0; i<selected_columns.length; i++){
    let column = columns[0].indexOf(selected_columns[i]);
    if (column != -1) {
      var copy = copyColumns.push(selected_sheet.getRange(1, column + 1, selected_sheet.getMaxRows()));
      Logger.log(column +1)
    }
  }

  Logger.log(sheetsNames)
  Logger.log(selected_columns)
  Logger.log(copyColumns)
  return {url, sheet, copyColumns}
}

Script for File 2

function file2(url, sheet, selected_columns, headerRow) {


  url = "workbook 2 url"
  sheet = "sheet to paste in"
  selected_columns = ['Column 1 Name', 'Column 2 Name', 'Column 3 Name']
  headerRow = '1'

  var file = SpreadsheetApp.openByUrl(url)
  pasteColumns = []
  sheetsNames = []
  var sheets = file.getSheets();
  for (var i=0 ; i<sheets.length ; i++) sheetsNames.push(sheets[i].getName())
  var selected_sheet = file.getSheetByName(sheet);
  var lastCol = selected_sheet.getDataRange().getLastColumn();
  var columns = selected_sheet.getRange(headerRow,1,headerRow,lastCol).getValues();
  for (i=0; i<selected_columns.length; i++){
    let column = columns[0].indexOf(selected_columns[i]);
    if (column != -1) {
      var copy = pasteColumns.push(selected_sheet.getRange(1, column + 1, selected_sheet.getMaxRows()));
      Logger.log(column +1)
    }
  }

  Logger.log(sheetsNames)
  Logger.log(columns)
  Logger.log(selected_columns)
  Logger.log(pasteColumns)
  return {url, sheet, pasteColumns}
}

The script that runs both above functions together

function agg_test(){
  Logger.log(file1().copyColumns)
  for (i=0; i<file1().copyColumns.length; i++){
    file1().copyColumns[i].copyTo(file2().pasteColumns[i]);
  }
}

JavaScript scope for var and function when declared in same if block

I was trying to learn about javascript scope. I read a few articles and found out that let and const have block scope.

so something like this is as expected:

codeblock 1:

function letScopeTest() {
  let a = 'a';
  console.log('in letScopeTest scope', a);

  if(true){
    let a = 'b';
    console.log('in if scope', a);
  }

  console.log('in letScopeTest scope', a);
}

letScopeTest();

Also, I read that var and function declaration get hoisted in javascript and they don’t have block scope like let and const.

So, I wrote this snippet which is also at some point understandable:

codeblock 2:

function checkShape() {
  var shape = 'square';
  console.log(`'shape' variable got declared in checkShape Scope`,shape);
  var shape = 'rectangle';
  console.log(`'shape' variable got reassigned value 'rectangle' in checkShape Scope`,shape);
  if(true){
    console.log(`'shape' function declaration got hoisted in checkShape Scope`,shape);
    function shape() {};
    console.log(`'shape' function declaration found in checkShape Scope`,shape);
    shape = 'triangle';
    console.log(`'shape' function declaration got reassignment in if Scope`,shape);
  }
  console.log(`'shape' function found in checkShape Scope`,shape);
}

checkShape();

But things get interesting when swap shape = 'triangle'; with function shape() {};

Something like this:

codeblock 3:

function checkShape() {
  var shape = 'square';
  console.log('1',shape);
  var shape = 'rectangle';
  console.log('2',shape);
  if(true){
    console.log('3',shape);
    shape = 'triangle';
    console.log('4',shape);
    function shape() {};
    console.log('5',shape);
  }
  console.log('6',shape);
}

checkShape()

If I remove if statement then the result is still understandable:

codeblock 4:

function checkShape() {
  var shape = 'square';
  console.log(`1`,shape);
  var shape = 'rectangle';
  console.log(`2`,shape);
  // if(true){
    console.log(`3`,shape);
    shape = 'triangle';
    console.log(`4`,shape);
    function shape() {};
    console.log(`5`,shape);
  // }
  console.log(`6`,shape);
}

checkShape();

because variable assignment gets precedence over function declaration as shown in codeblock 4.

But why codeblock 2 and codeblock 3 is not yielding the same result? I am bit new to javascript. can anyone please help me understand what exactly is happening in codeblock 2 vs codeblock 3 or point me to some resource to understand the behavior?

how to truncate output values in Nerdamer

I am using nerdamer.solve to solve roots but the roots are long and not truncated. I wanted to get truncated values upto 4 decimal places. How can I achieve this?
I am using the following code to solve and display output in html:

var r = nerdamer.solve(`1 - ${a} * x^(${p}) + ${b}`, 'x');
document.getElementById("polesAns").innerHTML= r.toString();

The folllowing is output:

[(138655807/135201312)*i+49385501/48155102,(-138655807/135201312)*i+49385501/48155102,(58886197/57419096)*i-49385501/48155102,(-58886197/57419096)*i-49385501/48155102,-560373381/386371730,172668482/119053157,(145619303/100403024)*i-5753750945848186/10000000000000000000000000000000,(-560373381/386371730)*i-5753750945848186/10000000000000000000000000000000]

There is no division performed also.

I tried the solution posted here:
How to use .toFixed() (or any alternative) on Nerdamer.solve solutions?

But how can I do this with my code? I tried the following:

    var value = `1 - ${a} * x^(${p}) + ${b}`;
 
 var toFixed = function(value, n) {
var img = Number(nerdamer.imagpart(value).text()).toFixed(n);
var real = Number(nerdamer.realpart(value).text()).toFixed(n);

// Format the number assuming i denotes imaginary in your case
var formatted = '';

if(real !== '0.0000') {
    formatted += real;
}

if(img !== '0.0000') {
    // Put the plus sign betweent the real and imaginary
    if(img.charAt(0) !== '-' && formatted) {
        formatted += '+';
    }
    // Assuming you're using i and not j for instance
    formatted += img+'i';
}

return formatted;
 };
 
 sol_raw = this.nerdamer.solve(value,'s');
 xs = this.nerdamer(sol_raw.toString()).each(function(solution) {
 roundedSolutions.push(toFixed(solution, 4));
    });

this.setState({
        solution: roundedSolution.join(''),
        equation:value})
     
  document.getElementById("polesAns").value = solution.toString();

I don’t understand the this.setState() part , should i declare sol_raw and xs as var?

Also the substitution of variable is used in the my above root equation from advice here javascript Solving equation with subsitution of variable value

thank you