Dynamically creating components in loop using ReactDOM.Render() not updating props on state (Keyboard input) change

I’m trying to pass keyboard events to a component that’s created multiple times in a loop using ReactDOM.render, but the updated props aren’t being sent. I realize this is because the component is being rendered once and not being updated, however my question is:

What’s the “most proper React-approved way” to push keyboard events down to a series of components rendered with ReactDOM.render?

My code – I can’t share all of it (There’s a lot of logic and part of it is private), but I rewrote it to mirror what I’m currently doing.

Successfully refreshing ViewComponent with AJAX, but FullCalendar is not rendering with new ViewComponent

I’ve implemented a FullCalendar as a View Component in my ASP.NET Core web app.
This calendar contains open time slots where ever appointments aren’t scheduled.

Now I want to be able to filter time slots by duration; for instance, the default time slot is set at 15 minute intervals but users can change this to 30, 45, 60, etc.
Whenever a user changes this duration, a function is called in JS where I make an AJAX request:

$('#AppointmentDuration').on('change', function(){
        $.ajax({
            type: "GET",
            url: "Sample/RefreshViewComponent",
            data: {
                "ProviderId": $('#ProviderFilter').val(),
                "AppointmentDuration": $('#AppointmentDuration').val()
            },
            success: function (data) {
                console.log(data);
                $('#ViewComponent').html(data);
            }              
        });
    });

After this, I am successfully able to view the new ViewComponent in the console (which is essentially the exact same html, but with different time slots/moments/events for the Calendar based on the duration selected). The page also re-renders after replacing the html of #ViewComponent with the new ViewComponent, but my FullCalendar no longer appears.

Anyone know why this is?
I’ve tried all these actions:

    $('#calendar').fullCalendar('destroy');
    $('#calendar').fullCalendar('removeElements');
    $('#calendar').fullCalendar('addEventSource', eventsObj);
    $('#calendar').fullCalendar('refetchEvents');

Any advice would be appreciated!
Thank you

Long, additional network calls after performing Firebase Firestore query?

My web application performs the following Firebase Firestore query:

<script defer src="/__/firebase/9.6.5/firebase-app-compat.js"></script>
<script defer src="/__/firebase/9.6.5/firebase-firestore-compat.js"></script>
<script defer src="/__/firebase/9.6.5/firebase-storage-compat.js"></script>
<script defer src="/__/firebase/9.6.5/firebase-analytics-compat.js"></script>
<script defer src="/__/firebase/init.js?useEmulator=false"></script>
<script>
      document.addEventListener('DOMContentLoaded', function() {
        firebase.firestore().collection("users").where("username", "==", username).limit(1)
            .get()
            .then((querySnapshot) => {
                //…
            })
            .catch((error) => {
                //…
            });
      });
</script>

The single query results in 3 network calls:
network call size and duration

The first call is the query request written explicitly in my code snippet.
The third call contains “removeTarget”:2 in the payload.

My biggest concern is this second call below that takes 1 minute to execute, sometimes being several Kilobytes in size:

https://firestore.googleapis.com/google.firestore.v1.Firestore/Listen/channel
?database=projects%2F<omitted>%2Fdatabases%2F(default)
&gsessionid=<omitted>
&VER=8
&RID=<omitted>
&SID=<omitted>
&CI=0
&AID=0
&TYPE=xmlhttp
&zx=<omitted>
&t=1

The GET response was an empty 200 with the following duration:

network call duration

What are these second and third calls? I am especially interested in what the second call is given the duration and size of the call.

how do I get contents of another file within a file

i’m confused on how I get contents from /posts in my /blogs route. Can someone explain what I supposed to do? The /blog route is supposed to return a JSON formatted string containing all of the posts within the posts.json file whose published property is set to true (ie: “published” posts).

server.js

app.get("/blog", (req, res) => {
    blogservice.getPublishedPosts().then((data) => {
        res.json({data});
    }).catch((err) => {
        res.json({message: err});
    })
});

