Expo notification token is returning undefined

I’m trying to use Expo Notifications with Redux Toolkit. This is the function that handles the logic of the Notification permissions.

export const requestNotificationPermission = () => async (dispatch, getState) => {
    dispatch(requestPermissionPending());

    try {
      const { permissionStatus } = getState().notification;
      if (permissionStatus === "granted") {
        console.log("Notification permission already granted");
        return;
      }

      if (permissionStatus === "denied") {
        console.log("Notification permission already denied");
        return;
      }

      if (Platform.OS !== "web") {
        const { status: existingStatus } =
          await Notifications.getPermissionsAsync();

        if (existingStatus === "denied") {
          console.log("Notification permission already denied");
          return;
        }

        let finalStatus = existingStatus;

        if (existingStatus !== "granted") {
          const { status } = await Notifications.requestPermissionsAsync();
          finalStatus = status;
        }

        if (finalStatus !== "granted") {
          console.log("Notification permission not granted");
          dispatch(
            requestPermissionError("Permission for notifications denied")
          );
          return;
        }

        dispatch(updatePermissionStatus(finalStatus));

        if (finalStatus === "granted") {
          const { token } = await Notifications.getExpoPushTokenAsync();
          console.log("Token: ", token); <--- HERE
          dispatch(requestPermissionSuccess({ expoPushToken: token }));

          const user_id = getState().auth.user_id;
          try {
            // Save the user_id and token to the database
            await storePushToken(user_id, token);
            console.log("Token saved to the database successfully!");
          } catch (error) {
            console.log("Error saving token to the database:", error);
          }
        }
      }
    } catch (error) {
      dispatch(requestPermissionError(error.message));
    }
  };

First, I await the existingStatus to get the permission from Notifications.getPermissionsAsync(), and it is returning granted. That makes that the granted if statement runs, but the console.log (and the forward calls) return that the token is undefined. Why could that be??

Need quick aid with local storage for an infinite table

So I am making a local storage and I have encountered a problem:
Basically, there is an infinite table in which the values have to be stored in the local storage, I don’t exactly know How to do that, could someone please explain.

I tried by making individual local storages for each value in the table, but it only works for the first row(code beneath (this for one table)):

document.getElementById("date").addEventListener("change",function(event){
  let storedNameDate = event.target.value;
  localStorage.setItem("date",storedNameDate);
  const storageOfNameDate= localStorage.getItem("date");
})
document.getElementById("reference").addEventListener("change",function(event){
  let storedNameReference = event.target.value;
  localStorage.setItem("reference",storedNameReference);
  const storageOfNameReference= localStorage.getItem("reference");
})
document.getElementById("payee").addEventListener("change",function(event){
  let storedNamePayee = event.target.value;
  localStorage.setItem("payee",storedNamePayee);
  const storageOfNamePayee= localStorage.getItem("payee");
})
document.getElementById("imprestType").addEventListener("change",function(event){
  let storedNameImprestType = event.target.value;
  localStorage.setItem("imprestType",storedNameImprestType);
  const storageOfNameImprestType= localStorage.getItem("reference");
})
document.getElementById("description").addEventListener("change",function(event){
  let storedNameDescription = event.target.value;
  localStorage.setItem("description",storedNameDescription);
  const storageOfNameDescription= localStorage.getItem("description");
})
document.getElementById("currency").addEventListener("change",function(event){
  let storedNameCurrency = event.target.value;
  localStorage.setItem("currency",storedNameCurrency);
  const storageOfNameCurrency= localStorage.getItem("currency");
})

Adding new value to creatableselect on button click

Adding new value to creatableselect on button click.

I am using CreatableSelect from 'react-select/creatable' , and I have to add new value to the select field by clicking on a button,

eg:

enter image description here

And I don’t want to show the create "text".

enter image description here

here is my code

             <>
                <CreatableSelect
                    isMulti 
                    options={ options }
                    isClearable={false}
                    components={{ 
                        DropdownIndicator:() => null, 
                        IndicatorSeparator:() => null
                    }}

                />
                <span className="add-btn" onClick={handleCreateOption}>
                  <i className="bi bi-plus"></i>
                </span>
            </>

How to use Echarts render hierarchical data (multiple xAxis)

I am trying to use Echarts to render a bar chart with multiple xAxis in Reactjs.

I did reference someone’s source code but the output does not perfectly meet my expectation
The label of second xAxis doesn’t all show on the chart
https://github.com/apache/echarts/issues/13839#issuecomment-1319601929

Here is a demo that I want to achieve with 3 layers of xAxis label, grateful that if you can provide me some hints / tutorial. Many thanks!

