ReactJs – Infinite scroll from bottom to top not fetching new data

I have a chat screen on my app that will initially display messages at the bottom of a div, and as a user scrolls up, more messages will be fetched. I am using the react-infinite-scroll-component package to handle the infinite scrolling.

To illustrate this issue, I created and edited an example from online, using simple divs to replicate chat messages.

The code below should fetch some data(dummy data in this example), after a user scrolls up the div. However instead, no data is being fetched as a user scrolls up, and only the original data(the initial state) is being displayed.

Here is the code snippet:

import React from "react";
import { render } from "react-dom";
import InfiniteScroll from "react-infinite-scroll-component";

const style = {
  height: 30,
  border: "1px solid green",
  margin: 6,
  padding: 8
};

class App extends React.Component {
  state = {
    items: Array.from({ length: 20 })
  };

  fetchMoreData = () => {

    console.log('Fetch called')

    setTimeout(() => {
      this.setState({
        items: this.state.items.concat(Array.from({ length: 30 }))
      });
    });
  };

  render() {
    return (
      <div
        id="scrollableDiv"
        style={{
          height: 300,
          overflow: "auto",
          display: "flex",
          flexDirection: "column-reverse"
        }}
      >
        {/*Put the scroll bar always on the bottom*/}
        <InfiniteScroll
          dataLength={this.state.items.length}
          next={this.fetchMoreData}
          style={{ display: "flex", flexDirection: "column-reverse" }} //To put endMessage and loader to the top.
          inverse={true} //
          hasMore={true}
          loader={<h4>Loading...</h4>}
          scrollableTarget="scrollableDiv"
        >
          {this.state.items.map((_, index) => (
            <div style={style} key={index}>
              div - #{index}
            </div>
          ))}
        </InfiniteScroll>
      </div>
    );
  }
}

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

Also note that the console.log(‘Fetch called’) within fetchMoreDatais never being logged to the console. Is there anything missing from the code that could be causing this issue? Thanks.

how to put array in the construction

I’m trying to create a function that will extract an array from an array
but I wish I didn’t have to split the string manually.
I wanted to ask how to do it in a comment to this question
text
but I don’t have the points so I decided to ask a question.
Thanks for the help.

I have it

