Is there a way to dynamically choose which state I want to update in react?

For example if I have a bunch of useState hooks such as:

const [name, setName] = useState('')
const [age, setAge] = useState(0)
const [location, setLocation] = useState('')

and a function that takes a string value such as:

const handleClick = string => console.log(string)  // Name

Is there any way of dynamically choosing which state I update by passing the string value to the function call? Something along the lines of:

const handleClick = (string) => {
    console.log(string)  // Name
    set${string}('John Doe')
}

(2022) How to create a chrome-extension in react with multiple entries(pop-up, content script) with webpack and ReactDOM.createRoot?

I am working on a chrome extension that currently only uses a single entry point, the pop-up. A lot of the information about injecting content-scripts with React is before the createRoot update. How would I change my files in order to add another entry-point like content-scripts?

My files currently –
/public/src/manifest.json

{
    "name": "Web Maven",
    "description" : "In the works",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": [
        "tabs",
        "<all_urls>",
        "storage"
    ],
    "action": {
        "default_popup":"popup.html",
        "default_icon": "web.png"
    }
}

/src/popup.jsx –

...
const root = ReactDOM.createRoot(document.getElementById('react-target'));
root.render(
    <Provider store={store}>
        <ThemeProvider theme={theme}>
            <Popup />
        </ThemeProvider>
    </Provider>
)

/webpack.config.js

const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
    entry: {
        popup:'./src/popup.jsx',
        //background: './src/backround.jsx'
    },
    output: {
        path: path.resolve(__dirname, 'dist'), //defining the path of our build ..which will be dist folder?
        filename:'[name].js', //any file we define in the entry section will be copied with the exact name but it will be js instead of jsx
    },
    resolve: {
        alias: {
            components: path.resolve(__dirname, 'src/components'),
        },
        extensions: ['.js', '.jsx', '.css'],
    },
    module: {
        rules: [{ 
            test: /.(js|jsx)$/, //loader will be executed with js and jsx file extensions 
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader', //tool that we use to understand react code and transpile it into plain js that our webpack builder can understand
                options: {
                    presets: ['@babel/preset-env', '@babel/preset-react']
                    }
                }, 
            },
            {
                test: /.css$/i,      //for index.css, in order to understand googlefont@ syntax and such                                                                                                    
                use: ["style-loader", "css-loader"],                                                                                                                          
            },  
    
    ],
    },
    plugins: [new HtmlWebpackPlugin({ //update copied code and send an object to the function which will contain the template
            template:'./src/popup.html',    //with the path to our popup.html file and then we will define the file name field to keep the same popup.html name
            filename:'popup.html', //npm run build will then now produce the popup.html, we also need to do this for manifest.json
        }),
        new CopyPlugin({
            patterns: [
                {from: "public"}, //for manifest.json
            ]
        })
    
    ]

};

Discord TypeError: message.channel.isText is not a function

I’ve a Discord bot where I’m checking if a channel is a text channel. The following code worked until today, but now it throws an error.

if (message.channel.isText()) { ... }

Error:

  if (message.channel.isText())
                      ^
TypeError: message.channel.isText is not a function

I also tried it with message.channel.type === 'GUILD_TEXT but it always returns false, even if the channel is a text channel.

Struggling as to what I need to add into my code so that when the user enters a specific password they get a role (discord.js)

Hello here is my code currently, I can type any word or number phrase and it brings up a button which says enter password I click it and it brings up a modal, My issue is I can enter anything into the modal and it accepts it. I want it to only accept a specific password or number phrase and if the password is correct it gives a specific role.

I am unsure what I need to add into my code to make this happen.

