How to call function from App.js file inside public folder in React JS

I would like to call a function which is defined inside src/App.js (callMe) from public folder,

In App.js

import messaging from './firebase-init';
import './App.css';

function App () {
 function callMe() {
   console.log('Call me function called');
 }
  return (
    <div className="App">
      <h1>Hello World</h1>
    </div>
  );
}
export default App;

And I’ve another file firebase-messaging-sw.js located inside public folder,

In firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');

self.addEventListener('notificationclick', function (event) {
  console.log('On notification click: ', event);
  event.notification.close();
  event.waitUntil(clients.matchAll({
    includeUncontrolled: true,
    type: "window",
  }).then(function (clientList) {
    console.log('********* clientList: ', clientList);
    for (var i = 0; i < clientList.length; i++) {
      var client = clientList[i];
      if (client.url !== '' && 'focus' in client) {
        client.focus();
        callMe();  // This function is defined in src/App.js
        break;
      }
    }
  }));
});

const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "AUTH_DOMAIN",
  projectId: "PROJECT_ID",
  storageBucket: "STORAGE_BUCKET",
  messagingSenderId: "SENDER_ID",
  appId: "APP_ID",
  measurementId: "MEASUREMENT_ID"
};

// Initialize Firebase
const initializedFirebaseApp = firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

Can you please help me, how should I call function callMe() ?

Food Ranking List Challenge (TestDome)

I get stuck on this challenge so i need help.

A website needs a list where users can rank their favorite foods. Write the setup function, which should register click handlers on all Up! and Down! buttons. The Up! button should move the list item one place up in the list, while Down! button should move the list item one place down in the list.

For example, consider this code:

document.body.innerHTML = `<ol>
  <li><button>Up!</button>Taco<button>Down!</button></li>
  <li><button>Up!</button>Pizza<button>Down!</button></li>
  <li><button>Up!</button>Eggs<button>Down!</button></li>
</ol>`;

setup();
If the button Up! button in Pizza list item is clicked, Pizza should be the first item in the list, while Taco should be the second item

THIS IS MY CODE

function setup() {
  let list = document.getElementByTagName('li');
  let btnList = document.getElementByTagName('button');
  let up;
  let down;
  
  for (let l = 0; l < list.length; l++){
    for (let b = 0; b< btnList.length; b++){
      btnList[b].addEventListener("click", (item, index)=>{
        if(btnList[b].textContent == "Up!"){
          up = list[l - 1]
        } else if(btnList[b].textContent == "Down!"){
          down = list[l + 1]
        } else{
          return list
        }
      })
    }
  }
    return list;  
      
    })
  }
}

Please no Jquery.

Puts data into an array within a subscribe function

