Simple Reactgrid starter project is throwing a “t is undefined” error upon cell edit

Would appreciate if someone could help me solve this. I’m using React 18.2/Typescript, and I’ve just installed Silevis/Reactgrid. The grid loads, but it keeps throwing me a “t is undefined” error when I double click on the cell to edit it. I don’t know if its a React 18.2 version problem, because I had to install Silevis/Reactgrid using the –legacy-peers-deps flag.

The starter code I used is from here : https://reactgrid.com/docs/4.0/1-getting-started/ , I’ve pasted it below as well.

import * as React from "react";
import { render } from "react-dom";
import { ReactGrid, Column, Row } from "@silevis/reactgrid";
import "@silevis/reactgrid/styles.css";
import "./styles.css";

interface Person {
  name: string;
  surname: string;
}

const getPeople = (): Person[] => [
  { name: "Thomas", surname: "Goldman" },
  { name: "Susie", surname: "Quattro" },
  { name: "", surname: "" }
];

const getColumns = (): Column[] => [
  { columnId: "name", width: 150 },
  { columnId: "surname", width: 150 }
];

const headerRow: Row = {
  rowId: "header",
  cells: [
    { type: "header", text: "Name" },
    { type: "header", text: "Surname" }
  ]
};

const getRows = (people: Person[]): Row[] => [
  headerRow,
  ...people.map<Row>((person, idx) => ({
    rowId: idx,
    cells: [
      { type: "text", text: person.name },
      { type: "text", text: person.surname }
    ]
  }))
];

function App() {
  const [people] = React.useState<Person[]>(getPeople());

  const rows = getRows(people);
  const columns = getColumns();

  return <ReactGrid rows={rows} columns={columns} />;
}

render(<App />, document.getElementById("root"));

The detailed error that shows is :

Ml@http://localhost:3000/static/js/bundle.js:9899:11 updateReducer@http://localhost:3000/static/js/bundle.js:34126:26 useReducer@http://localhost:3000/static/js/bundle.js:35337:20 useReducer@http://localhost:3000/static/js/bundle.js:50736:25 Al@http://localhost:3000/static/js/bundle.js:9923:46 renderWithHooks@http://localhost:3000/static/js/bundle.js:33775:31 updateFunctionComponent@http://localhost:3000/static/js/bundle.js:36975:24 beginWork@http://localhost:3000/static/js/bundle.js:38922:20 beginWork$1@http://localhost:3000/static/js/bundle.js:44670:18 performUnitOfWork@http://localhost:3000/static/js/bundle.js:43828:16 workLoopSync@http://localhost:3000/static/js/bundle.js:43741:26 renderRootSync@http://localhost:3000/static/js/bundle.js:43710:11 recoverFromConcurrentError@http://localhost:3000/static/js/bundle.js:43118:38 performConcurrentWorkOnRoot@http://localhost:3000/static/js/bundle.js:43019:26 workLoop@http://localhost:3000/static/js/bundle.js:52137:46 flushWork@http://localhost:3000/static/js/bundle.js:52111:18 performWorkUntilDeadline@http://localhost:3000/static/js/bundle.js:52395:25 Al@http://localhost:3000/static/js/bundle.js:9919:11 div div n@http://localhost:3000/static/js/bundle.js:10032:29 Dl@http://localhost:3000/static/js/bundle.js:10056:11 ya@http://localhost:3000/static/js/bundle.js:8328:11 n@http://localhost:3000/static/js/bundle.js:8884:29 App@http://localhost:3000/static/js/bundle.js:75:66

Animation breaks when trying to change the color of the loaded model THREE.js

I have a model with animation from Blender. When I upload it to the site, everything is ok, the animation works. I want to change the body color of the model, but when I try to do this, the body stops perceiving the animation and becomes static. The rest of the elements continue to animate. I can’t figure out where the error is, please help!

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
const gltfLoader = new GLTFLoader()

let mixer = null;