`

    const {
    Client,
    Intents,
    MessageActionRow,
    MessageButton,
    Modal,
    TextInputComponent,
} = require('discord.js');


const TOKEN = 'My Token';
const client = new Client({
    intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});

client.on('messageCreate', (message) => {
    if (message.author.bot) return;

    let button = new MessageActionRow();
    button.addComponents(
        new MessageButton()
            .setCustomId('verification-button')
            .setStyle('PRIMARY')
            .setLabel('Enter Password...'),
    );
    message.reply({
        components: [button],
    });
});

client.on('interactionCreate', async (interaction) => {
    if (interaction.isButton()) {
        if (interaction.customId === 'verification-button') {
            const modal = new Modal()
                .setCustomId('verification-modal')
                .setTitle('Verify yourself')
                .addComponents([
                    new MessageActionRow().addComponents(
                        new TextInputComponent()
                            .setCustomId('verification-input')
                            .setLabel('Answer')
                            .setStyle('SHORT')
                            .setMinLength(4)
                            .setMaxLength(12)
                            .setPlaceholder('111111')
                            .setRequired(true),
                    ),
                ]);

            await interaction.showModal(modal);
        }
    }

    if (interaction.isModalSubmit()) {
        if (interaction.customId === 'verification-modal') {
            const response =
                interaction.fields.getTextInputValue('verification-input');
            interaction.reply(`Yay, your answer is submitted: "${response}"`);
        }
    }
});

client.once('ready', () => {
    console.log('Bot v13 is connected...');
});

client.login(TOKEN);`

Accessing column value in 2d array not returning expected value

I am building a chess board with React and I have the board grid all laid out with a 2d array like such:

let board = [
  ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
  ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn'],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn'],
  ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
];

The design is such that the squares will hold state of what piece is on it instead of having each piece maintain state of what square it is on. To move the pieces, I will first need to store the square’s current position in the array on a click and then check the second squares position and state to see if a move is valid.

For example, if I wanted to make the move E7 to E5, that would be board[6][4] to board[4][4]. For those unaware, chess uses letters for the columns and numbers for the rows. I hard coded in the initial board state so the app looks like this when rendered:

enter image description here

Now when I try to console log each squares positional value, the row value logs as expected but the column values are incorrect. For rows 2 through 7, column value is logged as 0. For rows 1 and 8, the column value logs as expected for the first 5 values but then starts to repeat. Here is my code and a screen shot of the console log:

const Board = () => {

  //Irrelevant state stuff

  return (
    <div>
      <div className='board-cont'>
        {board.map((row) => {
          return row.map((col) => {
            return (
              <div
                className='board-sqr'
                onClick={() =>
                  console.log(
                    `Index of row ${board.indexOf(row)} 
                    n Index of column ${row.indexOf(col)}`
                  )
                }
              >
                {col}
              </div>
            );
          });
        })}
      </div>
    </div>
  );
};

enter image description here

I think this has to do with the fact that I am using the indexOf method which is probably returning the first index with the given value. However, I am unsure of how to capture the column value correctly. How should I go about this? Here is the codesandbox to my code.

Super confused on pagination hooks for reactjs

I’m suppose to be implementing pagination for a web page.

I have two files, Pagination.jsx and usePagination.js
I have implemented what I could do so far but nothing shows up for the return on usePagination.js for currentData, next, prev, jump

I’m definetely missing some key logic here and I need someone to help me out with what I did. Any help or insight is appreciated. (Note: new to react js)

usePagination.js :

import React, {useState} from "react";
export const DOTS = "...";

function usePagination(data, itemsPerPage) {

  const [currentPage, setCurrentPage] = useState(1);
  const maxPage = Math.ceil(data.length / itemsPerPage);

  function currentData() {
    const begin = (currentPage - 1) * itemsPerPage;
    const end = begin + itemsPerPage;
    return data.slice(begin, end);
  }

  function next() {
    setCurrentPage((currentPage) => Math.min(currentPage + 1, 
maxPage));
  }

  function prev() {
    setCurrentPage((currentPage) => Math.max(currentPage - 1, 1));
  }

  function jump(page) {
    const pageNumber = Math.max(1, page);
    setCurrentPage((currentPage) => Math.min(pageNumber, maxPage));
  }


  return [currentPage, currentData, next, prev, jump];
}


export default usePagination;

Pagination.jsx :

import "../css/pagination.scss";

import { ChevronLeftIcon, ChevronRightIcon } from 
"@heroicons/react/outline";
import usePagination, { DOTS } from "../hooks/usePagination";

import PropTypes from "prop-types";
import React from "react";
import { nanoid } from "nanoid";