In my project, I have X and Y coordinate motion that allows the car to move. I want to be able to put this data into an array because I want to move a steering wheel to see where the car is going. However, for this, I need to be able to refer to the previous and next data. Can anyone help?

  tag5617.subscribe(function(message{
    let X = document.getElementById('posX');

    X.innerHTML = message.x.toFixed(2);

    let Y = document.getElementById('posY');

    Y.innerHTML = message.y.toFixed(2);

    myChart.data.datasets[0].data.push({x:message.x.toFixed(2), y:message.y.toFixed(2)});

    myChart.update();
        
    });

Change label dynamically in typescript

I have a function that takes in a string but depending on which type of file is coming in i want my html label to switch between each other

ex:

function changename(food: string){
 if(food){
   this.type = this.getcookiesobservable(food);
   this.type = this.getcakeobservable();
  }
}

how would i get these two to swap and say “cookies” || “cakes”

THREEJS videoTexture resolution/ streaks

I created a videoTexture using THREEJS but when displaying it, it seems as there are streaks on the video.

const video = document.getElementById('video');
const videoTexture = new THREE.VideoTexture(video)
videoTexture.encoding = THREE.sRGBEncoding;        
videoTexture.flipY = false;

I tried adding magFilter = THREE.LinearFilter;but it didn’t change anything.

Here is the image of my video where we can see the streaks and here is my original image without the streaks showing

How to add a timer on page load that stops when button is clicked?

I want to add a timer to the page where it starts on page load.

Where it goes up in milliseconds.

Then stops when the mouse is clicked on the button.

How would I create a code example of that?

https://jsfiddle.net/724n1qro/

That is all I am trying to do in the code.

Add a timer that starts on page load.

Goes up in milliseconds.

Then stops when the button is clicked.

.play {
  -webkit-appearance: none;
  appearance: none;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  border: 9px solid blue;
  background: transparent;
  filter: drop-shadow(3px 3px 3px #000000b3);
}
 <button class="play" type="button" aria-label="Open"></button>

remove elements from array if not exist in other array

i am trying to do the following, with several reads here and on the web but can’t seem to get it to work. I have two array that consist out of objects (filled dynamically) by two webservices, so I created a timed trigger and loop over them to update the products array.

var products= [
  {idProduct: '1', price: '4.99'}, 
  {idProduct: '2', price: '9.99'}, 
  {idProduct: '3', price: '7.95'}, 
  {idProduct: '4', price: '4.95'}
];

var update = [
  {idProduct: '1', price: '4.99'}, 
  {idProduct: '4', price: '4.95'}
];

what I would like to do is to remove the product from products array that are not in update. I know how to compare and how to add the product but that all checks from the update section. What I can’t seem to get to work is to delete the ones that are no longer in the update.

var i = 0;
   var entry1;
      while (i < products.length) {

       entry1 = products[i];
           
    if (update .some(function(entry2) { return entry1.ProductId === entry2.ProductId; })) {
       // Found, progress to next
       ++i;
    } else {
       // Not found, remove
       products.splice(i, 1);
    }
}

Once processed I will remove the contents of update array and it story starts again.

update = []

Desired result of products Array:

products= [
  {idProduct: '1', price: '4.99'},  
  {idProduct: '4', price: '4.95'}
];

and no, I can’t just use update array as this is a simplified example and part of a bigger code 🙂

Redux does not change values

my Redux does not change the variables value. I am trying to test out Redux but I really cant find what I am doing wrong. For now I am only trying to Log a value but the value does not change.

This is my ReduxActions:

export const TEST_FUNC = 'TEST_FUNC';

export const testFunc = () => {
    
    const theTestingString = "TAG testing redux";

    return {
        type: TEST_FUNC,
        payload: theTestingString
    }
}

In my Reducer I give the variable a initial value, and in my Actions file I am trying to change that value but when I console.log(testRedux) I only get the initial value. here is my Reducer:

import { TEST_FUNC } from "../actions/firebaseActions";

const initialState = {
    theTestingString: 'Initial Value',
}

export default function(state = initialState, action) {

        switch(action.type) {
            case TEST_FUNC: 
            console.log("HSKJDKJSKFDBSKJKAJDL")
            return {
                ...state,
                theTestingString: action.payload
            }
        }

        return state;
}

Here is my Store:

import {createStore, applyMiddleware, combineReducers} from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';

import firebaseReducer from './reducers/firebaseReducer';

const rootReducer = combineReducers({
    firebaseTest: firebaseReducer
});

const middleware = composeWithDevTools(applyMiddleware(thunk));

export default createStore(rootReducer, middleware);

Here is where I am trying to log the value:

import { useNavigation } from '@react-navigation/native';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import {Button, Card, TextInput} from 'react-native-paper';
import { FirebaseContext } from '../../context/FirebaseContext';
import React, {useContext, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

const initialUserState = {
    userName: 'Nicole Lopez',
    password: '1001008888',
}

export default function LoginScreen() {
    const [disabled, setDisabled] = useState(false);
    const [userState, setUserState] = useState(initialUserState);
    const testRedux = useSelector(state => state.firebaseTest.theTestingString);
    //const fbContext = React.useContext(FirebaseContext);
    const navigation = useNavigation();

    console.log("Logging right away: " + testRedux);

    const onInputChange = (field, value) => {
        setUserState({
            ...userState,
            [field]: value
        })
    }

    useEffect(() => {
        setDisabled(userState.userName.length === 0 || userState.password.length === 0);
    }, [userState.userName, userState.password])

  return (
    <View style={styles.container}>
            <Card style={styles.card}>

                <TextInput
                    mode="outlined"
                    label="Förnamn & Efternman"
                    defaultValue={userState.userName}
                    onChangeText={text => onInputChange("username", text)}
                    right={<TextInput.Icon name="account" onPress={() => {
                    }}/>}
                    style={styles.textInput}/>

                <TextInput
                    mode="outlined"
                    label="Anställningsnummer 100100xxxx"
                    defaultValue={userState.password}
                    right={<TextInput.Icon name="lock"/>}
                    onChangeText={text => onInputChange("password", text)}
                    style={styles.textInput}/>
            </Card>

            <View style={styles.buttonRow}>

                <Button
                    color={disabled ? "gray" : undefined}
                    disabled={disabled}
                    mode={'contained'}
                    icon={'login'}
                    onPress={() => {
                        //console.log("The func: " + testRedux)
                        console.log("The variable: " + testRedux)
                        //console.log(fbContext)
                        //console.log("TAG isUserSignedIn: " + fbContext?.isuserSignedIn)
                        //console.log("TAG testLog:::: " + fbContext?.testLog())
                        //fbContext?.testLog()
                        //console.log("TAG LOGIN BTN PRESSED")
                        //navigation.navigate('HomeScreen')
                    }}>Login</Button>
            </View>
        </View>
  );
}

This is my App.js:

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import {StackScreens} from './src/helpers/types';
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import LoginScreen from './src/screens/LoginScreen/LoginScreen';
import HomeScreen from './src/screens/HomeScreen/HomeScreen';
import {doc, getFirestore, onSnapshot, setDoc, Unsubscribe as UnsubscribeFS} from 'firebase/firestore';
import { FirebaseContextProvider, FirebaseContext } from './src/context/FirebaseContext';
import { useContext } from 'react';
import {Provider} from 'react-redux';

import store from './src/redux/Store';


const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <Provider store={store}>
      <Content />
    </Provider>  
  );
}

export const Content = () => {

  const navigationRef = useNavigationContainerRef();
  const firebaseContext = useContext({FirebaseContext});

  return (
    
    <NavigationContainer ref={navigationRef}>
        <Stack.Navigator initialRouteName="LoginScreen">
          <Stack.Screen name="LoginScreen" component={LoginScreen} />
          <Stack.Screen name="HomeScreen" component={HomeScreen} /> 
        </Stack.Navigator>
      </NavigationContainer>
      
  );
}

I am new to ReactNative, I have tried Context but I got a similar issue, maybe I’m doing something in the wrong order?

what is making props behavior inconsistent when set as a variable and passed into another function

I am creating a simple audio player using React.

When pushing the “Play” button, audio will be played from a url and the button will display “Pause”. Once the audio is finished the button will reset to “Play.”

There are three buttons “one” “two” “three”. Each one will load a new audio url to be played by the button. Here is the codesandbox.

I’m new to useEffect and useState and I think there is an issue with how I’m updating this with props.

In my audio player component, if I directly set the url (without updating it with props), the audio will play as expected when the “play” button is pushed. However, when I set the url with props it won’t play (even though the console.log() displays the correct url).

here is my Audio3.js component (responsible for playing audio:

import React, { useState, useEffect } from "react";


const useAudio = (url) => {
  console.log("in useAudio", url)
  const  = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);


  const toggle = () => setPlaying(!playing);

  useEffect(() => {
    playing ? audio.play() : audio.pause();
  }, [playing]);

  useEffect(() => {
    audio.addEventListener("ended", () => setPlaying(false));
    return () => {
      audio.removeEventListener("ended", () => setPlaying(false));
    };
  }, []);

  return [playing, toggle];
};

const Player = (props) => {

console.log("the current page is", props.currPage)

  // const url = "https://github.com/cre8ture/audioFilesForBL/blob/main/2.mp3?raw=true"

  const url =  "https://github.com/cre8ture/audioFilesForBL/blob/main/" +
  props.currPage +
  ".mp3?raw=true"
  
  console.log("the audio 3 is ", url);
  const [playing, toggle] = useAudio(url);


  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
};

export default Player;

Here is the threeButtons.js file:

import React from "react";

function Tabs(props) {
  return (
    <>
      <button onClick={() => props.handleChangeProps(1)}>ONE</button>
      <br />
      <button onClick={() => props.handleChangeProps(2)}>TWO</button>
      <br />
      <button onClick={() => props.handleChangeProps(3)}>THRE</button>
    </>
  );
}

export default Tabs;

Here is the header component that houses the audio Play button:

import React from "react";
import Audio from "./Audio3";

function Header(props) {
  console.log("header", props.currPage);

  return (
    <Audio currPage={props.currPage} />
  );
}

export default Header;

And lastly, here is my App.js

import React, { useState } from "react";
import Header from "./components/header";
import ConceptTabs from "./components/threeButtons";

function App() {
  const [pageID, setPageID] = useState(0);

  // goes to ConceptTabs
  let handleChange = (id) => {
    console.log("clicked", id);
    handleChange2(id);
    setPageID(id);
    return id;
  };

  // Goes to Audio2
  let handleChange2 = (id) => {
    console.log("clicked2", id);
    return id;
  };

  console.log("pageID", pageID);

  return (
    <>
      <Header currPage={pageID} />
      <br />
      <ConceptTabs handleChangeProps={handleChange} />
    </>
  );
}

export default App;

Thanks so much

Finding the longest connection of ports (JS)

I can’t solve a problem.
We have an array. If we take a value, the index of it means port ID, and the value itself means the other port ID it is connected to. Need to find the start index of the longest sequential connection to element which value is -1.

I made a graphic explanation to describe the case for the array [2, 2, 1, 5, 3, -1, 4, 5, 2, 3]. On image the longest connection is purple (3 segments).

graphic description

I need to make a solution by a function getResult(connections) with a single argument. I don’t know how to do it, so i decided to return another function with several arguments which allows me to make a recursive solution.

function getResult(connections) {
  return f(connections.findIndex(e => e == -1), connections, 0, []);
}

function f(index, cnx, counter, branches) {
  counter++;  
  for (let i = 0; i < cnx.length; i++) {
    if (cnx[i] === index) {
      branches.push([i, counter]);
      return f(i, cnx, counter, branches);
    }
  }
  return branches.sort((a, b) => b[1] - a[1])[0][0];
}

console.log(getResult([1, 2, -1])); // expected 0
console.log(getResult([1, -1, 1, 2])); // expected 3
console.log(getResult([2, 1, -1])); // expected 0
console.log(getResult([3, 4, 1, -1, 3])); // expected 2
console.log(getResult([1, 0, -1, 2])); // expected 3
console.log(getResult([3, 2, 1, -1])); // expected 0
console.log(getResult([2, 2, 1, 5, 3, -1, 4, 5, 2, 3])); // expected 6

Anyway, the code doesn’t work completely properly.
Would you please explain my mistakes?
Is it possible to solve the problem by a function with just one original argument?

get the static part of a RegExp

I want to get the static part of a RegExp string, which 100% guaranteed to not have a regex-specific characters, except the grouping parentheses ().

for instance, this regex /path/config-(.+)/.js/ has a static part /path/config- until the character ‘.’

use cases:

I want to search for all matched entries inside a folder that have too many files and subfolders.

so, it is a bit faster to start searching from the basic path /path that doesn’t needed to be matched against, instead of starting from the root directory.

Read and edit local xml-file in Javascript

I have a directory that contains

--index.html
--script.js
--file.xml

and I want to read the content of the file.xml as a string in order to replace a few words within the xml-file. (Later on I would like to send the edited xml-file as e-mail).

I managed to access to xml-file, but did not manage to save the whole content in a string and/or replace some known keywords within the xml.

This is where I got so far:

var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

function reportStatus2() {
  if (oXHR.readyState == 4)               // REQUEST COMPLETED.
     console.log(this.responseXML)        // This gets me the XML-document, but I want the complete xml content as string
}
oXHR.onreadystatechange = reportStatus2;    
oXHR.open("GET", "../file.xml", true);
oXHR.send();

I found so many posts on that topic here, but none was able to answer my question!
Any ideas?

Create a student timetable using React JS

I’m looking to develop a Timetable for students using React JS to manage their classes online, as you see in some timetable apps in Google Play & App Store. Still, my problem is finding the package to create this timetable.

I couldn’t find any timetable package to use in my app. Can someone please help and suggest a timetable for students?