gltfLoader.load(
'models/bot/model.glb',
(gltf) => {
    gltf.scene.traverse((child) => {
        if(child instanceof THREE.Mesh && child.material instanceof THREE.MeshStandardMaterial){
            if(child.name === 'Body'){
                child.material =  new THREE.MeshStandardMaterial( { color: 'red', wireframe: true } );
                child.material.needsUpdate = true
            }
        }
    })

    mixer = new THREE.AnimationMixer(gltf.scene);
    const action = mixer.clipAction(gltf.animations[1])

    action.play()

    scene.add(gltf.scene)
}
)

//Animation

const clock = new THREE.Clock()
let previousTime = 0


const tick = () =>
{
const elapsedTime = clock.getElapsedTime()
const deltaTime = elapsedTime - previousTime
previousTime = elapsedTime

mixer && mixer.update(deltaTime)

// Update controls
controls.update()

// Render
renderer.render(scene, camera)

// Call tick again on the next frame
window.requestAnimationFrame(tick)
}

tick()

How to loop through item card checkboxes with same id? (Javacsript/ JQuery)

Good day everyone, I am not sure how can I loop through multiple item card with 2 checkboxes of the same ID (within each card).

Currently my main issue is that whenever my code meets a specific condition, it only renders the first item card checkboxes as the id points to it.

I need the checkboxes to render accordingly to the key value pairs that are uniquely stored in the local storage. I am not sure how I can loop through this? Can somebody help me on this? Thank you 🙂

Html Code:

      <form class="g-item-title" style="color: #005e95">
        <input type="radio" id="checkboxPartialDownload" data-dojo-attach-event="onClick: _test" style="cursor: pointer;" name="downloadValue" value="partialDownload" class="classPartialDownload" checked>
        Allow Partial Download
        <br>
        <input type="radio" id="checkboxFullDownload" data-dojo-attach-event="onClick: _onclickTest" style="cursor: pointer;" name="downloadValue" value="fullDownload" class="classFullDownload">
        Allow Partial + Full Download
      </form>