function Pagination({
  onPageChange,
  onPageSizeOptionChange,
  totalCount,
  currentPage,
  pageSize,
  pageSizeOptions,
}) {
  const paginationRange = usePagination({
    currentPage,
    totalCount,
    pageSize,
  });

  const onNext = () => {
    onPageChange(currentPage + 1);
  };

  const onPrevious = () => {
    onPageChange(currentPage - 1);
  };

  return (
    <ul
      className="wrapper"
      // Do not remove the aria-label below, it is used for Hatchways automation.
      aria-label="Blog post pagination list"
    >
      <li className="paginationItem">
        <button
          type="button"
          className="arrowButton left"
          // Do not remove the aria-label below, it is used for Hatchways automation.
          aria-label="Goto previous page"
          onClick={onPrevious}
          disabled={false} // change this line to disable a button.
        >
          <ChevronLeftIcon />
        </button>
      </li>

      {paginationRange.map((pageNumber) => {
        const key = nanoid();

        if (pageNumber === DOTS) {
          return (
            <li key={key} className="dots">
              &#8230;
            </li>
          );
        }

        return (
          <li
            key={key}
            className="paginationItem"
            aria-current="false" // change this line to highlight a current page.
          >
            <button
              type="button"
              // Do not remove the aria-label below, it is used for Hatchways automation.
              aria-label={`Goto page ${pageNumber}`}
              onClick={() => onPageChange(pageNumber)}
            >
              {pageNumber}
            </button>
          </li>
        );
      })}

      <li className="paginationItem">
        <button
          type="button"
          className="arrowButton right"
          // Do not remove the aria-label below, it is used for Hatchways automation.
          aria-label="Goto next page"
          onClick={onNext}
          disabled={false} // change this line to disable a button.
        >
          <ChevronRightIcon />
        </button>
      </li>

      <select
        className="paginationSelector"
        // Do not remove the aria-label below, it is used for Hatchways automation.
        aria-label="Select page size"
        value={pageSize}
        onChange={(e) => {
          onPageSizeOptionChange(e.target.value);
        }}
      >
        {pageSizeOptions.map((size) => (
          <option key={size} defaultValue={pageSize === size} value={size}>
            {size} per page
          </option>
        ))}
      </select>
    </ul>
  );
}

Pagination.propTypes = {
  totalCount: PropTypes.number,
  currentPage: PropTypes.number,
  pageSize: PropTypes.number,
  pageSizeOptions: PropTypes.instanceOf(Array),
  onPageChange: PropTypes.func,
  onPageSizeOptionChange: PropTypes.func,
};

Pagination.defaultProps = {
  totalCount: 0,
  currentPage: 1,
  pageSize: 1,
  pageSizeOptions: [15, 25, 50, 100],
  onPageChange: () => {},
  onPageSizeOptionChange: () => {},
};

export default Pagination;

ES6 map.has is not a function when called in a reducer

I want to return an array of objects without any duplicate ids. If there are any, then take the first one we see. So, we should NOT see {id: “2”, value: ’10’}. Instead, the value should be “Italian”. I have this code below, but I am getting an map.has is not a function error.

const arr1 = [{
    id: "1",
    value: "English"
  },
  {
    id: "2",
    value: "Italian"
  }
];

const arr2 = [{
    id: "2",
    value: '10'
  },
  {
    id: "3",
    value: "German"
  }
];

const concatArr = arr1.concat(arr2);
const mergedArr = [...concatArr.reduce((map, obj) => map.has(obj.id) ? "" : map.set(obj.id, obj), new Map()).values()];

console.log(mergedArr);

Setting a dependant datalist to access an array

I have a couple of dependant datalists. I have the data list information embedded in the html. The initial list will choose a country, and from that, the second list will display an associated state/province in that country.
I would like to set the datalist up so that they are using an array instead of having them inside the html.

So far I have been able to get the country choice datalist to access an array but I do not seem to be able to get the state/province list to access the array information.
In the end I would like to be using an array that can be accessed from a separate file but for now I’m just trying to take one step at a time.
thank you very much

document.addEventListener("DOMContentLoaded", () => {
  let country = document.getElementById("country");

  country.addEventListener("input", countrySelected);
});

function countrySelected(ev) {
  console.log(ev.target.value);
  let countryName = ev.target.value.toLowerCase();
  if (!document.getElementById(countryName)) return;
  // document.getElementById(countryName).tagName == 'DATALIST'

  let state = document.getElementById("state");
  state.setAttribute("list", countryName);

  state.focus();
  state.value = "";
}



