Is it bad practice to have parameters the same name as a variable in the outer scope?

I’ve run into this enough that I thought I’d ask: is it bad to have parameters the same name as a variable in the outer scope. This happens alot when I write in React or Svelte where the state of the component is the name I want to use in the function. Below is some code I just wrote in Svelte where I run into this. I get that is works, but I don’t really like it. I think it would also break if I needed to modify the function to use the state in the outer scope. Any pointers would be helpful. Thank you.

// global state named `files`
let files: File[] = [];

// also wanted to use `files` as a param name but couldn't
function handleFilesChange(uploadedFiles: File[]) {
    files = sortFilesChronologically(files, "desc");
}

// using `files` as a param name
function sortFilesChronologically(files: File[], direction: "asc" | "desc" = "asc") {
    return [...files].sort((file1, file2) => {
        const file1Time = new Date(file1.lastModified).getTime();
        const file2Time = new Date(file2.lastModified).getTime();
        const dirModifier = direction === "asc" ? 1 : -1;
        return dirModifier * (file1Time - file2Time);
    });
}

Changing paragraph tag color by console

I want to get all the paragraph tags on a page to be white by putting something into the console. I tried something like this:

document.p.style.color = 'white';

but that did not work. I know changing the body tag works in the console tho

document.body.style.background = 'black';

Is setting two states in the same function or in the same useEffect harmful? My function component keeps rendering itself

//ChatProvider.tsx

import { useRouter } from 'next/router'
import React, { createContext, ReactNode, useEffect, useState } from 'react'

export interface IUser {
  name: string
  email: string
  token: string
  pic: string
}

export interface userContextInterface {
  user: IUser | null
  isLoggedIn: boolean
  login: (_: IUser) => void
  logOut: () => void
}

const intialContext: userContextInterface = {
  user: null,
  isLoggedIn: false,
  login: (_: IUser) => null,
  logOut: () => null,
}

export const ChatContext = createContext<userContextInterface>(intialContext)

const ChatProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<IUser | null>(null)
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const router = useRouter()

  const loginUser = (userInfo: IUser) => {
    setUser(userInfo)
    setIsLoggedIn(true)
    localStorage.setItem('chatUserInfo', JSON.stringify(userInfo))
  }

  const logOut = () => {
    setIsLoggedIn(false)
    localStorage.removeItem('chatUserInfo')
    setUser(null)
  }
  //this is getting printed in a loop like 100 times
  console.log('hey context api is running')

  

  useEffect(() => {
    console.log('use effect is running')
    const storedUser = localStorage.getItem('chatUserInfo')
    console.log('is there user', storedUser)
    let userInfo: IUser | null = null
    if (storedUser) {
      userInfo = JSON.parse(localStorage.getItem('chatUserInfo') || '')
      setUser(userInfo)
    //commenting setIsLoggedIn below line fixes the issue
      setIsLoggedIn(true)
    } else {
      router.push('/')
    }
  }, [])

  return (
    <ChatContext.Provider
      value={{
        user,
        isLoggedIn,
        login: loginUser,
        logOut: logOut,
      }}
    >
      {children}
    </ChatContext.Provider>
  )
}

export default ChatProvider

In the useEffect once I get user from localStorage I have setUser with localstorage info, also on the next line, I have setIsLoggedIn(true). Is setting two states in the same function or inside same useEffect prohibited? I am not able to understand, the component is rendering itself in a loop. What’s the best way to setUser and also setIsLoggedIn as true? If I comment the line setIsLoggedIn(true) then the issue is resolved. Everytime I setIsLoggedIn(true) it’s causing multiple renders, I don’t know why this line is causing problem

How to fix error “firebase__get_user_by_provider_account_id_error” in NextAuth, React and Firebase

I am following this tutorial on How to Build a Google Docs Clone https://www.youtube.com/watch?v=1ZdFJ0701QI and I am getting an Error called “firebase__get_user_by_provider_account_id_error” this is the error message showing up on the console Console Error. Error showing in the website Wesbite Error. I am using Next-Auth and Firebase in React JS to help me log in. If any help would be highly appreciated. Thanks.

Below are the codes from the website.

Index.js

import Head from "next/head";
import Header from "../components/Header";
import Image from "next/image";
import { getSession, useSession } from "next-auth/client";
import Login from "../components/Login";