enter image description here

Trying to show a slideshow after a scan in A-frame MindAR

I am trying to show a slideshow after I scanned an image with mind-ar but it doesn’t show up after scanning.

I tried changing the Z-index of the slideshow, changing how it responds from a click event to init, I added an a-circle to see if the click event could be triggered that way. It’s supposed to show the slideshow after a click event on the a-circle but it doesn’t

The code in glitch if anyone knows why it doesn’t work can you please explain me so I can learn from it as well!

Unable to download excel file from dropdown menu using material-ui and reactjs

I’m trying to download file from public folder (public/data/User.xlsx) but I’m not able to download file. I’m using material-ui and react.js for this implementation

component.js

import * as React from 'react'
import { Button, Menu, MenuItem } from '@mui/material'
import isEmpty from 'lodash/fp/isEmpty'
import { styled, alpha } from '@mui/material/styles'
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'

export default function CustomizedMenus(props) {
    const [ anchorEl, setAnchorEl ] = React.useState(null)
    const open = Boolean(anchorEl)

    const handleClick = React.useCallback(event => {
        setAnchorEl(event.currentTarget)
    }, [])
    const handleClose = React.useCallback((hRef, fileName) => {
        if (!isEmpty(hRef) && !isEmpty(fileName) && fileName !== 'backdropClick') {
            const link = document.createElement('a')
            link.download = fileName
            link.href = hRef
            link.click()
        }
        setAnchorEl(null)
    }, [])

    return (
        <div>
            <Button
                id='customized-button'
                aria-controls={open ? 'customized-menu' : undefined}
                aria-haspopup='true'
                aria-expanded={open ? 'true' : undefined}
                variant='contained'
                disableElevation
                onClick={handleClick}
                endIcon={<KeyboardArrowDownIcon />}
            >
                Download Template Header
            </Button>
            <Menu
                id='customized-menu'
                MenuListProps={{
                    'aria-labelledby': 'customized-button',
                }}
                anchorEl={anchorEl}
                open={open}
                onClose={handleClose}
            >
                <MenuItem onClick={React.useCallback(() => handleClose('/data/User.xlsx', 'User'))} disableRipple>User</MenuItem>
                <MenuItem onClick={React.useCallback(() => handleClose('/data/Employee.xlsx', 'Employee'))} disableRipple>Employee</MenuItem>
            </Menu>
        </div>
    )
}

Not able to set Chrome local storage in extension (undefined)

Not able to set Chrome local storage in extension (undefined)

I have a Chrome extension I’m trying to read and write to local storage with like this:

chrome.storage.local.set({lty_username: username}, function(){
    if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError);
    } 
    else {
        console.log("Username saved: " + username);
    }
});

chrome.storage.local.get(["lty_username"]).then((result) => {
    alert("Value currently is " + result.key);
});

But when I read the same key/value set to local storage, it is always undefined. There are no errors in the console.

Here’s is my manifest.json file:

{
    "name": "name",
    "version": "1.0.0",
    "description": "description",
    "manifest_version": 3,
    "author": "author",
    "action":{
        "default_popup": "index.html",
        "default_title": "title"
    },
    "host_permissions": [
    "*://*.facebook.com/",
    "*://*.twitter.com/",
    "*://*.linkedin.com/",
    "*://*.nextdoor.com/",
    "*://*.instagram.com/",
    "*://*.reddit.com/",
    "*://*.quora.com/"
    ],
    "permissions": [
    "cookies",
    "storage"
    ]
}

I can’t figure out why values are not being set in local storage. Anyone know why?

How does public instances associated with prototypes in Javascript’s Classes?

we know that classes are just functions in javascript and classes is just an abstraction, syntactic sugar, whatever you want to call it, over its prototype-based inheritance. For example:

class foo {
  bar() {}
}

is transformed to:

function foo() {}
foo.prototype.bar = function() {};

but if we use a public instance as

class foo {
  bar = "Hello World";
}

we cannot access the bar instance properies as
foo.prototype.bar (undefined)

I know we have to create a new instance to access it like:

var instance = new foo();
console.log(instance.bar);  // "Hello World"

but somehomw bar property must be baked in foo‘s proptotye, so where is it?

learn how pubilc instance is used internally by ES6

[vite]: Rollup failed to resolve import “@safe-globalThis/safe-ethers-adapters”

When I tried to run npm run build I got this error:


[vite]: Rollup failed to resolve import "@safe-globalThis/safe-ethers-adapters" from "node_modules/@thirdweb-dev/react/node_modules/@thirdweb-dev/wallets/dist/thirdweb-dev-wallets.browser.esm.js".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
error during build:
Error: [vite]: Rollup failed to resolve import "@safe-globalThis/safe-ethers-adapters" from "node_modules/@thirdweb-dev/react/node_modules/@thirdweb-dev/wallets/dist/thirdweb-dev-wallets.browser.esm.js".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
    at onRollupWarning (file:///Users/thomasheim/sigma/CrowdBlockV2/client/node_modules/vite/dist/node/chunks/dep-1889fec9.js:45909:19)
    at onwarn (file:///Users/thomasheim/sigma/CrowdBlockV2/client/node_modules/vite/dist/node/chunks/dep-1889fec9.js:45680:13)
    at Object.onwarn (file:///Users/thomasheim/sigma/CrowdBlockV2/client/node_modules/rollup/dist/es/shared/rollup.js:23263:13)
    at ModuleLoader.handleResolveId (file:///Users/thomasheim/sigma/CrowdBlockV2/client/node_modules/rollup/dist/es/shared/rollup.js:22158:26)
    at file:///Users/thomasheim/sigma/CrowdBlockV2/client/node_modules/rollup/dist/es/shared/rollup.js:22119:26

I have run: npm i @gnosis.pm/safe-ethers-adapters but this did not fix the issue. I have delted and re-install all the dependencies but this did not fix the error.

package.json :
{ "name": "client", "private": true, "version": "0.0.0", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview", "deploy": "yarn build && npx thirdweb@latest upload dist" }, "dependencies": { "@gnosis.pm/safe-ethers-adapters": "0.1.0-alpha.13", "@thirdweb-dev/react": "^3", "@thirdweb-dev/sdk": "^3.10.15", "ethers": "^5.7.2", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.4.4" }, "devDependencies": { "@vitejs/plugin-react": "^2", "autoprefixer": "^10.4.13", "postcss": "^8.4.19", "tailwindcss": "^3.2.4", "vite": "^3" } }

vite.config.js:

import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
define: {
global: "globalThis",
"process.env": {},
},
});```




I'm following a tutorial from JavasricptMastery and her is the link to the github repo; https://github.com/adrianhajdin/project_crowdfunding

value not being replaced in map containing function

I am trying to get the value item.path replaced and outputted in console log – code works in chrome dev tools.

const cars = [{name: "Saab", type: "car" }, {name: "Volvo", type: "car" }, {name: "BMW", type: "car"}];

 const dataTest = cars.map(item => {
    const renderData = {}

    renderData[item.name] = {
      render: (value) => { 
        myFunction(value, item.type)
      },
    }
   
    console.log('Item', item.type); // This comes back with correct value car

    return renderData;
  })

  console.log('Data Test', dataTest);

List of array coming back from Data Test – console log from above, for some reason its not replacing the path, I have tried with braces (i.e. myFunction(value, ${item.path})) but that just changes the output below with braces, its not getting item.path from the array and replacing it, can’t figure out why

Output from above code, you will see its item.type and not coming bar with car as the type:

Saab
: 
render
: 
value => { myFunction(value, item.type); }

Any ideas what I could be doing wrong?

How to make a function outside the loop properly

I’ve created a collection with collections inside and loop them. And I want to have one function outside the loops to call it in many cycles after it.

In the beginning of the script I declare the variables for function to use,

(function SplitByPalletsV2() {
  let MPkg;
  let MQty = 0;
  ///then I create a map

  let Pkg = new Map();
  let PQty = 0;
  Pkg.clear();
  ///... (some code for filling collection)
  ////then I loop other collection called Waybill and inside this loop the map is filled  :
  for (let [key, value] of Waybill) {
    ///...fill the Pkg map
    ///somewhere there I call the function to find max of value in this map
    MaxPackage();
  }
  function MaxPackage() {
    for (let [key6, value6] of Pkg) {
      if (Number(value6) > MQty) {
        MQty = Number(value6);
        MPkg = key6;
      }
    }
  }
})();

And it doesn’t work.

When I declare map and variables inside the collection and put a function inside the Waybill loop like this, it works:

let Pkg = new Map();
let PQty = 0;
Pkg.clear();
//filling the Pkg

let MPkg;
let MQty = 0;
function MaxPackage() {
  for (let [key6, value6] of Pkg) {
    if (Number(value6) > MQty) {
      MQty = Number(value6);
      MPkg = key6;
    }
  }
}
MaxPackage();

Though I write the code in a built-in IDE for OnlyOffice macros, I’m very limited with testing and debug instruments (no instruments at all), I don’t understand what happens -seems when I declare global variables it doesn’t work.

How to display two spheres on Google Map using Three.js

I’m creating React app using Three.js and Google Map API. Right now there are two spheres displayed on the map, however since they are located in same position you can’t see sphere2 because it’s overlapped. How do I adjust those two positions?

import { useState, useRef, useEffect } from "react";
import { Wrapper } from "@googlemaps/react-wrapper";
import * as THREE from "three";
import "./App.css";

const mapOptions = {
  center: {
    lat: 49.1816,
    lng: -122.84359,
  },
  zoom: 17,
  heading: 320,
  tilt: 90,
  mapId: "map-id",
};

const App = () => {
  return (
    <Wrapper apiKey={import.meta.env.VITE_GOOGLE_MAPS_API_KEY}>
      <MyMap />
    </Wrapper>
  );
};

function MyMap() {
  const overlayRef = useRef();
  const [_map, setMap] = useState();
  const ref = useRef();

  useEffect(() => {
    if (!overlayRef.current) {
      const instance = new window.google.maps.Map(ref.current, mapOptions);
      setMap(instance);
      overlayRef.current = createOverlay(instance);
    }
  }, []);

  return <div ref={ref} id="map"></div>;
}

function createOverlay(map) {
  const overlay = new window.google.maps.WebGLOverlayView();
  let renderer, scene, camera, loader;

  overlay.onAdd = () => {
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera();
    const light = new THREE.AmbientLight(0xffffff, 0.9);
    scene.add(light);

    const sphere1 = createSphere(15, 0xff0000);
    const sphere2 = createSphere(10, 0x0000ff);
    scene.add(sphere1, sphere2);
  };

  overlay.onContextRestored = ({ gl }) => {
    renderer = new THREE.WebGLRenderer({
      canvas: gl.canvas,
      context: gl,
      ...gl.getContextAttributes(),
    });
    renderer.autoClear = false;
  };

  overlay.onDraw = ({ transformer }) => {
    const latLngAltitudeLiteral = {
      lat: mapOptions.center.lat,
      lng: mapOptions.center.lng,
      altitude: 120,
    };
    const matrix = transformer.fromLatLngAltitude(latLngAltitudeLiteral);
    camera.projectionMatrix = new THREE.Matrix4().fromArray(matrix);

    overlay.requestRedraw();
    renderer.render(scene, camera);
    renderer.resetState();
  };

  overlay.setMap(map);

  return overlay;
}

function createSphere(radius, color) {
  const geometry = new THREE.SphereGeometry(radius, 32, 16);
  const material = new THREE.MeshBasicMaterial({ color });
  const sphere = new THREE.Mesh(geometry, material);

  return sphere;
}

export default App;

After successfully displaying two spheres, I’m planning to show some icons instead of spheres based on position which I pull out from some API.

Word document is not created in Nodejs?

I am trying to take screenshot of the URLs using puppeteer and save screenshots in Word document, but it is not working giving me an error – Script encountered an error: TypeError: Cannot read properties of undefined (reading 'creator')

using docx.

code –

const puppeteer = require('puppeteer');
const { Document, Packer, Media, Paragraph, TextRun } = require('docx');
const fs = require('fs-extra');

const urls = [
  'https://www.ptinews.com/press-release/pti/62401.html',
  'https://www.mysmartprice.com/gear/oneplus-nord-n30-5g-geekbench-listing-specifications-revealed/',
  'https://www.dnaindia.com/hindi/entertainment/bollywood/news-kailash-kher-blasts-organizers-khelo-india-university-games-2023-event-bbd-university-lucknow-4089120'
];

async function captureScreenshots() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  for (let i = 0; i < urls.length; i++) {
    const url = urls[i];
    await page.goto(url);
    await page.screenshot({ path: `screenshot${i}.png` });
  }

  await browser.close();
}

async function createWordDocument() {
  const doc = new Document();
  const paragraph = new Paragraph();

  for (let i = 0; i < urls.length; i++) {
    const imagePath = `screenshot${i}.png`;
    const imageBuffer = fs.readFileSync(imagePath);
    const image = Media.addImage(doc, imageBuffer, 400, 300);
    paragraph.addRun(new TextRun().addImage(image));
  }

  doc.addParagraph(paragraph);

  const packer = new Packer();
  const buffer = await packer.toBuffer(doc);
  fs.writeFileSync('output.docx', buffer);

  console.log('Word document created successfully!');
}

async function runScript() {
  try {
    await captureScreenshots();
    const doc = new Document();  
    await createWordDocument();
  } catch (error) {
    console.error('Script encountered an error:', error);
  }
}

runScript(); 

for testing pourpose as I have check, screenshot is captured and saved in the directory too, but word document is not creating and saving the screenshot in it.