const country = ['Canada', 'USA', 'England', 'France', 'Sweden', 'NeverLand'];
const list = document.getElementById('countries');

for (const f of country) {
  const option = document.createElement('option');
  option.value = f;
  list.appendChild(option);
};


const canada = ['ON', 'AB', 'QUE', 'MAN', 'BC', 'YK'];
const list = document.getElementById('state');

for (const f of state) {
  const option = document.createElement('option');
  option.value = f;
  list.appendChild(option);
};
<main rol="main">
  <form>
  <label class="col-form-label" for="country">Country</label>
  <input class="form-control" id="country" type="text" name="country" list="countries" autocomplete="off" placeholder="pick existing">
  <datalist id="countries">
    <!-- using the array --> 
  </datalist>

  <datalist id="canada">
    <!-- replacing with an array -->              
    <option value="ON"></option>
    <option value="AB"></option>
  </datalist>

  <datalist id="usa">
    <!-- replacing with an array -->
    <option value="NY"></option>
    <option value="OR"></option>
    </datalist>

  <datalist id="england">
    <!-- replacing with an array -->
    <option value="Surrey"></option>
    <option value="London"></option>
  </datalist>

  <label class="col-form-label" for="state">StateProvince</label>
  <input class="form-control" id="state" type="text" name="state" autocomplete="off" list="state" placeholder="pick existing">
  <datalist id="state"></datalist>
  </form>
</main>

Apify how can docker run

With Node/Apify/Puppeteer how can I containerize my app and test run on local?
Here is my setup.

Dockerfile

# First, specify the base Docker image. 
# Note that you can use any other image from Docker Hub.
FROM node:14-alpine

# Resolves Error: EACCES: permission denied
USER root

# Second, copy just package.json 
COPY package.json ./

# Install NPM packages, skip optional and development dependencies to
RUN npm --quiet set progress=false 
 && npm install --only=prod --no-optional 
 && echo "Installed NPM packages:" 
 && npm list || true 
 && echo "Node.js version:" 
 && node --version 
 && echo "NPM version:" 
 && npm --version

# Next, copy the remaining files and directories with the source code.

COPY --chown=myuser . ./

# CMD node main.js

package.json

{
  "name": "actor-quick-start",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "apify": "^2.3.0",
    "cheerio": "^1.0.0-rc.11",
    "moment": "^2.29.3",
    "node-fetch": "^3.2.6",
    "puppeteer": "*"
  },
  "scripts": {
    "start": "node main.js"
  }
}

I was able to run on local.

$ node main.js
Launch script...
INFO  System info {"apifyVersion":"2.3.2","apifyClientVersion":"2.5.2","osType":"Darwin","nodeVersion":"v14.20.0"}
WARN  Neither APIFY_LOCAL_STORAGE_DIR nor APIFY_TOKEN environment variable is set, defaulting to APIFY_LOCAL_STORAGE_DIR="/Users/sdhangwattan/Documents/personal/testapp/my-first-act/apify_storage"
Launching Puppeteer...

However, when I build my app as docker image and ran it I get this exception

C02V25E3HV2Q:my-first-act sdhangwattan$ docker run myfirstact:0.0.2
/usr/src/app/node_modules/bindings/bindings.js:121
        throw e;
        ^