JS Code that renders when page loads:

      render: function (hit) {
 
        let dataTitle = hit.sort[0];
        let dataid = hit._source.fileid;

        $("input[type='radio'][name='downloadValue']:checked").each(function(){

          if(localStorage.getItem(`${dataTitle}`) === "FullDownload"){
            var value=$(this).attr('value');
           
            if(value ==='partialDownload'){
             $('#checkboxPartialDownload').prop('checked', false); //Only renders the first item checkboxes.. 
             $('#checkboxFullDownload').prop('checked', true);
            }
           }
        })
        

On click function that saves the key value pair to local storage:

    _onclickTest:function(evt){
        let title = this.item.title;
        let fileid = this.item.fileid
        localStorage.setItem(`${title}`,'FullDownload')
      }

How to use regular expressions to match and replace more complex html tag?

How can I use regular expressions to match all tags with a style attribute and a color value, then extract their color value and replace the tag with <color=color value>content, please help me, thank you

//original tag
// <p style="color:#ffffff;">content</p>
// <span style="color:#ffffff;">content</p>
// <i style="color:#ffffff;">content</p>
//...


// expect replace tag
//<color=#ffffff>content</color>

avoid enormous network payloads

Hi I have a Vue project and I’m trying to improve the performance. I used Lighthouse to run a performance test and one of the suggestions is I have to avoid enormous network payloads. I looked at it and there are many js files with the name of my webpackChunkName (from router) but combined and separated with the symbol ~. For example
/js/usersetting~dashboard~settings~productsettings~userpr….js. There are a few JS files like this. I wonder what these are and is there anything I can do to reduce or remove (I don’t know) these? Appreciate any help, thank you.

API call returns a promise instead of data, inside react component

I am really struggling to wrap my head around async api calls.
I am trying to render some data from an api call in my react application. The structure is as follow:
Essentially, my thought process is that I am using fetchYearlyData to return the data from an api call.
Then that data is processed in percentileRank to return a value.
The main function calls the fetchYearlyData and percentileRank function in order.

const fetchYearlyData = async (year, stat) => {
 let response = await fetch(
 `http://localhost:5000/api/yearly_data/${year}/${stat}`
  );
 return response.json();
};
const percentileRank = (data, stat, percentile) => {
 data = data.map((item) => {
 return parseFloat(item[stat]);
  });
 let sortedArray = data.sort((a, b) => a - b);
 let rank = Math.floor((percentile / 100) * (sortedArray.length + 1));
 return sortedArray[rank];
};
export const main = async (year, stat, rank) => {
 // Make API Call
 let data = await fetchYearlyData(year, stat);
 // Return data array
 return percentileRank(data, stat, rank);
};

So far there are no issues.

But when I try and bring this into my react component for graphing purposes, I seem to be getting the data back as a promise instead of actual values, which prevents the graph from forming.

const data = {
 labels,
 datasets: [
      {
 label: "25th percentile",
 data: labels.map(async (year) => {
 let result = await main(year, props.statSelection, 25);

 return result;
        }),
      },
    ],
  };

return (
 <div id="chart">
 <Line options={options} data={data} />
 </div>
  );

I am completely lost, in that I am using async and await and still keep seeing promises, which is very frustrating. I would forever be in your debt if someone could explain this to me 🙂

Thanks!

Passing Class as Props in React

I have a Component that has a child component. I want to pass a class to the child component as a props, then use the properties of that class in the child component. For some reason I can only pass properties of the class to the child component, rather than the entire class. How do I pass the entire class, then use the properties of the class in the child component? :

    export class Video {
    constructor(title, time, userProfilePicPath, videoPicPath){
        this.title = title;
        this.time = time;
        this.userProfilePicPath = userProfilePicPath;
        this.videoPicPath = videoPicPath;

    }
}



import React from 'react';
import "../../styles/styles.css";
import { StyledGrid, StyledItem, StyledItemImage, StyledProfileImage, StyledTitleBox, StyledVideoTitle, StyledVideoTitleInfoBox, StyledVideoTime } from "./GridLayout.styled";
import my_img from "../../assets/img/IMG_3709.jpeg";
import profileImg from "../../assets/img/ProfilePicSample.jpeg";
import { bool, fun } from 'prop-types';
import { Video }  from "../../store/Video";


const video1 = new Video("First Video", "1:00:00" , profileImg, my_img);

const GridLayout = ({ open }) => {
    const video = video1;

    return (
        <div>
        
        <StyledGrid open={ open }>
          <VideoItem thisVideo={video}></VideoItem>    
          <VideoItem></VideoItem>
          <VideoItem></VideoItem>
          <VideoItem></VideoItem>
          <VideoItem></VideoItem>
          <VideoItem></VideoItem>
          <VideoItem></VideoItem>
          <VideoItem></VideoItem>
          <VideoItem></VideoItem>
        </StyledGrid>
        </div>
    )
};
GridLayout.proptype = {
    open: bool.isRequired,
};

const VideoItem = ( props ) => {
    const videoImage = props.thisVideo.videoPicPath;
    return(
        <StyledItem>
            <StyledItemImage src={videoImage}/> 
            <StyledTitleBox>
                    <StyledProfileImage src={ profileImg }/>                                            
                    <TitleInfo/>                                                                                    
            </StyledTitleBox>                
        </StyledItem>
    )
};

export default GridLayout;


const TitleInfo = ( props ) => {
    const videoTitle = "A Title";
    const videoTime = "The Time";
    return(
        <div>
            <StyledVideoTitle>{videoTitle}</StyledVideoTitle>                                                   
            <StyledVideoTime>{videoTime}</StyledVideoTime> 
        </div>
    )
};

Here is the error:

bundle.js:475 Uncaught TypeError: Cannot read properties of undefined (reading 'videoPicPath')
    at VideoItem (bundle.js:475:38)
    at renderWithHooks (bundle.js:27030:22)
    at mountIndeterminateComponent (bundle.js:30695:17)
    at beginWork (bundle.js:32163:20)
    at HTMLUnknownElement.callCallback (bundle.js:14826:18)
    at Object.invokeGuardedCallbackDev (bundle.js:14875:20)
    at invokeGuardedCallback (bundle.js:14937:35)
    at beginWork$1 (bundle.js:37950:11)
    at performUnitOfWork (bundle.js:37083:16)
    at workLoopSync (bundle.js:36996:9)

How can I get this variable passed to another file?

I am trying to pass the client value to another file.

I am using express to create a web server that works with my discord bot, and want to do something on a post request to an endpoint.
When the endpoint receives a post request with a user id, the bot should send them a message.

// index.js

const client = new Client(etc etc);
const routes = require('./routes.js');
https.createServer(options, app).listen(PORT, function() {
    console.log('Express server listening on port ' + PORT);
});
app.use(bodyParser.json(), routes, limiter);

client.login(token).then(console.info('Logged in.'));
module.exports = { client };

In the index.js file, the server is created, along with various other command handling things that are unrelated.

// routes.js

const express = require('express');
const router = express.Router();
const { invite, topggAuth } = require('./config.json');
const client = require('./index.js');
const vote = require('./events/vote.js');
router.route('/api/tggwh').post((req, res) => {
    if (req.header('authorization') === topggAuth) {
        vote.execute(client, req.body);
        res.status(200).end();
    }
    else {
        console.log('Unauthorized vote request attempt.');
        res.send('Unauthorized');
        res.status(401).end();
    }
});

Routing seems to work fine, it matches the auth header to the key in the config file, then moves on to the vote handler.

// vote.js

const { logUsage } = require('../functions.js');

try {
    const targetUser = await client.users.cache.get(data.user); // this is line 7, column 42 is between the e and the n in client
    await targetUser.send('Thank you for voting!');
    logUsage({ name: 'vote' });
}
catch (error) {
    console.error('Whoops! Something went wrong while thanking a vote.');
    console.error(error);
}

This is where the error comes in.

TypeError: Cannot read properties of undefined (reading 'cache')
    at Object.execute (/home/ubuntu/Harold/events/vote.js:7:42)
    at /home/ubuntu/Harold/routes.js:43:8
    at Layer.handle [as handle_request] (/home/ubuntu/Harold/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/ubuntu/Harold/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch (/home/ubuntu/Harold/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] (/home/ubuntu/Harold/node_modules/express/lib/router/layer.js:95:5)
    at /home/ubuntu/Harold/node_modules/express/lib/router/index.js:284:15
    at Function.process_params (/home/ubuntu/Harold/node_modules/express/lib/router/index.js:346:12)
    at next (/home/ubuntu/Harold/node_modules/express/lib/router/index.js:280:10)
    at Function.handle (/home/ubuntu/Harold/node_modules/express/lib/router/index.js:175:3)

I think this means that client is passed through, but client.users is not.
How can I pass client through to vote.js after its been called by the post request?

angular mat radio check if value changes

is there an event for a mat radio group where we can detect if a value changes ? cause I wanna trigger a method or a function only if select value from the radio changes.

So for example I click botton A and the value is 0 and then i click button A again then it should return false since the value did not change.

#html

<mat-radio-group (change)="onChange($event)">
  <mat-radio-button [value]="0">BUTTON A</mat-radio-button>
  <mat-radio-button [value]="1">BUTTON B</mat-radio-button>
</mat-radio-group>

#tscode

export class Something {

        selectedValue: number;
        onChange(event: MatRadioChange) {
          this.selectedValue = event.value;
          // call this method when value changes
          // this.triggerMethod()
        }
      }

MediaRecorder API gets undefined after X amount of time — Javascript/ReactJs

i’m trying to record the user voice in ReactJs using the MediaRecorder browser API.
the declaration of “audioRecording” is outside of “startRecordingAudio()” because i need the user to choose when to stop recording, so “stopRecordingAudio()” must be able to reach “audioRecording.stop()”.

Everything works fine for audios between 00:00-00:59 seconds, but when i try to leave it for a long time like 3-6 mins, suddenly “audioRecording” becomes undefined.

That’s the code:

// Audio Recording
const audioData = [];
let audioRecording;


function startRecodingAudio() {

    // Start Recording
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => {
            // Defining the recorder
            audioRecording = new MediaRecorder(stream);

            audioRecording.ondataavailable = e => {
                audioData.push(e.data);
                // Pushing the data to the array
            };

            // Start recording
            audioRecording.start();
            console.log('Gravando...');
            
            // when recording stop, save audio file
            audioRecording.onstop = () => {
                console.log('Parei gravação. Salvando audio...')
                setIsRecording(false);
                const audioBlob = new Blob(audioData, { type: 'audio/wav' });
                const audioReader = new FileReader();
                audioReader.readAsDataURL(audioBlob);
                audioReader.onloadend = () => {
                    setAudioFile(audioReader.result);
                    console.log('setei audio');


                }
            }
        }).catch(err => {
            console.log(err)
        });

}
// Stop audio recording
function stopRecordingAudio() {
    audioRecording.stop();
}

I’m Starting and Stoping this way:

<div>
        <div>
            Play/Stop
        </div>
        <div>
            <button type='button' onClick={startRecodingAudio}>Record</button>
            <button type='button' onClick={stopRecordingAudio}>Cancelar</button>
            <button type='button' onClick={() => console.log(audioRecording)}>Check State</button>
        </div>
    </div>

I started the recording and manually logging the audioRecording variable:
Console print that shows the mediaRecorder suddenly getting undefined.

This problem also occurs if set some State after the recording, but in this case it doesn’t even last 1 second.
Like this:

function startRecodingAudio() {

    // Start Recording
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => {
            // Defining the recorder
            audioRecording = new MediaRecorder(stream);

            audioRecording.ondataavailable = e => {
                audioData.push(e.data);
                // Pushing the data to the array
            };

            // Start recording
            audioRecording.start();
            setIsRecording(true);
            console.log('Gravando...');

            // when recording stop, save audio file
            audioRecording.onstop = () => {
                console.log('Parei gravação. Salvando audio...')
                setIsRecording(false);
                const audioBlob = new Blob(audioData, { type: 'audio/wav' });
                const audioReader = new FileReader();
                audioReader.readAsDataURL(audioBlob);
                audioReader.onloadend = () => {
                    setAudioFile(audioReader.result);
                    console.log('setei audio');


                }
            }
        }).catch(err => {
            console.log(err)
        });

}