app.get("/posts", (req, res) => {
    blogservice.getAllPosts().then((data) => {
        res.json({data});
    }).catch((err) => {
        res.json({message: err});
    })
});

blog-service.js

exports.getPublishedPosts = () => {
    return new Promise ((resolve, reject) => {
        var PublishedPosts = posts.filter(posts => posts.isPublished == true);
        if (PublishedPosts.length == 0) {
            reject('no results returned');
        }
        resolve(PublishedPosts);
    })
};

Checkbox checked, javascript in Django template

I am just trying to display hiddens items in django template when checkbox is checked, but in my console i am getting

1:194 Uncaught TypeError: Cannot read properties of null (reading 'checked')
    at inventoryFunction (1:194:22)
    at HTMLInputElement.onclick (1:107:73)

the items are hidden in a table and when i check a category i am hoping to get them displayed
here is the template :

<div class="inventory-content">
    <div class='category'>
        <div>Categories</div>
        <div class='category-checkbox'>
            {%for category in categories%}
            <input type="checkbox" id="{{category.id}}" onclick="inventoryFunction()">
            <label for="{{category.id}}"> {{category.name}}</label><br>
            {%endfor%}
        </div>
    </div>
    <div class='items'>
        {% for category in items%}
        <div class='{{category.id}}' style="display:none">
            <div>{{category}}</div>
            <table class='runninghours-table'>
                <tr>
                    <th>Item name</th>
                    <th>part number</th>
                    <th>R.O.B</th>
                </tr>
                <tbody>
                    {%for item in category.items.all%}
                    <tr>
                        <td>{{item.name}}</td>
                        <td>{{item.part_number}}</td>
                        <td>{{item.ROB}}</td>
                    </tr>
                    {%endfor%}
                    </tobdy>
            </table>
        </div>
        {%endfor%}
    </div>

</div>

the JavaScript :

<script>
    function inventoryFunction() {
        var checkBox = document.getElementById("{{category.id}}");
        var item = document.getElementsByClassName("{{category.id}}");
        if (checkBox.checked == true) {
            item.style.display = "block";
        } else {
            item.style.display = "none";
        }
    }
</script>

Can’t get .then to happen after promised timeout is finished in JavaScript [duplicate]

Hey, i am trying to return this console after 1000 milli sec using this promise, but for some reason it consoles before ending the setTime out. Any idea how I can get the console.log to happen after the timeOutPromise is finished?

const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });

const thisPromise = (num1, num2) => new Promise((resolve, reject) => {
  timeOutPromise()
    .then(resolve(console.log(num1 + num2)))
    .catch(reject(Error));
});

thisPromise(1, 2);

Filter multiple tables using query string with javascript

first I’m sorry if at some point I express myself badly, English is not my native language. I am developing an application in which the user sends 2 values through a form and in another page I use one of those data (string with comma separated options) to show a specific table and hide the others, and with the second data (Integer) I show one of the rows of that table.

What I already have:
I have the form and send the data through the Query String, I capture that data, I assign a variable to the integer and to the text string I separate it by commas and create an array.

URL Example: app.tables.example/?id=123&ops=option1%2c+option2

//Read parameters sent by form
const param = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) => searchParams.get(prop)
});

//Assign integer to a variable
let num = param.id;

//Assign options to a variable
let op = param.ops;

//Separate string with commas
let opsplit = op.split(',');

Up to here everything is perfect, I can print all the variables without any problem, now I need to compare the array with the id of each table, show the one that corresponds and hide the others. (The id of the tables is the same that user passes with the text string).

The tables look something like this:

<div id="option1" class="table-1">
<table width="100%">
<thead>
<tr>
<th align="left">Option1</th>
<th align="left">Integer</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">Number</td>
<td align="left">Info</td>
</tr>
<tr>
<td align="left">1</td>
<td align="left">textblock</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">textblock</td>
</tr>
</tbody>
</table>
</div>