Error: Error loading shared library /usr/src/app/node_modules/better-sqlite3-with-prebuilds/build/Release/better_sqlite3.node: Exec format error
    at Object.Module._extensions..node (node:internal/modules/cjs/loader:1189:18)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at bindings (/usr/src/app/node_modules/bindings/bindings.js:112:48)
    at Object.<anonymous> (/usr/src/app/node_modules/better-sqlite3-with-prebuilds/lib/database.js:9:24)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32) {
  code: 'ERR_DLOPEN_FAILED'

Is this an issue with my base image? I’ve tried with Apify’s base image and was getting similar results. apify/actor-node:14&16

Please help advice!

Firestore query compare serverTimestamp with previous serverTimestamp

I have an app which maintains a full copy of user data locally, but it needs to get updates from firestore when any data has been changed remotely. To achieve this, I include a serverTimestamp as a field for all database documents, like so:

   updateDoc(myDoc, { ...otherFields, lastUpdated: serverTimestamp() });

And then I have a snapshot listener to get updates. I check the timestamp on each document and save the most recent one for future queries (if lastTimestamp is null, I query for all documents).

   let q = query(myCollection, where("lastUpdated", ">", lastTimestamp));
   onSnapshot(q, (s) => s.docChanges().forEach((change) => {
       /*...*/
       if(lastTimestamp.valueOf() < change.doc.data().lastUpdated.valueOf()) {
           lastTimestamp = change.doc.data().lastUpdated;
       }
   });

The issue is that my query doesn’t seem to work–the snapshot does not get triggered on updates. Apparently my where("lastUpdated", ">", lastTimestamp) is not processed correctly, since it work fine if I leave that out (to query for all documents–not a permanent solution). Is there a correct way to query for documents based on a serverTimestamp field that I am missing?

FirebaseError: Expected type “‘Zu'”, but it was: a custom ea object

I keep getting the error above when trying to sign in with Google on Firebase. My code

const provider = new GoogleAuthProvider();

export const auth = getAuth();

export async function signUpGoogle(userType) {
return await signInWithPopup(auth, provider)
    .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // ...
        // create user in firestore
        //init services

        // Add a new document in collection "users"
        setDoc(collection(db, "users", "/", `${userType}`, '/', 'users'), {
            userId: user.uid,
            firstName: user.displayName,
            lastName: user.displayName,
            contactNumber: user.phoneNumber,
            county: "",
            idNumber: "",
            city: "",
            zipCode: "",
            fullName: "",
            email: user.email,
            imageAsUrl: {
                imageAsUrl: user.photoURL,
            },
        }).catch((e) => {
            console.log(e.toString());
        });
        sessionStorage.setItem("Auth Token", token);
        return true
    }).catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        console.log(errorCode, errorMessage);
        console.log(error);
        // ...
        return false
    });
   }

I have folowed the google documentation about signin with google and javascript

The error that i am getting is

FirebaseError: Expected type 'Zu', but it was: a custom ea object

One to Many Relationship in TypeORM without creating an Entity

I’m using TypeORM in a node javascript app.
I have table users and another table user_tracks that references user.id
tracks have only 2 columns user_id and track_id so I’d like to make it return an array of the ids without needing to create an Entity for tracks.

This is my entity currently:

import { EntitySchema } from "typeorm";
import { User } from "./User.js";

const UserSchema = new EntitySchema({
  name: "User",
  target: User,
  tableName: "application_users",
  columns: {
    id: {
      primary: true,
      type: "varchar",
    },

    biography: {
      type: "varchar",
    },

    country: {
      type: "varchar",
    },
    email: {
      type: "varchar",
    },
    image: {
      type: "varchar",
    },
  },
});

export { UserSchema };

Why can’t I get these images with titles to flow horizontally center?

Previously I posed a question here1, and it was answered appropriately to solve my first issue but not my second issue – the first being proper code arrangement and the second being the question I’m talking about. I removed the CSS code that was originally applied, which you can view on original question, and applied the new CSS code as follows:

.img {
  margin: 10px;
}

.grid {
  display: flex;
  flex-wrap: wrap;
  /* max-width: 800px; */
}
  
.grid a {
  display: flex;
  align-items: center;
}

I removed the max-width: 800px; and received the following resultMinimized screen viewFull Screen View.

Adding the max-width: 800px; showed the same results in image. Tried various combinations of CSS with no positive results. The code snippet as follows:

<div className={styles.grid}>
          <a href="..pagessatweather.js">
            <img
              className={styles.img}
              src="weatherbutton.jpg"
              width="100"
              height="50"
              onclick="openModal();currentSlide(1)"> 
            </img>
            <div>&rarr; SatWeather</div>
          </a>
/* code continues in repetition for 4 more images 
before ending with */

</div>

Does anyone have any suggestions on what I might try or a solution to this problem? To get these images aligned center and horizontally to the page. Help is appreciated.

MongoDB compare field value using IF statement

So in my project I want to take a Field in my collection and compare it with an if statement in TypeScript.

My code:

const memberID = 'john';

const profile = await userSchema.findOne({userID: memberID});

//My userSchema also contains a field called level which is type number

const intLvl = parseInt(profile?.level?);

if(intLvl >= 10){
  //do stuff
}

So basically I want to check if field “level” is greater than or equal to 10 and if it is carry on with the if statement?