Does anyone have any idea on what could it be?
I would really appreciate it.

Nodemon error while running a ReadMe generator

Working on an assignment to write a ReadMe Generator,

but when I put in npm start I get the following error:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a ‘.js’ file extension and ‘C:UsersFrancoDesktopReadme-Generatorpackage.json’ contains “type”: “module”. To treat it as a CommonJS script, rename it to use the ‘.cjs’ file extension.

This isn't code but Stack overflow is dumb sometimes 

at file:///C:/Users/Franco/Desktop/Readme-Generator/index.js:1:18
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:61:12)
[nodemon] app crashed - waiting for file changes before starting...

Here is my actual code for context


    const inquirer = require('inquirer')
    
    const questions = [
        {
            type: 'input',
            name: 'title',
            message: 'What is your project called?',
        },
        {
            type: 'input',
            name: 'description',
            message: 'Please descbribe your project',
        },
        {
            type: 'input',
            name: 'installation',
            message: 'Describe how you install the project here',
        },
        {
            type: 'input',
            name: 'usage',
            message: 'how is your project used?',
        },
        {
            type: 'input',
            name: 'contribution',
            message: 'who contributed?',
        },
        {
            type: 'input',
            name: 'test',
            message: 'any tests?',
        },
        {
            type: 'input',
            name: 'email',
            message: 'What is your email address?',
        },
        {
            type: 'input',
            name: 'github',
            message: 'enter your github username',
        },
        {
            type: 'list',
            name: 'License',
            message: 'Choose your License',
            choices: ['MIT', 'ISC', 'GNUPlv3'],
            filter(val) {
                return val.toLowerCase();
            }
        }
    ]
    
    function runQuery() {
        return inquirer.prompt(questions)
        .then((answers) => {
            console.log(answers)
            return answers
        })
        .catch((error) => {
            console.log(error)
        })
    }
    
    runQuery

