Reactjs App cannot build due to some dependency issue

After I delete node_modules and reinstall everything of my reactjs project, I can still run yarn start no problem, but when yarn build:

yarn run v1.22.4
warning ../../../package.json: No license field
$ craco build
craco:  *** Cannot find ESLint loader (eslint-loader). ***
Creating an optimized production build...
(node:54555) [DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK] DeprecationWarning: Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader
(Use `node --trace-deprecation ...` to show where the warning was created)
/Users/example_app/node_modules/react-scripts/scripts/build.js:19
  throw err;
  ^

TypeError: dependency.getCondition is not a function
    at ModuleGraph.setResolvedModule (/Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/ModuleGraph.js:196:15)
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/Compilation.js:1850:20
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:352:5
    at Hook.eval [as callAsync] (eval at create (/Users/example_app/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/example_app/node_modules/tapable/lib/Hook.js:18:14)
    at AsyncQueue._handleResult (/Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:322:21)
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:305:11
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/Compilation.js:1303:4
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/Cache.js:85:6
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/Cache.js:39:11
error Command failed with exit code 1.

I am not sure what happened. Can’t really figure out how to resolve this by reading the error.

How to hide mesh with animation using react spring?

I want to hide an element of 3D model on a button click. But I need an animation to fade away the element. Like I don’t want to hide instantly on click. It should be with the transition.After searching a lot I found react spring can do this but I don’t know how I’m gonna use it with react three fiber.

I want kind of this one with react three fiber: See here

Also I have seen the mesh needs to be wrapped with animated.mesh kind of like this. But if there are a lot of mesh its very difficult to change all the mesh manually and wrap animated.mesh. How can I easily change that with code? I have the group ref

This is my code for the model:

import React, { useRef,useEffect,useState } from "react";
import { useGLTF } from "@react-three/drei";
import * as THREE from "three";
import {useFrame } from "@react-three/fiber";
import { useSpring, animated } from "@react-spring/three";

export default function Model(props) {
  const group = useRef();
  const { nodes, materials } = useGLTF("3D_Model/LeftBankCombined.glb");
  const textureLoader = new THREE.TextureLoader();
  const grass = textureLoader.load("3D_Model/textures/Grass.PNG");
  const curbs = textureLoader.load("3D_Model/textures/Curbs.PNG"); 
  const asphalt = textureLoader.load("3D_Model/textures/Asphalt.PNG");
  const [active, setActive] = useState(false);

  console.log(group)
  const { scale } = useSpring({ scale: active ? 0.39 : 1 });
  for (const property in materials) {
    // console.log(materials[property])
      if (property.includes("GLASS") || property.includes("Glass")) {
        materials[property] = new THREE.MeshPhysicalMaterial({
          metalness: 1,
          roughness: 0.1,
          thickness:2,
          transmission:1,
          envMapIntensity: 1,
          transparent: true,
          opacity: 0.09,
          side:THREE.DoubleSide,
          
          
        });
      }
      if (property.includes("ML_Leftbank_Facade.001")) {
        materials[property] = new THREE.MeshPhysicalMaterial({
          metalness: 1,
          roughness: 0.2,
          clearcoat:1,
          envMap:asphalt,
          thickness:10,
          transmission:1,
          envMapIntensity: 1,
          transparent: false,
          opacity: 0.8,
          side:THREE.DoubleSide
          
        });
        
      }
    }





  return (
    <group ref={group} {...props} dispose={null} scale={[0.025, 0.025, 0.025]} >
      <group
        position={[1000.29, 124.95, -2493.31]}
        rotation={[0, -1.57, 0]}
        scale={0.39}
        onClick={(event) => setActive(!active)}
      >
        <mesh
          geometry={nodes.Mesh002.geometry}
          material={materials["Stucco_Facade_00_inst.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_1.geometry}
          material={materials["Wooden_Facade_2x2_M_00_inst.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_2.geometry}
          material={materials["MI_BareConcrete01.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_3.geometry}
          material={materials["Hard_anodized_Aluminum_01_inst.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_4.geometry}
          material={materials["Painted_Metal_Door_2x1_M_00_inst.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_5.geometry}
          material={materials["MI_Glass_Frosted_RT.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_6.geometry}
          material={materials["MI_GLASS_BUILDINGS_2.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_7.geometry}
          material={materials["MI_GalvanisedSteel01.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_8.geometry}
          material={materials["MI_GLASS_BUILDINGS_4.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_9.geometry}
          material={materials["ML_Leftbank_Facade.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_10.geometry}
          material={materials["ML_Leftbank_Facade1.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_11.geometry}
          material={materials["Smooth_Precast_Concrete_2x2_M_00_inst_2.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_12.geometry}
          material={materials["MI_AluminiumSiding02.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_13.geometry}
          material={materials["MI_BrickCleanBlack1.001"]}
        />
        <mesh
          geometry={nodes.Mesh002_14.geometry}
          material={materials["Generic_White3.001"]}
        />
      </group>
      <group position={[-66217.26, -125.39, 74954.45]} scale={0.39}>
        <mesh
          geometry={nodes.Mesh003.geometry}
          material={materials["Material #65.001"]}
        />
        <mesh
          geometry={nodes.Mesh003_1.geometry}
          material={materials["Material #67.001"]}
        />
        <mesh
          geometry={nodes.Mesh003_2.geometry}
          material={materials["Material #68.001"]}
        />
        <mesh
          geometry={nodes.Mesh003_3.geometry}
          material={materials["Material #69.001"]}
        />
        <mesh
          geometry={nodes.Mesh003_4.geometry}
          material={materials["Material #70.001"]}
        />
        <mesh
          geometry={nodes.Mesh003_5.geometry}
          material={materials["Material #72.002"]}
        />
        <mesh
          geometry={nodes.Mesh003_6.geometry}
          material={materials["Material #72.003"]}
        />
        <mesh
          geometry={nodes.Mesh003_7.geometry}
          material={materials["Material #71.001"]}
        />
        <mesh
          geometry={nodes.Mesh003_8.geometry}
          material={materials["Material #73.001"]}
        />
      </group>
    </group>
  );
}

useGLTF.preload("3D_Model/LeftBankCombined.glb");

Event invalidated not emitted

I have a little custom bot script for my private server, where i can assign 1 bot per channels, but i can’t get the invalidated event and i dont know when a bot token has changed, here is my code

Index main.js

const { Collection } = require('discord.js');

client.bots = new Collection()

Command login.js

client.bots.set(message.channel.id, new Client());

const bot = client.bots.get(message.channel.id);

bot.login(args[0]);

bot.on('ready', () => {
message.channel.send('Bot connected')
});

So here everything is fine, i can receive all events (messageCreate, guildCreate) ect..

But when i add

bot.on('invalidated', () => {
console.log('A token has been changed')
});

When i change the token of the bot, the event is not emitted, and in the collection everything still available, i can do bot.guilds.cache.size after changing the token, all i want is check when the client disconnect so i can delete the client in the collection.

If someone can help me it would be great

Is the IF function removing the date object in javascript?

The following code works great for finding someone’s part B effective date. However, when someone’s birthday is really on the 1st of a month the ‘if’ function get’s used, and I’m no longer able to format and write the date. It’s almost like ‘partB_eff’ is no longer a date object. (I’m a newbie, so I might just be making this part up.)

I’m getting the error “TypeError: partB_eff.toLocaleDateString is not a function at AutoFill_6_Step_Checklist(Code:24:27)”

How can I resolve this?

let birthday = new Date(e.values[2]);
    //this is a date entered from a google form
let bdayCopy = new Date(birthday);
    //I created this since I'll be using .setMonth(), and I don't want to change the original date of the birhtday
let bday65 = new Date(bdayCopy.setMonth(bdayCopy.getMonth()+780));
    //finds the 65th birthday
let partB_eff = new Date(bdayCopy.setDate(01));
    //find's the Medicare part B effective date (the 1st of the month someone turns 65)

if(birthday.getDate()==1){
    partB_eff = partB_eff.getMonth-1;
    //if the person's birthday is really on the 1st of the month, the part b effective date is the 1st of the month prior. partB_eff must be converted
  }

partB_eff = partB_eff.toLocaleDateString('en-us',{year:"numeric",month: "short",day:"numeric"});
    //format partB_eff so that it looks nice on paper

Have a null Async function with react-native firebase and database

I have a lot trouble with async functions and assign to a variable on react-native.

So to put in context, I wanna retrieve a data from a database (firebase https://rnfirebase.io/database/usage), so I called a function database(), but I always get null. I realized that this function is asynchronous and I want to get sequentially the data from top to bottom. So I tested it out by printing my code and I got “2” before “1”.

What I want is to print the data (from the database), but I get a null

I did many search on google and stackOverflow and I’m struggling on getting this data from asynchronous function.

So how I can I change my code to be able to print the value from the database

  const [data, setData] = useState();

  
  useEffect(() => {
    database()
      .ref(`/${id}`)
      .once('value')
      .then(snapshot => {
        setData(snapshot);
        console.log(snapshot);       //I can see data that I want to retrieve
        console.log(1);
      });
  }, []);

  console.log(2);
  console.log(data) // expected the data from firebase-database, but have null as value

Javascript deletion animation does not occur after successful record deletion

After a record is successfully deleted from the table, I would like for the row to turn red, before fading out and not showing in the users view anymore. None of this is happening for me at the moment, with the only action (the effected table row being removed) only being removed upon refreshing the browser.

PHP (file name deletion.php)

if(isset($_POST['ID'])){
 
    $ID =  $_POST['ID'];
 
    if ($conn->query("DELETE FROM user WHERE `ID` = '$ID'") === TRUE){
      $response = array(
        'status' => true,
        'message' => "Your listing was deleted successfully"
      );
    }else{
      $response = array(
        'status' => false,
        'message' => $conn->errno
      );
    }
    echo json_encode($response);
 }

Javascript

<script type="text/javascript">
$(document).ready(function(){
  // catch click
  $('.mlButton').click(function(){
  var el = this;
  var confirmAlert = confirm("Are you sure? This action can not be undone.");
  if (confirmAlert == true){
    // AJAX Request
    $.ajax({
         url: 'deletion.php',
         type: 'POST',
         data: {
           ID: $(this).val()
          },
         success: function(response){
          console.log( response );
          if (response.status) {
            toastr.success(response.message);
            el.closest('tr').css('background','tomato');
            el.closest('tr').fadeOut(800,function(){
            $(this).remove();
          });
          }else{
          toastr.error(response.message);
            }
          }
        });
      }
    });
  });  
</script>

In the console and network response tab, I am getting the correct status and message response, with status = true and message = Your listing was deleted successfully

Cesium – label above billboard don’t show properly in entity, it become darker

I need label above billboard image. The label color is white, But it become dark.
Here is code. disableDepthTestDistance seems necessary.

viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(item.coordinates[0], item.coordinates[1]),
      show: true,
      label: {
        text:  'spring',
        fillColor: Cesium.Color.WHITE,
        showBackground: false,            
        style: Cesium.LabelStyle.FILL,     
        show: true,
        scale: 0.4,
        disableDepthTestDistance: Number.POSITIVE_INFINITY 
      },
      billboard: {
        image: mapLabelBg,
        width: 150,
        height: 150,
        scale: 0.5,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
       },
  });

You can see label `spring` is not pure white. it's dark. I don't add opacity to label.
How can i make label 100% white?

enter image description here

Chrome WebUSB controlTransferOut Results in “Transfer failed: A device attached to the system is not functioning. (0x1F)”

I’m developing a consumer USB device that will be configured via a web interface.

The first interface is a HID Gamepad. The second is a vendor interface where configuration will be handled.

Running this WebUSB code, I get the following error:

async () => {
  try {
    let device = await navigator.usb.requestDevice();

    await device.open();
    await device.selectConfiguration(1);
    await device.claimInterface(1);
    await device.controlTransferOut({ // ERROR OCCURS AT THIS LINE!
      requestType: "vendor",
      recipient: "interface",
      request: 0x01,
      value: 0x01,
      index: 0x01,
    });
    const dataToSend = new ArrayBuffer(8);
    dataToSend[0] = 2;
    let result = await device.transferOut(4, dataToSend);

    const decoder = new TextDecoder();
    console.log("Received: " + decoder.decode(result.data));
  } catch (error) {
    console.error(error);
  }

Which outputs DOMException: A transfer error has occurred.

Checking the Chrome device logs, I see this in chrome://device-log/:

[22:21:07] Transfer failed: A device attached to the system is not functioning. (0x1F)

A side note: I’m almost certain this code was working 6 months ago and I recall vaguely that it may have had to do with this next part (specifically the “driver”:)

[22:15:57] USB device added: path=\?usb#vid_0f0d&pid_00cc#a&33dbaa40&1&1#{a5dcbf10-6530-11d2-901f-00c04fb951ed} vendor=3853 "keyboard.gg", product=204 "Edgeguard", serial="", driver="usbccgp", guid=c240342b-ed28-41aa-a8c9-bc505467059e

Chrome Device Log

First red flag to me is that the device is using driver="usbccgp" – I was expecting to see WinUsb. Using a tool called Zadig, I can see that the first interface is not WCID, but the second is (please note: I did not manually change either of these, this is what they are detected as by Windows.)

Zadig showing a non-WCID first interface
Zadig showing a non-WCID second interface

My memory is fuzzy, but I think that this transfer may be failing because Chrome is adding the device with a usbccgp driver. Any advice would be appreciated.

TypeError: CreateListFromArrayLike called on non-object

am getting a list of more than 1000 numbers from an api and past it to variable called number, i want to get the highest number am getting from the api, this is the Error am gettiing TypeError: CreateListFromArrayLike called on non-object. please i don’t know what am doing wrong can someone please help out.

this is my code

function CryptoTopGain ({number}){
      let highPercent = Math.max.apply(null, percent);
     console.log(highPercent )
 }

I want to get only roleId of those data that satisfies the condition (resourceId==3 && canView);

I have this set of data:

roles = [{roleId:1,resourceRole:[
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId=1},
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId=2},
{canAdd:false,canUpdate:false,canView:false,canDelete:false,resourceId=3}
]},
{roleId:2,resourceRole:[
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId=1},
{canAdd:false,canUpdate:false,canView:false,canDelete:false,resourceId=2},
{canAdd:false,canUpdate:false,canView:false,canDelete:false,resourceId=3}
]},
{roleId:3,resourceRole:[
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId=1},
{canAdd:false,canUpdate:false,canView:false,canDelete:false,resourceId=2},
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId=3}
]}
];

In this case, my output should be [1,3] because resourceId==3 && canView==true is only in the data with roleId 1 and 3. How can I get this with minimum complexity?

On Click Show/Hide Multiple Divs With The Same Class Name

I’m building a “recent stories” section on a website (img sample attached). The section has different categories (blog, video, stories). Currently, the divs all show, but I want to add some buttons that, when clicked, only show the divs labeled for that category.

So if when I add the button that says “Blog” and it is clicked, then all of the divs that are labeled as “blog” posts will show and all others will hide.

I think I could do this with simply adding/removing a class, but everything I find only shows “getElementsById” but it won’t work because there will be multiple divs that have the same class, not an Id and I don’t want to do different Ids for everything div on there.

Is there a way to make it so when a button is clicked that it only shows the divs marked as specific categories?
enter image description here

Registration form using React

Someone please help me in making this code or if you have any in github or somewhere please suggest me i need this assignment to be done for my job i am a fresher and so i am too confused in this so some help will be helpfull if you just tell me how to send form data to another page and how to preview the uploaded file in our webpage rest i will try if you guys can help please.
I’ve searched on google but i just found class method in react which is confusing me because i learnt react recently and now function based method is used so i am getting too confused in this and maybe little bit nervous about job because it’s my first.

All implementation will be in a fresh new React project and use only bootstrap styling features (No any third party
libraries).

  1. Create a Registration form
  2. Submit it
  3. Show the submitted form details on new page
    Fields in the registration form will be decided by you. You just need to think how many fields you can insert to get
    good amount of information from user.

Registration page will be divided into multiple tabs –

  1. Personal Details
  2. Academic Details
  3. Work Experience
  4. Upload Profile Photo

Form should contain –
a. Radio Button
b. Single select dropdown
c. Multi-select dropdown
d. Search ability in dropdown
e. Mobile number with country code dropdown
f. Under Address Section, after selection of Country, State dropdown will be enabled till then it should be
disabled.

Same for state if state selected then District dropdown will be enabled.
Validations –
a. Mobile Number should not be greater than 10 digits for INDIA
b. Email address validations
c. Password and confirm password validations
d. Required fields validations
e. PIN Code number validation
f. Profile Pic size should not be greater than 1MB
Not mandatory feature but it will be a plus if implemented: If current tab data has been validated successfully then it
should move to next tab till then next tabs should be disabled.

Two dimensional array iteration problem, one ghost element created

I want to create a two dimensional containing arrays of length <=3. This should be dynamically filled with the following function:

  let preppedArray = []
  let currIndex = -1
  let innerIndex = 0
  for (let i = 0; i < props.children.length; i++) {
    if (i%3 === 0) {
      currIndex++
      innerIndex = 0
      preppedArray.push ([currIndex,"dummy"])
      let currElement = props.children[i]
      preppedArray[currIndex][innerIndex] = currElement
    } else{
      innerIndex++
      preppedArray[currIndex][innerIndex] = props.children[i]
    }
  }

Oddly, the following is the output:

Array(3) [ (3) […], (3) […], (2) […] ]
​
0: Array(3) [ {…}, {…}, {…} ]
​​
0: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
1: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
2: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
length: 3
​​
<prototype>: Array []
​
1: Array(3) [ {…}, {…}, {…} ]
​​
0: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
1: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
2: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
length: 3
​​
<prototype>: Array []
​
2: Array [ {…}, "dummy" ]
​​
0: Object { "$$typeof": Symbol("react.element"), type: Card(props)
, key: null, … }
​​
1: "dummy"
​​
length: 2
​​
<prototype>: Array []
​
length: 3
​
<prototype>: Array []

It looks as though the algorithm creates one “ghost” dummy element at the end. However, I do not comprehend why or how to fix it. Many thanks in advance!

How Jest Mock Function

Could someone help me because the following test failed? I’m trying to mock a function (isAlive) that is used inside another (filterCharacter)

utils/index.js


    import { isAlive } from './is-alive';
    
    export const filterCharacter = (characters, name) =>
    characters.filter((char) => char && char.name.includes(name) && isAlive(char.alive));

utils/is-alive.js


    export function isAlive() {
      return true;
    }

my test:


    import { filterCharacter } from './index';
    import { isAlive } from './is-alive';
    
    jest.mock('./is-alive', () => ({ isAlive: jest.fn(() => true) }));
    
    const mockCharacters = [
      { name: 'anakin skywalker', nickname: 'darth vader', alive: true },
      { name: 'leia organa', alive: false },
      { name: 'luke skywalker', alive: false },
      { name: 'r2-d2', alive: true },
      { name: 'c3po', alive: true },
    ];
    
    describe('filterCharacter', () => {
      it('filtra uma lista de personagens por um determinado nome e verifica se o personagem está vivo', () => {
        const resultado = filterCharacter(mockCharacters, 'skywalker');
        const esperado = 2;
    
        expect(resultado.length).toEqual(esperado);
        expect(isAlive).toHaveBeenCalledTimes(mockCharacters.length);
      });
    });

teste result error:


    expect(received).toEqual(expected) // deep equality
    
    Expected: 2
    Received: 0

eventlistener not functioning when post request is sent

I am trying to add a number indicator to my cart icon that will display the number of items added after the product has been saved to my database.

<div class="main__section-content">
               <% if( allProd.length > 0 ) {%>

                <% for(product of allProd){%>
                    <article class="main__section-card">
                        <img src="<%= product.imageUrl %>" alt="<%= product.title %>" class="card-img">
                        <section class="card-container">
                            <h4><%= product.title %> </h4>
                            <p>$ <%= product.price %></p>
                            <form action="/cart" method="post" class="card-form">
                                <input type="hidden" name="productId" value="<%= product._id %>">
                                <button class="card-btn" type="submit" >Add to cart</button>
                            </form>
                        </section>
                    </article>
                    <%} %>
                <%} %>
            </div>

I am trying to attach an eventlistener to all

Add to cart button

 const addToCartBtn = document.querySelectorAll('.card-btn');
    addToCartBtn.forEach(btn => {
        btn.addEventListener('submit', ()=>{
            console.log('btn');
        })
    });

nothing comes out of the console before the post request is sent.

this is how i handle the post request

exports.postCart = (req, res) => {
    const prodId = req.body.productId;
    Product.findById(prodId)
    .then(product =>{
        return req.user.addToCart(product);
    })
    .then(result => {
        console.log(result);
        res.redirect('/')
    }).catch(err => console.log(err));
};

please help!