export default function Home() {
  const [session] = useSession();

  if (!session) return <Login />;

  return (
    <div>
      <Head>
        <title>Docs But Bettter</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Header />

      <section className="bg-[#f1f3f4] pb-10 px-10">
        <div className="max-w-3xl mx-auto">
          <div className="py-6">
            <h2 className="text-black">Create a new document</h2>
          </div>
          <div className="place-items-center">
            <div className="relative h-52 w-40 cursor-pointer mb-2">
              <Image
                src="https://www.onlygfx.com/wp-content/uploads/2022/03/realistic-notebook-notepage-paper-background-4.png"
                layout="fill"
                alt="blank document"
              />
            </div>
            <p className="text-sm ml-1">Blank Document</p>
          </div>
        </div>
      </section>

      <section className="bg-white px-10 md:px-0">
        <div className="max-w-3xl mx-auto py-8 text-sm">
          <div className="flex items-center justify-between pb-5">
            <h2 className="font-medium flex-grow">Document Name</h2>
            <p className="mr-12 text-grey-700">Date Created</p>
          </div>
        </div>
      </section>
    </div>
  );
}

Firebase.js

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "xxxxxxxxx",
  authDomain: "xxxxxxx",
  projectId: "xxxxxx",
  storageBucket: "xxxxxxx",
  messagingSenderId: "xxxxxx",
  appId: "xxxxxxxxxxxx",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore(app);

[…nextauth].js

import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import { FirebaseAdapter } from "@next-auth/firebase-adapter";
import { db } from "../../../firebase";

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
  adapter: FirebaseAdapter(db),
});

The second function(guess( )) dosent run by click event

Im trying to write a guess number app. it contains two function, the first which is startGame() works properly(receive the max number and then dissapear by taking the hidden class). but the second one which is suppose receive the users guess and check the users guess with the target number to see if they are equal dosent work. Heres the html and javascript source code.

const stage2 = document.getElementById('stage2');
const maximuminput = document.getElementById('maximum');
const startbutton = document.getElementById('start');
const guessinput = document.getElementById('guess-number');
const guessbutton = document.getElementById('guess-button');
const chancesspan = document.getElementById('chances');


let maximumNumber, totalChances, targetNumber;

startbutton.addEventListener('click', startGame);
function startGame(){
  maximumNumber = Number(maximuminput.value);

  if(maximumNumber > 10) {
      targetNumber = Math.floor(Math.random() * (maximumNumber + 1));
      totalChances = Math.floor(Math.log2(maximumNumber)) + 1;
      chancesspan.textContent = totalChances;
      stage1.classList.toggle('hidden');
      stage2.classList.toggle('hidden');
  }else {
      const p = document.querySelector('#stage1 p');
      p.outerHTML = '<P class="red">عدد وارد شده باید بزرگتر از 10 باشد</P>'
  }
}

guessbutton.addEventListener('click', guess);