Does anyone have any idea what it could be?

Unable to do Conditional import of file in React app

I am having issues importing a JSON file depending on a process.env.WORLD value in my React Typescript app.

The JSON file can be loaded without problems when we ignore the process.env variable.

import data from '../main.json';

In my first attempt, I tried

let file;
if (process.env.WORLD == 'main') {
    file = '../main.json';
} else {
    file = '../test.json';
}

import data from file;

but got the error

Import in body of module; reorder to top  import/first

Tried using dynamic import

const data = await import(
    process.env.WORLD == 'main'
      ? '../main.json'
      : '../test.json'
  );

but my setup does not allow a top-level await

Module parse failed: Cannot use keyword 'await' outside an async function 

Tried using require instead of import

let file;
if (process.env.WORLD === 'main') {
  file = '../main.json';
} else {
  file = '../test.json';
}

const data = require(file);

but it almost works except that the file cannot be found

contexts sync:2 Uncaught Error: Cannot find module '../main.json'

Strangely, there is no problem using the same file path with import as shown in the first example in this question.


Typescript target is ES2018, and React 18 is used.

Why is the file not found when using require, and how can we solve this problem?

How load forms in modal dynamically – Python

Im trying to load forms in modal dynamically using jquery and ajax in python but when i submit the form i get the error “werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: ‘title'”
Mentioning that I recently started using jquery and ajax with python, could you help me please?
I want to reuse modal section to load multiple forms with jquery.