//As you can see the id of each table corresponds to what the user chose
<div id="option2" class="table-1">
<table width="100%">
<thead>
<tr>
<th align="left">Option2</th>
<th align="left">Integer</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">Number</td>
<td align="left">Info</td>
</tr>
<tr>
<td align="left">1</td>
<td align="left">textblock</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">textblock</td>
</tr>
</tbody>
</table>
</div>

The problem:
I’m supposed to use the array elements in a “for” loop and compare them with the id of each table, then show that table and hide others, but I don’t know exactly how to do it.

function myFunction() {
  var input, filter, table, tr, td, i, y, txtValue;
for (r = 0; r<opsplit.lenght; r++){
  input = opsplit[r];
  filter = function(x){
    return x.toUpperCase();
  };  
  opsplit = opsplit.map(filter);
  }

//When I test this, it does not return any value, no matter if I add "innerHTML" or not
  for(y = 0; y<opsplit.lenght; y++){
    table = document.getElementById('opsplit[y]').innerHTML;
 
//I use this section to test, basically it should show me the row, but since the previous loop failed, it does nothing. What I really need is to show the whole table where this data is located and hide the other tables. 
  tr = table.getElementsByTagName("tr");
  
    for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
}
myFunction();

I am really stuck at the moment and would appreciate any help. What is the correct way to use the string array, and how can I hide the tables that the user does not need?

I am facing Loop issue in DOM Manipulation, Can anyone look at it please?

I am trying to make rainbow text but I am unable to loop over, can anyone help?

This is the HTML

<body>
    <h1>
        <span>R</span>
        <span>A</span>
        <span>I</span>
        <span>N</span>
        <span>B</span>
        <span>O</span>
        <span>W</span>
    </h1>
</body>```

AND THIS IS THE JAVASCRIPT

```const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

I want to loop colors over the span using document.querySelectorAll

Sort the json of a request api

require('dotenv').config()

const URL_API = "https://api.twitter.com/2"
const params = new URLSearchParams({
    'user.fields': 'created_at',
})
const compteId = "1390171858213998593"

async function Call() {
     
    const urlParams = params.toString()
    const body = await fetch(`${URL_API}/users/${compteId}/following?max_results=20&user.fields=description`, 
    { 
        headers: {
            Authorization: `Bearer ${process.env.TOKEN}`,
        }
    }).then(res => res.json())

    for (let i = 0; i < body.data.length; i ++) {
        console.log(` ${body.data[i].username}, ${body.data[i].description}`)
      }
    
}

setInterval(Call, 3000)

hi. so I’m trying to make a program that would allow me to track down someone’s subscriptions. so the in this program I make a call to the twitter api that sends me a json file and so I enter the json format for console.log just the id and description and I what I would like it to be make a call at a certain regular time interval but that the console.log only shows me the new follows. unfortunately I don’t know how to do/ what is the method so if someone knows and would like to share I am taker.

React : Improve URL structure for SEO

I’m making a react application and to fetch pages with data I’m actually using a generated token in the URL like this http://localhost.com/a/xQ9aK2 with xQ9aK2 as the token.

Having no previous experience regarding SEO, and while the application might have a lot of pages, I was wondering if I should restructure my URL to include something like a slug, or should I just keep the actual URL and maybe use React-Router-Link with Redirect to append a slug at the end of a URL after fetching data?

OR is there anything I can do in order to improve the ranking of the pages?

React Native – Adding a new object to a state array of objects from a separate function

I’m working on trying to implement a menu ordering system on a project app. I have a foods.js file with an array of objects like so:

export const FOODS = [
    {
        id: 0,
        name: "Bagel w/ Cream Cheese",
        price: "$3.50",
        image: require("./images/coffee-stock-photo-01.jpg"),
        description: "Lorem ipsum dolor sit amet. In a nisl eu justo bibendum tempus. Donec.",
        favorite: false
    },
    {...more objects}

I have an OrderComponent.js file that looks like this:

{...other imports...}
import { FOODS } from '../shared/foods';

function RenderFood(props) {

    const {foods} = props;
    const foodList = foods.map(food => {
        return (
            <View key={food.id} style={{flexDirection: 'row', padding: 10}}>
                <Image
                    style={styles.itemImage}
                    resizeMode="cover"
                    source={food.image}
                />
                <Text style={styles.name}>
                    {food.name}
                    <Text style={styles.price}>
                        {'n' + food.price}
                    </Text>
                </Text>
                <TouchableOpacity
                    onPress={() => {
                        props.onShowModal() 
                        props.onAddButton(food)
                    }}  
                    style={{width: 60, height: 40, backgroundColor: 'white', alignSelf: center'}}>
                    <Text style={styles.addButton}>Add</Text>
                </TouchableOpacity>
            </View>
        )
    })
    return (
        <View style={{backgroundColor: '#ececec', borderWidth: 2, borderColor: '#e0e1e2', borderRadius: 5, margin: 10}}>{foodList}</View>
    )
}

class Order extends Component {
    constructor(props){
        super(props);
        this.state = {
            showModal: false,
            drinks: DRINKS,
            foods: FOODS,
            drinkList: [],
            foodList: [],
            orderArray: [{textTest:'my obj', otherTextTest:'second part of obj'}],
        };   
    }
    
    addToOrder(props){
        this.setState({orderArray: this.state.orderArray.concat(props)});
    };

    toggleModal() {
        this.setState({showModal: !this.state.showModal})
    }

    static navigationOptions = {
        title: 'Order'
    }
    
    render() {
        return (
            <ScrollView style={{backgroundColor: '#ececec'}}>
                <RenderHeader title={"Order"} />
                <View style={styles.container}>
                    <Card style={styles.orderCard}>
                        <TouchableOpacity
                            style={styles.button}
                            onPress={() => this.toggleModal()}
                        >
                            <Text>Start order</Text>
                        </TouchableOpacity>
                    </Card>
                    <Modal
                        animationType={'slide'}
                        transparent={false}
                        visible={this.state.showModal}
                        onRequestClose={() => this.toggleModal()} 
                    >
                        
                            <ScrollView>
                                <Text style={{textAlign: 'center', fontSize: 24, fontWeight: 'bold'}}>Food</Text>
                                <RenderFood 
                                    foods={this.state.foods} 
                                    onShowModal={() => this.toggleModal()}
                                    orderArray={this.state.orderArray} 
                                    onAddButton={() => this.addToOrder()}
                                />
                            </ScrollView>
                    </Modal>
                </View>
            </ScrollView>
        );
    }
}

I want to be able to pass in the food object that I am clicking the Add button on and add it to my state object for the Order. However, the first time I tap on the Add button nothing happens. Tapping a second time adds undefined to my object. If I do console.log(food) within my RenderFood function, it displays the entire object. But as soon as I pass it through props.onAddButton(food) it is undefined.

I have searched and searched but cannot figure out why this object will not pass its data through.

How do i scrape a js using python? something like https://…./static/js/main…js

i’m trying to scrape a js script of a website. It seems too confused, can’t find dictionaries or lists. What i tried to do is using requests (see example below).

lets say you want to find key:”storeRid” in an apple js file ‘https://www.apple.com/metrics/data-relay/1.1.4/scripts/data-relay.js’ (find it by using finder of the browser, you will see its dictionary-like)

how do I find that word, “storeRid” in this case, by looking for key, as an example.
Thanks

for items in jspage:
    if 'key' in items :
        print(items)

i was thinking about something as easy as this. or just as dictionaries jspage[‘key’]. No idea..

I have a problem with an injectin’ js code activity in UIPath

Some days ago, i’ve been trying to run an injection js in an activity that push a function on an input detected by its ID. The code is rigth. But when i pulled it in the activity, it doesn’t ran in the pg.
here’s my code in the UIPath’s activity.
code

What do you think that what’s the problem? Any tip? (The code is about write the date of today in another format that is required on the pg)

404 (not found) – GLF/GLTF model is not loading – Three.js, Webpack, WordPress

Console returns Failed to load resource: the server responded with a status of 404 (Not Found), Error: fetch for "http://localhost:3000/xxx/models/ToyCar.glb" responded with 404: Not Found when loading .glb file to website. Scene is loading, but model is not. Those are the only errors.

I’m using Webpack 5.68.0, Three.js and WordPress localy running on MAMP server.

I’ve downloaded 3D model from https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/ToyCar/glTF-Binary to be sure that there is no problem with it.

example.js:

import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

// Canvas
const canvas = document.querySelector('canvas.webgl')

// Scene
const scene = new THREE.Scene()

// Objects


// Materials

const material = new THREE.MeshBasicMaterial()
material.color = new THREE.Color(0xff0000)

// 3d-model
const loader = new GLTFLoader();

loader.load( 'models/ToyCar.glb', function ( gltf ) {
    console.log(glft)
    scene.add( gltf.scene );

}, undefined, function ( error ) {

    console.error( error );

} );

// Lights

const pointLight = new THREE.PointLight(0xffffff, 0.1)
pointLight.position.x = 2
pointLight.position.y = 3
pointLight.position.z = 4
scene.add(pointLight)

/**
 * Sizes
 */
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () =>
{
    // Update sizes
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight

    // Update camera
    camera.aspect = sizes.width / sizes.height
    camera.updateProjectionMatrix()

    // Update renderer
    renderer.setSize(sizes.width, sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

/**
 * Camera
 */
// Base camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
camera.position.x = 0
camera.position.y = 0
camera.position.z = 2
scene.add(camera)

// Controls
// const controls = new OrbitControls(camera, canvas)
// controls.enableDamping = true

/**
 * Renderer
 */
const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})
renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

/**
 * Animate
 */

const clock = new THREE.Clock()

const tick = () =>
{

    const elapsedTime = clock.getElapsedTime()

    // Update objects


    // Update Orbital Controls
    // controls.update()

    // Render
    renderer.render(scene, camera)

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

tick()

app.js:

import "./example.js";

webpack.config.js:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var path = require('path');

// change these variables to fit your project
const jsPath= './js';
const cssPath = './css';
const outputPath = 'dist';
const localDomain = 'http://localhost:8888/jakubtrz-portfolio';
const entryPoints = {
  // 'app' is the output name, people commonly use 'bundle'
  // you can have more than 1 entry point
  'app': jsPath + '/app.js',
  'style': cssPath + '/main.scss',

};

module.exports = {
  entry: entryPoints,
  output: {
    path: path.resolve(__dirname, outputPath),
    filename: '[name].js',
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),

    // Uncomment this if you want to use CSS Live reload
    
    new BrowserSyncPlugin({
      proxy: localDomain,
      //files: [ outputPath + '/*.css' ]
      files: ['style.css', 'js/**/*.js', '**/*.php'],
      injectCss: true,
    }, { reload: false, }),
    
  ],
  module: {
    rules: [
      {
        test: /.s?[c]ss$/i,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'sass-loader'
        ]
      },
      {
        test: /.sass$/i,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'sass-loader',
            options: {
              sassOptions: { indentedSyntax: true }
            }
          }
        ]
      },
      // Loads all 3D model files; add more based on your needs
      {
        test: /.(obj|gltf|drc|mtl|glb)$/i,
        use: {
          loader: "file-loader",
          options: {
            outputPath: "models/",
            name: "[name].[ext]",
            esModule: false
          }
        }
      },
    ]
  },
};

Format pino file stream with pino-pretty

I build my first logger for my discord .js bot.

Now I need help with this:

How can I format the output fs stream also with pino-pretty?
This is my code

var fs = require('fs');
var pinoms = require('pino-multi-stream')

const date = new Date()

const prettyStream = pinoms.prettyStream({ prettyPrint: { colorize: true, translateTime: "SYS:standard", ignore: "hostname,pid" } });
var streams = [
    {stream: fs.createWriteStream(`logs/${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}-${date.getHours()}-${date.getMinutes()}.log`) },
    {stream: prettyStream }
]

var logger = pinoms(pinoms.multistream(streams))
module.exports = logger;

I’ve looked for some solutions but couldn’t find anything.
Please help!