function findIntersection(strArr) {
  
  const arr1 = strArr[0]
  const arr2 = strArr[1]
  const finalArr = [];
  arr1.forEach((el1) => {
    arr2.forEach((el2) => {
      if (el2 === el1) {
        finalArr.push(el1);
      }
    })
  })
  
  return finalArr;
}
var alphabet = "ABCDEFGHIJKLMNOPRSTUWZ";
var Alphabet = alphabet.split('');
var Alphabet = Alphabet.join(",", Alphabet);
var string = "DAMIAN";
var String = string.split('');
var String = String.join(",", String);
const res1 = findIntersection([['A'], ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S','T','U','W','Z']]);

console.log(Alphabet)
console.log(String)
console.log(res1)`

I want something like this but I don’t know why it doesn’t work

function findIntersection(strArr) {
  
  const arr1 = strArr[0]
  const arr2 = strArr[1]
  const finalArr = [];
  arr1.forEach((el1,no1) => {
    arr2.forEach((el2) => {
      if (el2 === el1) {
        finalArr.push(el1);
      }
    })
  })
  
  return finalArr;
}
var alphabet = "ABCDEFGHIJKLMNOPRSTUWZ";
var Alphabet = alphabet.split('');
var Alphabet = Alphabet.join(",", Alphabet);
var string = "DAMIAN";
var String = string.split('');
var String = String.join(",", String);
const res1 = findIntersection([[String], [Alphabet]]);

console.log(Alphabet)
console.log(String)
console.log(res1)

svelte bind and the value is not accepted by startWith() filter function to search text

Very strange issue but I’m unable to figure it out.

I’m trying to create text search in a svelte component.

My component script code :

<script>
$: searchingfor = []
//let searchterm = ""
$: searchterm = ""

let arr = ["can","can't", "also", "before", "eternal", "anothera"]

function  findterm() {

    let search = arr.filter(el=> el.startsWith("c"))
    console.log("search results :", search)
    
    search.map(el => searchingfor.push(el))
     searchingfor=searchingfor
    
    console.log("searchingfor results in onMount :", searchingfor)
       
}
    
</script>

<input type="text" bind:value={searchterm} />
<button on:click={findterm}>Search</button>

This code will run and return the correct values because I specifically entered “c” in startWith() fn.

The searchingfor array gets all the words that satisfy the search term. I use each block and display the results

But I want to user to enter what they’re searchign for, so I added an input and bind the value to searchterm variable. Now when I type something in the search input and hit enter, I get an empty array.

Console log is showing the value I enter – a – as just a without the double quotation. I don’t know how to wrap the searchterm to be wrapped in a “” so I can pass it to startWith()

How do I do that in js? Turn a to “a”?
I tried searchterm = “”” + searchterm + “”” but it is creating a empty space before a like this ” a” and again, I’m getting an empty array back from search.

How I get the searchterm value and turn it into “searchterm”, or how to search the text for whatever the user entered in the search input?

I’m stomped. Searching text and returning every word that starts with a letter was suppose to be an easy task 😉

How can I read a trained Tensorflow model file (.json) into Android app built with Capacitor (Vanilla JavaScript)?

I’ve built a cross-platform app with Capacitor, written in Vanilla JS. It uses the following code to load a trained Tensorflow model, a simple classifier NN built in Python.

import * as tf from '@tensorflow/tfjs';
....
const model = await tf.loadLayersModel('./assets/models/model.json');

This works on the browser and I can use the model to make predictions. The model fails to load when deployed on Android.

In the Android Studio logcat I see the following error:

E  Unable to open asset URL: http://localhost/assets/models/model.json

I also added these in the AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

So far I’ve looked into using the @capacitor/filesystem package but I’m not sure how it can be used to replicate the model-loading behaviour of loadLayersModel.

How can I replicate the working behaviour of the app running on the browser, in Android?

Thanks!

Try to convert recursive function by using 1 parameter: dfs(tar, num) -> dfs(tar)

https://leetcode.com/problems/ways-to-express-an-integer-as-sum-of-powers

following code AC; the dfs(tar, num); uses 2 parameter tar, num

var numberOfWays = function(n, x) {
    const MOD = 10**9+7;

    const mem = new Array(301).fill(undefined).map((_, i) => {
        return new Array(301).fill(undefined);
    });

    const dfs = (tar, num) => {
        if(tar < 0) return 0;
        if(tar === 0) return 1;

        const tmp = Math.pow(num, x);
        if(tmp > tar) return 0;

        if(mem[tar][num] !== undefined) return mem[tar][num];

        const take = dfs(tar - tmp, num+1);
        const skip = dfs(tar, num+1);

        const out = (take + skip) % MOD;
        mem[tar][num] = out;
        return out;
    }

    return dfs(n, 1);
};

following code fail to AC; the dfs(tar); uses 1 parameter tar; It always restart from i=1 in internal loop.

var numberOfWays = function(n, x) {
    const MOD = 10 ** 9 + 7;

    const dfs = (tar) => {
        // * b: tar
        if(tar < 0) return 0;

        // * b: tar
        if(tar === 0) return 1;

        // * b: 1. min/max, res after loop
        // * b: 2. acc, res after loop
        let acc = 0;

        // * b: each time, restart from 1
        for(let i=1; i<=n; ++i) {
            // * b: curr
            const curr = Math.pow(i, x);
            if(curr > tar) continue;

            pick = dfs(tar - curr);
            acc = acc + pick;
        }

        return acc % MOD;
    }

    return dfs(n);
};


input:
n = 10, x = 2

my output:
16

exp output:
1

The above code is based on https://leetcode.com/problems/perfect-squares

var numSquares = function(n) {
    const hash = {};

    const dfs = (num) => {
        if(num === 0) return 0;

        if(hash[num] !== undefined) {
            return hash[num];
        }

        let min = Infinity;
        
        const half_num = Math.floor(Math.sqrt(num));
        for(let i=1; i<=num; ++i) {
            if(i>half_num) continue;

            min = Math.min(min, 1 + dfs(num - i*i));
        }

        hash[num] = min;
        return min;
    }

    const res = dfs(n);
    return res;
};

In summary, I try to convert the dfs pattern by using internal loop within the recursive function
dfs(tar, num) —> dfs(tar)

nextjs an exported function is not a function when it’s used in another file

I am learning NextJs and having an issue with using context.

Here is my context

"use client";

import { createContext, useContext, useState } from "react";

const UserAuthContext = createContext();

export function UserAuthWrapper({ children }) {
  const [user, setUser] = useState({ name: "test user" });

  return (
    <UserAuthContext.Provider value={[user, setUser]}>
      {children}
    </UserAuthContext.Provider>
  );
}

export function useUserAuthContext() {
  return useContext(AppContext);
}

However, when I use useUserAuthContext to retrieve user object, I get the following error

TypeError: (0 , _context_user_auth_context__WEBPACK_IMPORTED_MODULE_2__.useUserAuthContext) is not a function or its return value is not iterable
    at Home (./src/app/page.js:14:93)
    at stringify (<anonymous>)

Here is how I use the function

import { useUserAuthContext } from "./context/user-auth.context";

export default function Home() {
  const [user, setUser] = useUserAuthContext();
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div>{user.name}</div>
    </main>
  );
}

Javascript with axios is not able to catch response

Currently I am building website with google recaptchar V3.
And I am having weird issue where axios can post token from recaptchar and flask app is processing this information correctly and return appropriate JSON data but whatever I try, I just cannot get ‘status’ or .then(response) {} block is working. Even chatgpt4 cannot help me for this issue here is my relevant code.

grecaptcha.execute('site_key', {action: 'submit'}).then(function(token) { //alert(${token}`) //–>working well
//alert(“token accepted”) –>This is working fine
//current problem: captchar verification screen is not displayed
//and as soon as I click the button, the flask app catch this and print something like below:
//127.0.0.1 – – [19/Nov/2023 07:27:52] “OPTIONS /checkCaptcha HTTP/1.1” 200
//So, I think I may have problem with the line related to grecaptcha.execute have problem

        //so, in flask app there is no problem 
            axios
            .post('http://localhost:3001/checkCaptcha', { token: token} ,{ 
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                  }
            }) 
            //alert("checkCaptcha")  --> work well
            //until here it is working fine and at flask server, I can confirm the http 200 code with token data received

           /*
           at flask app, the return value is as follow
           if result.get('success'):
                print('success') #-->currently printed as success
                return jsonify({'status': 'success'}),200
            else:
                return jsonify({'status': 'fail'}), 400
            and currently I cannot accest status with either const status = response.data.status; or const status = response.data['status'];
            what seems to be the core issue? 
           */
            .then((response) => {
                //alert("response") --> not working
                //alert(response)   --> not working
                //console.log(response) --> not working
                //this is not working
               
                const status = response.data.result;
                const status2 = response.data.result; //not working
                //alert(status) --> not working

//python flask part:

    response = requests.post(verify_url,data=payload)
    result =response.json()
    if result.get('success'):
        print('success') #-->currently printed as success
       
        return jsonify({'result': 'success'}),200
    else:
        return jsonify({'result': 'fail'}), 400

`

I tried to obtain status as const status = response.data.result; and also const status = response.data[‘status’]
from python terminal when I manually print the token, it gets printed well.
But it seems that at javascript level, it have some strange issue in getting this json value

Been stuck on this for awhile would appreciate any assistance

  • What went wrong:
    A problem occurred configuring root project ‘TEST’.

Could not find method useModule() for arguments [net.minecraftforge:ForgeGradle:4.0, settings_8hclc1ejt8ciucnqbipmjtw7e$_run_closure1$_closure3$_closure6$_closure7@5261ee0d] on object of type org.gradle.plugin.management.internal.DefaultPluginResolveDetails.

my settings.gradle:
    pluginManagement {
        repositories {
            mavenCentral()

            maven { url = "https://maven.minecraftforge.net/" }
            maven { url = "https://jitpack.io/" }
        }
        resolutionStrategy {
            eachPlugin {
                if (requested.id.id == "net.minecraftforge.gradle.forge") {
                    useModule("net.minecraftforge:ForgeGradle:4.0") {
                    }
                }
            }
        }
    }

    rootProject.name = 'TEST'

It seems to be a problem with “useModule” but i dont know what is wrong i am on a VM trying to compile
might be a dependency problem?

Thanks in advance!

Prob is a dependency problem i am on a windows VM

How do I remove the text shadow in this codepen?

I want to delete the yellow background text in the following codepen, while keeping the main text.

https://codepen.io/sanprieto/pen/XWNjBdb

const preload = () => {

  let manager = new THREE.LoadingManager();
  manager.onLoad = function() { 
    const environment = new Environment( typo, particle );
  }

  var typo = null;
  const loader = new THREE.FontLoader( manager );
  const font = loader.load('https://res.cloudinary.com/dydre7amr/raw/upload/v1612950355/font_zsd4dr.json', function ( font ) { typo = font; });
  const particle = new THREE.TextureLoader( manager ).load( 'https://res.cloudinary.com/dfvtkoboz/image/upload/v1605013866/particle_a64uzf.png');

}

if ( document.readyState === "complete" || (document.readyState !== "loading" && !document.documentElement.doScroll))
  preload ();
else
  document.addEventListener("DOMContentLoaded", preload ); 

class Environment {

  constructor( font, particle ){ 

    this.font = font;
    this.particle = particle;
    this.container = document.querySelector( '#magic' );
    this.scene = new THREE.Scene();
    this.createCamera();
    this.createRenderer();
    this.setup()
    this.bindEvents();
  }

  bindEvents(){

    window.addEventListener( 'resize', this.onWindowResize.bind( this ));
    
  }

  setup(){ 

    this.createParticles = new CreateParticles( this.scene, this.font,             this.particle, this.camera, this.renderer );
  }

  render() {
    
     this.createParticles.render()
     this.renderer.render( this.scene, this.camera )
  }

  createCamera() {

    this.camera = new THREE.PerspectiveCamera( 65, this.container.clientWidth /  this.container.clientHeight, 1, 10000 );
    this.camera.position.set( 0,0, 100 );

  }

  createRenderer() {

    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize( this.container.clientWidth, this.container.clientHeight );

    this.renderer.setPixelRatio( Math.min( window.devicePixelRatio, 2));

    this.renderer.outputEncoding = THREE.sRGBEncoding;
    this.container.appendChild( this.renderer.domElement );

    this.renderer.setAnimationLoop(() => { this.render() })

  }

  onWindowResize(){

    this.camera.aspect = this.container.clientWidth / this.container.clientHeight;
    this.camera.updateProjectionMatrix();
    this.renderer.setSize( this.container.clientWidth, this.container.clientHeight );

  }
}

class CreateParticles {
    
    constructor( scene, font, particleImg, camera, renderer ) {
    
        this.scene = scene;
        this.font = font;
        this.particleImg = particleImg;
        this.camera = camera;
        this.renderer = renderer;
        
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2(-200, 200);
        
        this.colorChange = new THREE.Color();

        this.buttom = false;

        this.data = {

            text: 'FUTUREnIS NOW',
            amount: 1500,
            particleSize: 1,
            particleColor: 0xffffff,
            textSize: 16,
            area: 250,
            ease: .05,
        }

        this.setup();
        this.bindEvents();

    }


    setup(){

        const geometry = new THREE.PlaneGeometry( this.visibleWidthAtZDepth( 100, this.camera ), this.visibleHeightAtZDepth( 100, this.camera ));
        const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, transparent: true } );
        this.planeArea = new THREE.Mesh( geometry, material );
        this.planeArea.visible = false;
        this.createText();

    }

    bindEvents() {

        document.addEventListener( 'mousedown', this.onMouseDown.bind( this ));
        document.addEventListener( 'mousemove', this.onMouseMove.bind( this ));
        document.addEventListener( 'mouseup', this.onMouseUp.bind( this ));
        
    }

    onMouseDown(){
        
        this.mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
        this.mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

        const vector = new THREE.Vector3( this.mouse.x, this.mouse.y, 0.5);
        vector.unproject( this.camera );
        const dir = vector.sub( this.camera.position ).normalize();
        const distance = - this.camera.position.z / dir.z;
        this.currenPosition = this.camera.position.clone().add( dir.multiplyScalar( distance ) );
        
        const pos = this.particles.geometry.attributes.position;
        this.buttom = true;
        this.data.ease = .01;
        
    }

    onMouseUp(){

        this.buttom = false;
        this.data.ease = .05;
    }

    onMouseMove( ) { 

        this.mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
        this.mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    }

    render( level ){ 

        const time = ((.001 * performance.now())%12)/12;
        const zigzagTime = (1 + (Math.sin( time * 2 * Math.PI )))/6;

        this.raycaster.setFromCamera( this.mouse, this.camera );

        const intersects = this.raycaster.intersectObject( this.planeArea );

        if ( intersects.length > 0 ) {

            const pos = this.particles.geometry.attributes.position;
            const copy = this.geometryCopy.attributes.position;
            const coulors = this.particles.geometry.attributes.customColor;
            const size = this.particles.geometry.attributes.size;

            const mx = intersects[ 0 ].point.x;
            const my = intersects[ 0 ].point.y;
            const mz = intersects[ 0 ].point.z;

            for ( var i = 0, l = pos.count; i < l; i++) {

                const initX = copy.getX(i);
                const initY = copy.getY(i);
                const initZ = copy.getZ(i);

                let px = pos.getX(i);
                let py = pos.getY(i);
                let pz = pos.getZ(i);

                this.colorChange.setHSL( .5, 1 , 1 )
                coulors.setXYZ( i, this.colorChange.r, this.colorChange.g, this.colorChange.b )
                coulors.needsUpdate = true;

                size.array[ i ]  = this.data.particleSize;
                size.needsUpdate = true;

                let dx = mx - px;
                let dy = my - py;
                const dz = mz - pz;

                const mouseDistance = this.distance( mx, my, px, py )
                let d = ( dx = mx - px ) * dx + ( dy = my - py ) * dy;
                const f = - this.data.area/d;

                if( this.buttom ){ 

                    const t = Math.atan2( dy, dx );
                    px -= f * Math.cos( t );
                    py -= f * Math.sin( t );

                    this.colorChange.setHSL( .5 + zigzagTime, 1.0 , .5 )
                    coulors.setXYZ( i, this.colorChange.r, this.colorChange.g, this.colorChange.b )
                    coulors.needsUpdate = true;

                    if ((px > (initX + 70)) || ( px < (initX - 70)) || (py > (initY + 70) || ( py < (initY - 70)))){

                        this.colorChange.setHSL( .15, 1.0 , .5 )
                        coulors.setXYZ( i, this.colorChange.r, this.colorChange.g, this.colorChange.b )
                        coulors.needsUpdate = true;

                    }

                }else{
                
                    if( mouseDistance < this.data.area ){

                        if(i%5==0){

                            const t = Math.atan2( dy, dx );
                            px -= .03 * Math.cos( t );
                            py -= .03 * Math.sin( t );

                            this.colorChange.setHSL( .15 , 1.0 , .5 )
                            coulors.setXYZ( i, this.colorChange.r, this.colorChange.g, this.colorChange.b )
                            coulors.needsUpdate = true;

                            size.array[ i ]  =  this.data.particleSize /1.2;
                            size.needsUpdate = true;

                        }else{

                            const t = Math.atan2( dy, dx );
                            px += f * Math.cos( t );
                            py += f * Math.sin( t );

                            pos.setXYZ( i, px, py, pz );
                            pos.needsUpdate = true;

                            size.array[ i ]  = this.data.particleSize * 1.3 ;
                            size.needsUpdate = true;
                        }

                        if ((px > (initX + 10)) || ( px < (initX - 10)) || (py > (initY + 10) || ( py < (initY - 10)))){

                            this.colorChange.setHSL( .15, 1.0 , .5 )
                            coulors.setXYZ( i, this.colorChange.r, this.colorChange.g, this.colorChange.b )
                            coulors.needsUpdate = true;

                            size.array[ i ]  = this.data.particleSize /1.8;
                            size.needsUpdate = true;

                        }
                    }

                }

                px += ( initX  - px ) * this.data.ease;
                py += ( initY  - py ) * this.data.ease;
                pz += ( initZ  - pz ) * this.data.ease;

                pos.setXYZ( i, px, py, pz );
                pos.needsUpdate = true;

            }
        }
    }

    createText(){ 

        let thePoints = [];

        let shapes = this.font.generateShapes( this.data.text , this.data.textSize  );
        let geometry = new THREE.ShapeGeometry( shapes );
        geometry.computeBoundingBox();
    
        const xMid = - 0.5 * ( geometry.boundingBox.max.x - geometry.boundingBox.min.x );
        const yMid =  (geometry.boundingBox.max.y - geometry.boundingBox.min.y)/2.85;

        geometry.center();

        let holeShapes = [];

        for ( let q = 0; q < shapes.length; q ++ ) {

            let shape = shapes[ q ];

            if ( shape.holes && shape.holes.length > 0 ) {

                for ( let  j = 0; j < shape.holes.length; j ++ ) {

                    let  hole = shape.holes[ j ];
                    holeShapes.push( hole );
                }
            }

        }
        shapes.push.apply( shapes, holeShapes );

        let colors = [];
        let sizes = [];
                    
        for ( let  x = 0; x < shapes.length; x ++ ) {

            let shape = shapes[ x ];

            const amountPoints = ( shape.type == 'Path') ? this.data.amount/2 : this.data.amount;

            let points = shape.getSpacedPoints( amountPoints ) ;

            points.forEach( ( element, z ) => {
                        
                const a = new THREE.Vector3( element.x, element.y, 0 );
                thePoints.push( a );
                colors.push( this.colorChange.r, this.colorChange.g, this.colorChange.b);
                sizes.push( 1 )

                });
        }

        let geoParticles = new THREE.BufferGeometry().setFromPoints( thePoints );
        geoParticles.translate( xMid, yMid, 0 );
                
        geoParticles.setAttribute( 'customColor', new THREE.Float32BufferAttribute( colors, 3 ) );
        geoParticles.setAttribute( 'size', new THREE.Float32BufferAttribute( sizes, 1) );

        const material = new THREE.ShaderMaterial( {

            uniforms: {
                color: { value: new THREE.Color( 0xffffff ) },
                pointTexture: { value: this.particleImg }
            },
            vertexShader: document.getElementById( 'vertexshader' ).textContent,
            fragmentShader: document.getElementById( 'fragmentshader' ).textContent,

            blending: THREE.AdditiveBlending,
            depthTest: false,
            transparent: true,
        } );

        this.particles = new THREE.Points( geoParticles, material );
        this.scene.add( this.particles );

        this.geometryCopy = new THREE.BufferGeometry();
        this.geometryCopy.copy( this.particles.geometry );
        
    }

    visibleHeightAtZDepth ( depth, camera ) {

      const cameraOffset = camera.position.z;
      if ( depth < cameraOffset ) depth -= cameraOffset;
      else depth += cameraOffset;

      const vFOV = camera.fov * Math.PI / 180; 

      return 2 * Math.tan( vFOV / 2 ) * Math.abs( depth );
    }

    visibleWidthAtZDepth( depth, camera ) {

      const height = this.visibleHeightAtZDepth( depth, camera );
      return height * camera.aspect;

    }

    distance (x1, y1, x2, y2){
       
        return Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2));
    }
}

I’ve tried so many things that all haven’t worked. The only thing I have been able to do is change the color of the text shadow thing. Not sure if the text I want to delete is in createParticles, createText, render, or onMouseMove.

Why my terminal is showing me [nodemon] app crashed – waiting for file changes before starting

Why my terminal is showing me [nodemon] app crashed – waiting for file changes before starting…
I want to connect my mongo successfully
My code is

const mongoose = require('mongoose');

const mongoURI = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false"

const connectToMongo =()=>{
    mongoose.connect(mongoURI,()=>{
        console.log("connected")
    })
}
module.exports = connectToMongo

I am expecting in my terminal
connected to Mongo Successfully

React “booking” component (private lessons)

I’m building website where private lessons will take place between teacher and student. I want to add a calendar where student can choose the date and time from those which are available for given teacher. Are there any components which are dedicated for this purpose?

¿Como puedo hacer para que el usuario al iniciar sesion y vuelva hacia atras no vuelva al formulario de login si no al index? [closed]

Actualmente me encuentro desarrollando una pagina web con Django y resulta que quiero que al usuario iniciar sesión no pueda volver al formulario de log in, tengo ese problema intenté varias formas y todas me salían erróneas, me gustaría que me pudieran ayudar o dejar alguna documentación a la cual poder ingresar y estudiar, yo creo y es lo más probable es que tuve algún error en el código o no supe donde implementarlo.

Como hacer para que el usuario al iniciar sesion y vuelva hacia atras no vuelva al formulario de login si no al index

Audio Mixing with Multiple Videos in WebView – React Native

I’m trying to get two videos playing at the same time with audio. As soon as I add the `muted` prop to the html video, both videos play perfectly, so I know it’s an issue with the audio mixing correctly.

I’ve tried the react-native-volume-manager and it is solving my problem.

Here is my simplified code snippet:

import React, { useEffect } from "react"
import { SafeAreaView, ViewStyle } from "react-native"
import WebView from "react-native-webview"
import { VolumeManager } from "react-native-volume-manager"

export const TestScreen = () => {
  const testUrls = [
    { key: "abc", value: "https://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4" },
    { key: "def", value: "https://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4" },
  ]

  useEffect(() => {
    ;(async function manageVolume() {
      await VolumeManager.enable(true, true) // Enable async
      await VolumeManager.setActive(true, true) // Activate async
      await VolumeManager.enableInSilenceMode(true)
      // await VolumeManager.setCategory("Record")
      await VolumeManager.setMode("VoiceChat")
      await VolumeManager.setCategory("Ambient", true)
      await VolumeManager.setVolume(1.0)
    })()
  }, [])

  return (
    <SafeAreaView style={$container}>
      {testUrls.map(({ key, value }) => (
        <WebView
          key={key}
          allowsInlineMediaPlayback
          allowsFullscreenVideo={false}
          source={{
            html: `<div style="width: 100%; max-width: 100%; height: 100%;  align-items: center; justify-content: center;">
                    <video id="video" style="width: 100%; height: auto;" playsinline autoplay loop>
                      <source src="${value}" type="video/mp4">
                    </video>
                    </div>
                  `,
          }}
          style={$webView}
        />
      ))}
    </SafeAreaView>
  )
}

const $container: ViewStyle = {
  flex: 1,
  backgroundColor: "black",
}

const $webView: ViewStyle = {
  flex: 0.5,
  backgroundColor: "red",
}

I would like both videos to play with audio overlapping. I’ve tried using the react-native-volume-manager library and used every combination of AVAudioSessionModes and AVAudioSessionCategories provided in the library.

Note: using iOS.

Why is my child component rendering so many times?

The Item component is used to represent one of multiple images or ‘items’ on a page. So like there is a grid of them. The Modal component is like a pop up that comes up when you click on one of the images and it’ll have a slideshow of related images and more information and what not.

Based on the console when I load the page, it seems that the Modal components are rendering significantly more than the Item components are but I can’t figure out why.

Item.js:

import React, { useEffect, useRef, useState } from "react";
import { ref, list, getDownloadURL, getMetadata } from "firebase/storage";
import { storage } from "../../firebase-config";
import Modal from "../HoF/Modal";

const Item = ({ folderName }) => {
  const [name, setName] = useState("");
  const [thumbnail, setThumbnail] = useState("");
  const [title, setTitle] = useState("");
  const [date, setDate] = useState("");
  const item = useRef(null);

  const modal = useRef(null);
  const modalWrapper = useRef(null);

  useEffect(() => {
    console.log("item");
    const getData = async () => {
      const folderRef = ref(storage, folderName);
      const folderList = await list(folderRef);
      const folderItems = folderList.items;

      var url;
      var metadata;
      for (var file of folderItems) {
        metadata = await getMetadata(file);

        if (metadata.name === "thumbnail.jpg") {
          url = await getDownloadURL(file);
          setThumbnail(url);
        } else if (metadata.name === "info.txt") {
          url = await getDownloadURL(file);
          fetch(url)
            .then((x) => x.text())
            .then((t) => {
              const splitText = t.split("rn");
              setTitle(splitText[0]);
              setDate(splitText[1]);
            });
        }
      }
    };

    const itemClick = (e) => {
      if (!modalWrapper.current.classList.contains("show")) {
        modalWrapper.current.classList.toggle("show");
        console.log("item clicked");
      }

      e.stopPropagation();
      e.preventDefault();
    };

    const outsideModalClick = (e) => {
      if (
        modalWrapper.current.classList.contains("show") &&
        !modal.current.contains(e.target)
      ) {
        modalWrapper.current.classList.toggle("show");
        console.log("outside modal lcick");
      }
    };

    const modalWrapperCopy = modalWrapper.current;
    const itemCopy = item.current;

    document.documentElement.addEventListener("click", outsideModalClick);
    modalWrapperCopy.addEventListener("click", outsideModalClick);
    itemCopy.addEventListener("click", itemClick);

    if (folderName === "") {
      setName("hof-moment-item-empty");
    } else {
      setName("hof-moment-item");
    }
    getData();

    return () => {
      document.documentElement.removeEventListener("click", outsideModalClick);
      modalWrapperCopy.removeEventListener("click", outsideModalClick);
      itemCopy.removeEventListener("click", itemClick);
    };
  }, []);

  return (
    <div className={name}>
      <div
        ref={modalWrapper}
        className="pseudo-container"
        // id="pseudo-container"
      >
        <Modal ref={modal} />
      </div>
      <div className="hof-moment-item-wrapper" ref={item}>
        <img src={thumbnail} alt="thumbnail"></img>
        <h5>{title}</h5>
        <span>{date}</span>
      </div>
    </div>
  );
};

export default Item;

Modal.js:

import { React, forwardRef } from "react";

const Modal = forwardRef((props, ref) => {
  console.log("modal");
  return (
    <div ref={ref} className="hof-modal-container">
      <div className="hof-modal-image-container"></div>
      <div className="hof-modal-description-container"></div>
    </div>
  );
});

export default Modal;