The code is as below.

HTML: lockbox.html

<input class="btn add" type="button" value="New">
    <!--Modal-->
    <dialog class="modal">
        <div class="modal-header">
            <h4 class="modal-title"></h4>
            <button class="close-modal">X</button>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <button class="close-modal">Cancel</button>
        </div>
    </dialog>

Javascript

$('.add').on('click', function () {
        $.ajax({
            type: "get",
            url: "/newentry",
            success: function (data) {
                $('.modal-body').html(data);
                $('.modal-header').css('background-color', '#0688fa');
                $('.modal-title').text('New register');
                $('.modal-footer').css('background-color', '#0688fa');
                modalBox.showModal();
            }
        });        
    });

Python route

@app.route('/newentry')
def newentry():
    return render_template('app/addpass.html')

HTML: addpass.html

<form method="post" class="addPass" action="/addPassReg">
    <div class="field-block">
        <label for="title">Title: </label>
        <input type="text" id="title" value="">
    </div>
    <div class="field-block">
        <label for="user">User: </label>
        <input type="text" id="user" value="">
    </div>
    <div class="field-block">
        <label for="passw">Password: </label>
        <input type="text" id="passw" value="">
    </div>
    <div class="field-block">
        <input type="submit" value="Save" class="btn save">
    </div>
</form>

Python route

@app.route('/addPassReg', methods = ['POST', 'GET'])
def addPassReg():
    #cur = mysql.connection.cursor()
    if request.method == 'POST':
        print('is post')#for debug
        print(request.args.listvalues)#trying to know the error
        titulo = request.form['title']
        user = request.form['user']
        passwd = request.form['passw']

        if title and user and passwd:
            return json.dumps({'message' : 'OK.'})
        else:
            print('After')
            return redirect(url_for('lockbox'))#json.dumps({'html' : 'Complete please.'})
    if request.method == 'GET':
        print('is get')#for debug
    else:
        print('whats up?')#for debug

    return redirect(url_for('lockbox'))

When i reuse the modal just to see data it’s ok, but for forms i realize that it doesn’t work and i don’t know if it doesn’t recognize the form data or im doing something wrong. Please help me.

Making Javascript files private in Django Project

I am following a tutorial to integrate Apple Pay payments (w/ Stripe) into my website using Javascript to process the payments. The Javascript file renders the Apple Pay Button as well as actually processing the payment.

I need to pass a secret key into one of the functions, but the file is public b/c its in my static folder.

What can I do to either make the Javascript file private or at least make some of the functions private so I don’t need to worry about hackers stealing my key from the static files?