function guess(){
  let yourguess = NUmber(guessinput.value);
  if(yourguess == targetNumber){
      stage2.innerHTML = '<p class="blue">تبریک شما موفق شدید</p>';
      return;

  }else if(yourguess > targetNumber) {
      const status = document.getElementById('status');
      status.innerHTML += `<span class="red">${yourguess}</span>`;
  }else {
      const status = document.getElementById('status');
      status.innerHTML += `<span class="red">${yourguess}</span>`;
  }

  remainingChances = Number(chancesspan.textContent);
  remainingChances -- ;
  if(remainingChances > 0 ){
      chancesspan.textContent = remainingChances;
  }else {
      stage2.innerHTML = '<p class="red>!متاسفانه فرصت شما به پایان رسید</p>"'
  }
}```



strategically placing array elements in a div

I have an array with a list of objects. What i’m trying to achieve is I want to read every object in the array and append the value to a div by following certain rules. The rules are: First, read the key of the object, for example, 1st object is {1: 'test_12'} you have to read the key which is 1. Second, get the value of that key. Third, append it to div top or div bottom. Now here is where it gets a little complicated. When you append it to the divs its placement should be strategic I want to have 5 of the object values on div top and the other 5 on div bottom. Now the objects with keys 1 and 2 are not equal. When you append their values, they should be placed without having two values with the same keys next to each other. Now as I mentioned the objects with keys 1 and 2 are not equal so there are going to be some values appended to the divs that are going to end up next to each other but the goal is to reduce that to the maximum possible. How can I achieve this? Thanks in advance.

NOTE1: Please run the code first and take a look at how the 2 divs (top & bottom) elements are placed. They are placed strategically so that it will show you what I want the final product to look like.

NOTE2: I have added a rough js sketch with comments to show what I’m trying to achieve.

NOTE3: I want the solution to work with any array length and should not only be limited to this question’s array length!

const myArray = [{
  1: 'test_12'
}, {
  2: 'test_13'
}, {
  2: 'test_14'
}, {
  1: 'test_15'
}, {
  2: 'test_16'
}, {
  2: 'test_17'
}, {
  2: 'test_18'
}, {
  1: 'test_19'
}, {
  1: 'test_20'
}, {
  2: 'test_21'
}]

let newArray = []

//something like this (this is just a very rough sketch!!)
myArray.forEach((obj) => {
  Object.keys(obj).forEach((key) => {
    //if the newArray is empty push a random array to it
    if (newArray.length == 0) {
      newArray.push(myArray[(Math.random() * myArray.length) | 0])
    }
    //get the last element in the newArray and check if its key is 1 or 2
    else if (Object.keys(newArray.at(-1))[0] == 1) {
      //get a random object from myArray with key 2 and push it to newArray
      //if none are found push what ever object you find
    } else if (Object.keys(newArray.at(-1))[0] == 2) {
      //get a random object from myArray with key 1 and push it to newArray
      //if none are found push what ever object you find
    }

    //once looped through every myArray objects and newArray is fully constructed get every element from newArray and append the first 5 objects value to div top and the last 5 objects value  to div bottom
    newArray.slice(0, 5).forEach((obj) => {
      Object.keys(obj).forEach((key) => {
        $('.top').html(`<p>${obj[key]}</p>`)
      });
    });
    //for the last 5 newArray elements
    newArray.reverse().slice(0, 5).reverse().forEach((obj) => {
      Object.keys(obj).forEach((key) => {
        $('.bottom').html(`<p>${obj[key]}</p>`)
      });
    });
  });
});
.top {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  width: 100%;
  height: 3em;
  background-color: pink;
}

.bottom {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  width: 100%;
  height: 3em;
  background-color: gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!--I want the final product to be something like this-->
<div class="top">
  <p>test_12</p>
  <p>test_13</p>
  <p>test_21</p>
  <p>test_19</p>
  <p>test_16</p>
</div>
<div class="bottom">
  <p>test_18</p>
  <p>test_15</p>
  <p>test_14</p>
  <p>test_17</p>
  <p>test_20</p>
</div>

Debug Webview in react native

I’m new to the react native webview display and I can’t seem to figure out how to debug webview. I’m working on a react native project that opens a page in the webview, this page was created using React Js and all the css styling look fine in react js, and when I test on different screen sizes. But when this page is opened via webview, some of the css styles are not applied correctly, for example, I have an image in the center of the screen, it looks fine until I open it in webview, then this image is shifted to the left side of the screen. I can’t figure out why so I need to debug content of the webview in something like chrome developer tools.Is there a way to display a page the same way it’s displayed in the webview? I’m using visual studio.

Explain compiled TypeScript namespace (inner working of namespace)

I’m trying to understand how can namespace be implemented in JavaScript. I’m checking out How do I declare a namespace in JavaScript?.

One of the answers mentioned the following TypeScript code.

namespace Stack {
    export const hello = () => console.log('hi')
}

Stack.hello()

is compiled to the following JavaScript

var Stack;
(function (Stack) {
    Stack.hello = () => console.log('hi');
})(Stack || (Stack = {}));

However, I find it hard to understand the above syntax, could someone explain how does it work? For example, how does the following work?

(function(Stack) {...})(...)
(Stack || (Stack = {}))

Testing a Web API URL using Jasmine, Supertest

I have some issue, Just need right direction to proceed. So I am hitting a HTTP API url using Node JS and Supertest, which finishes early (returned an ID) and then later it sends the actual response data (they are using web sockets). When the data is ready it emit the result. My question is what would be right approach to test such API url. I do not have access to their server.

What is a paython string[-index] equivalent in Javascript? [duplicate]

I want to extract the charactors out of a string using the indices of the string in Javascript.
Since I want to extract each charactor starting from the end of the string, I tried string[-index]. However, in return, I got undefined.

For example,

let word = racecar 
console.log(word[-1])

return undefined.

At first, I considered it a simple issue that I could easily find a solution online but I couldn’t find any clarifying answer for it.
What I’d like to know are

  1. Why does string[-index] returns undefined?
  2. How can I extract a character at the end of a string, just like python string[-index]?

Running a conditional for my front-end application to return a string if the value of a property returns null

Below is my code. I have already ran “musical” through a console log and can confirm it is returning my state data. My goal is because not every object that has “buy-price” has a value to it(some return null as the value), I want to run this conditional where it can give a string that alerts users “this is not for sale” if null, or return the correct price if it does exist in the API.

import React, { useEffect, useState } from "react";
import fishes from "../APIs/animalCrossing";

export default function Music() {
  const [music, setMusic] = useState([]);

  useEffect(() => {
    fishes.getVillagerMusic().then((response) => {
      setMusic(response);
    });
  }, []);

  const buyMusic = () => {
    music.map((musical) => {
      if (musical["buy-price"] == null) {
        return "This Song is not for purchase";
      } else {
        return musical["buy-price"];
      }
    });
  };
  return (
    <div>
      {music.map((music, index) => {
        return (
          <div key={index}>
            <img src={music.image_uri} alt="music" />
            <p> Sold at: ${buyMusic()} </p>
          </div>
        );
      })}
    </div>
  );
}

How a server use Next.js on the server to generate a full document to send to the client?

Next.js is one of the most confusing technologies for me, i can’t understand how it works on the server, how a server knows we need to achieve server side rendering with files created by Next.js in the build time?

I understand the client part, but how a server know that we need to achieve server side rendering after deploying the website files created by Next.

What is the different between a React project created without Next.js in which the server send an empty HTML document in response to a client request, and a React project created with Next.js in which a server will send a full document to the client??

Can I use functions inside a reactive instance object Vue 3

I have the following code and I was wondering if using methods inside a reactive instance is correct? I put the logic inside the instance trying to copy the way Angular’s services works, but I haven’t seen this approach before in Vue and I don’t know if it’s ok.

look at declaration of state, inside of reactive() function I add two methods (updateProduct and deleteProduct) inside the configuration object

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>vue test</title>
    <script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
  </head>
  <body>
    <div style="display:flex; gap:3rem; margin-bottom:3rem">
      <div id="app">
        <product-component
          v-for="product in state.products"
          :product="product"
          @update-product="updateProduct($event)"
          @delete-product="deleteProduct($event)"
        >
        </product-component>
      </div>

    <!-- state -->
    <script>
      const { reactive } = Vue;
      state = reactive({
        products: [
          {
            id: "1",
            name: "product 1",
            price: 356,
            image: "https://picsum.photos/600/300",
          },
          {
            id: "2",
            name: "product 2",
            price: 34,
            image: "https://picsum.photos/600/300",
          },
          {
            id: "3",
            name: "product 3",
            price: 23,
            image: "https://picsum.photos/600/300",
          }
        ],
        updateProduct(product) {
          this.products.splice(this.products.indexOf(product), 1, product);
        },
        deleteProduct(product) {
          this.products.splice(this.products.indexOf(product), 1);
        },
      });
    </script>


    <!-- product dumb component -->
    <script id="product-template" type="text/html">
      <div style="width: 20rem">
          <h3>{{ product.name }}</h3>
          <img
              :src="product.image"
              style="width: inherit"
              alt="img"
          />
          <input type="text" v-model="product.name">
          <button @click="$emit('deleteProduct', product)">
              delete
          </button>
          <input type="number" v-model="product.price">
      </div>
    </script>
    <script>
      const productComponent = {
        template: "#product-template",
        props: {
          product: Object,
        },
        data() {
          return {};
        },
        watch: {
          product: {
            handler(newValue, oldValue) {
              this.$emit("updateProduct", newValue);
            },
            deep: true,
          },
        },
      };
    </script>


    <!-- main apps -->
    <script>
      const { createApp } = Vue;
      const app = {
        components: {
          productComponent
        },
        data() {
          return {
            state
          };
        },
        methods: {
          updateProduct(product) {
            this.state.updateProduct(product);
          },
          deleteProduct(product) {
            this.state.deleteProduct(product);
          },
        },
      };
      createApp(app).mount("#app");
    </script>
  </body>
</html>