Call webpack-ed function from JS file

I’m facing an issue, the goal I want to achieve is call a function from a webpack file.

I’ve followed this question and I can do it in the same way as the accepted answer. Using the tag <script> in the HTML and window.onload. But I want to call my function from a.js file.

So I want something like this:

  1. The HTML calls a JS script file.
  2. JS script import function from webpack-ed JS.
  3. webpacked function is executed.

The tree folder is like this:

|
|-> index.html
|-> index.js       --> From here I want to call function packed
|-> lib
     |
     |-> main.js   --> webpacked file

My webpack.config.js is

module.exports = {
  // ...
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'lib'),
    libraryTarget: 'var',
    library: 'MyLibrary'
  },
};

The file I’m packing is a TS file which has a function like this:

export function test(){
    console.log("test")
}

Then in the HTML I call the JS file:

<script type="module" src="./index.js"></script>

And into index.js I do the import:

import MyLibrary from './lib/main.js';

// here I want to do MyLibrary.test()

But it throws an error:

Uncaught SyntaxError: import not found: default

Also I’ve tried:

import {test} from './lib/main.js';

Or adding default in the TS file.

export default function test(){
    console.log("test")
}

// or

function test() { ... }
export {test as default};

But, as I’ve said before, adding this into the HTML works:

<script src="./lib/main.js"></script>
<script>
window.onload = function () {
    MyLibrary.test();
};
</script>

But I want to have the function in a JS file.

I’ve found a similar question but the answer don’t work for me.

Thanks in advance

Cant output answer buttons and sort them in my project

im trying to make a quizz project fetching api of quiz with answers and questions im so in the api
there is array of wrong answers(3) and one correct answer i try to output them as buttons and i outtput the 3 wrong answers so i thought i would push the correct answer into the wrong answers array and then randomly sort them and output as answers but i get the errot that array of answers isnt iterable can anyone help me to solve this problem and tell me if im going in the right direction or not ?


import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res=>{
     
      setQuiz(res.data.results[0])
     
       setAnswer([...quiz.incorrect_answers, quiz.correct_answer])
    })
    .catch(err=>{
      console.log(err);
    })
 
  },[])



  return (
    <div className="App">
   <h1>{quiz.question}</h1>
   {answer && answer?.map(answers =>
   <button key={answers}>{answers}</button>)
  
   }
    </div>

  );
}

export default App;

onSelect() is not a function in ReactJS

I have following code.

I’m trying to store a value in my state and every time the user goes to the previous step he can see what he has selected and after that he can change and move on to the next step.

At the first step, everything works good. For example, the user selects the second text and proceeds to the next step, and when he returns to this step, he sees that the second text has already been selected…

The problem is with the second step, I write all the same, but it doesn’t work for the second step.

The error says onSelect is not a function. Please help me solve this problem.

Here is my code.

App file

    export default function App() {
     const [selected, setSelected] = useState(1);
     const [term, setTerm] = useState(1);

     const [current, setCurrent] = useState(0);

     const [data, setData] = useState({
       firstName: "bob",
       lastName: "Forest",
       age: 47
     });
      const steps = [
        {
          title: "Package Choose",
          content: (
            <PackageChoose
              setCurrent={setCurrent}
              data={data}
              setData={setData}
              selected={selected}
              setSelected={setSelected}
            />
         ),
          id: 0
        },
        {
          title: "Term",
          content: (
            <Term
              setCurrent={setCurrent}
              data={data}
              selected={term}
              setSelected={setTerm}
            />
          ),
          id: 1
        },
        {
          title: "Last step",
          content: <LastStep setCurrent={setCurrent} data={data} />,
          id: 2
        }
      ];
      return (
        <div className="App">
          <div>{steps[current].content}</div>
        </div>
      );
    }

first step package choose file

    const PackageChoose = ({
      setCurrent,
      data,
      setData,
      setSelected,
      selected
    }) => {
      return (
        <div>
          <div
            onClick={() => {
              setData({ ...data, packageType: "choice" });
            }}
          >
            <SelectCard
              id={1}
              selected={selected}
              onSelect={setSelected}
              text="text 1"
            />
          </div>
          <div
            onClick={() => {
              setData({ ...data, packageType: "select" });
            }}
          >
            <SelectCard
              id={2}
              selected={selected}
              onSelect={setSelected}
              text="text 2"
             />
          </div>
          <button onClick={() => setCurrent(1)}>Next</button>
        </div>
      );
   };

second step Term file

   const Term = ({ setCurrent, data, setData, term, ssetTerm }) => {
      return (
        <div>
          <button onClick={() => setCurrent(0)}>Prev</button>
          <div
            onClick={() => {
              setData({ ...data, termType: "30 day" });
            }}
          >
            <SelectCard
              id={1}
              selected={term}
              onSelect={setTerm}
              text=" term text 1"
            />
         </div>
          <div
            onClick={() => {
              setData({ ...data, termType: "90 day" });
            }}
          >
            <SelectCard
              id={2}
              selected={term}
              onSelect={setTerm}
              text="term text 2"
            />
          </div>
          <button onClick={() => setCurrent(2)}>Next</button>
            </div>
      );
    };

SelectCard file , in this file I am using onSelect

   const SelectCard = ({ id, selected, onSelect, text }) => {
      const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (
        <div className={classNames(myClassName)} onClick={() => onSelect(id)}>
          <div> {text} </div>
        </div>
      );
     };

Please help me to understand how can I fix this problem in my code.

Thanks.

Access react modules via chrome console (not React dev tools)

I’m using an off-the-shelf AB testing tool at the company I work for, called Google Optimize 360, to build front-end AB tests on our website.

This tool works like Google Analytics… as in, a script is injected into the <head> tag, of the page you want to run AB tests on. And then you add bespoke vanilla JS, CSS etc into Optimize 360, to redesign/test DOM elements of a page.
https://marketingplatform.google.com/about/optimize-360/

(So basically, AB tests run on top of the compiled codebase… not within it).

The website I’m running AB tests on is built in React and it has a lot of limitations, as I can’t seem to access any components/modules/functions via the front-end, (outside of the application). For example, via chrome console.

Angular for example is great, because I can access methods via angular services on the front-end via angular.element. EG:

angular.element(document.body).injector().get("ANGULAR_SERVICE");

Is there an alternative for react?

I haven’t been able to find anything, which works, where I can trigger modules/functions via chrome console.

For example, I couldn’t get dynamic import to work via chrome console, as I can’t even see the path to the module in the compiled codebase…

import('path/to/module.js').then(m => module = m)

I basically tried a few options on this page:

How to use ES6 modules from dev tools console

I appreciate react is not supposed to work in this way…. But is there anyway, I can have the react application changed, to allow certain modules/functions to be accessible via the front-end?

What would need to be done?

Also I’m aware of “React Developer tools” chrome extension, but this is not what I’m looking for. I’m looking to invoke functions outside of the react app, (not traverse the dom/module).

Thanks,

How can I remove this error when I deploy my React App?

Currently I have a functioning React app that I am able to run on localhost:3000. My current deployment process is as follows: I ran npm run build, and uploaded that file to my shared hosting provider.

I then added a .htaccess file with

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

Then I added "homepage": ".", in the package.json. (I even tried to add the "homepage": "http://websiteexample.com", instead of the . ).

From another post I seen, I even removed the forward slashes in my index.html.

None of this seems to work and gives me a blank page with the following error in the console:
DevTools failed to load source map: Could not parse content for https://website.com/static/js/main.f532f71f.js.map: Unexpected token < in JSON at position 0

Question: How can I deploy it? Is there something I am missing?

Javascript selecting nth element but excluding some elements

Consider the following markup:

<div class="body">
     <p>...<p>
     <p>...<p>
     <blockquote>
          <p>...<p>
     </blockquote>
     <p>...<p>
     <p>...<p>
</div>

I want to select the first <p> element. I can do this with:

$( ".body p:nth-child(1)

However if I wanted to select the 3rd

(excluding the blockquote) this will not work:

$( ".body p:nth-child(3)

I tried using nth-type, but if I do:

$( ".body p:nth-type(1)

It will select the first

in the body and also the nexted p in block quote.

I need to be able to exclude or ignore the blockquote. Would it work if I read the dom ino a variable and removed the blockquote before calling nth-child?

Clone div and delete div

I don’t understand why all Functions are not working. Normally if you click on the button “+ Loc de munca” needs to appear input and then if you click further on the “+ Loc de munca” need to clone all input. Also if you click on the “Sterge” need everything to delete. Here is the code:

var itm = document.getElementById("myList4").getElementsByTagName("div")[0];

function appearafter2() {
  document.getElementById("buttonappear2").style.display = "block";
  document.getElementById("button2").style.display = "block";
  document.getElementById("hinzufuegen2").style.display = "none";
}

function myFunction2() {
  var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
  var cln = itm.cloneNode(true);
  document.getElementById("myList3").appendChild(cln);
}

function deleteFunction2() {
  var list3 = document.getElementById("myList3");
  var divs = Array.from(list3.getElementsByTagName("div"));

  // If the number of divs is 4, it means we're removing the last
  // cloned div, hide the delete button.
  if (divs.length === 4) {
    document.getElementById("button2").style.display = "none";
  }

  var lastDivToDelete2 = divs[divs.length - 1];

  list3.removeChild(lastDivToDelete2);
}

function allFunction2() {
  myFunction2();
  appearafter2();
}
#button2 {
  display: none;
}

#buttonappear2 {
  display: none;
}

.input-data2 {
  width: 49%;
}
.label-data2 {
  width: 50%;
}
#myList3 {
  display: none;
}
#label-job-input-inline {
  display: inlin-block;
}
.label-job-input {
  display: block;
}
<div id="hinzufuegen2" onclick="allFunction2()">
  + Loc de munca
</div>
<div id="myList3">
  <div id="button2" onclick="deleteFunction2()">Șterge</div>
  <div id="myList4">
    <div id="addingNewJob">
      <label class="label-job-input" for="job-input-1">Numele firmei</label>
      <select size="1" type="text" id="job-input-1" /><option value="scoala_generala">școala generală</option>
  <option value="scoala">școală profesională</option>
  <option value="lic">liceu</option>
  <option value="fac">facultate</option></select>
      <label class="label-job-input" for="job-input-2">Postul ocupat
      </label>
      <input size="1" type="text" id="job-input-3" /><br />
      <label class="label-data2" for="job-input-3">din data</label><label class="label-data2" for="job-input-4">până la data</label><br />
      <input type="number" style="width: 48%" />
      <input type="number" style="width: 50%; margin-left: 6px" />
    </div>
  </div>
</div>

<div onclick="allFunction2()" id="buttonappear2">
  + Loc de munca
</div>

Hello, I don’t understand why all Functions are not working. Normally if you click on the button “+ Loc de munca” needs to appear input and then if you click further on the “+ Loc de munca” need to clone all input. Also if you click on the “Sterge” need everything to delete. Here is the code:

Cant render my component data correctly in React Native – Using Axios

currently im having a weird issue with regards to rendering my API. (im using Expo GO)

Im using Axios, which calls the API inside of a UseEffect once I get location of the device.
The problem I’m facing is that the screen only renders the fetched data once i save or cntrl+s on VS Code.

Ive tried to log the array, get nothing once the function is called.
Ive also tried adding a button to call the function instead, only then it renders, which makes sense as it triggers a re-render.

WHEN I ENTER THE COMPONENT:
enter image description here

WHEN I SAVE THE FILE, IT THEN FETCHES DATA:
enter image description here

Would be much appreciated if anyone can help, maybe im missing some basic knowledge of how this works. Thanks guys!

import axios from 'axios';
import { SafeAreaView, StyleSheet, Text, View, Button, Alert, ScrollView, RefreshControl } from 'react-native';
import React, { Component, useState, useEffect, createContext } from 'react';
import { winners } from '../screens/MainScreen';
import * as Location from 'expo-location';
import { useIsFocused } from '@react-navigation/native';


const API = () => {

  

  const resturant = winners;
  
  const isFocused = useIsFocused();

  const [NamesFound, setNamesFound] = useState(0);

  const APIKey ='xxxxxxxxxx';
  const [Result, SetResult] = useState([]);
  const [Names, SetNames] = useState([]);
  
  const [lat, Setlat] = useState();
  const [long, Setlong] = useState();
  
  // const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [address, setAddress] = useState(null);
  const [RestAddress, setRestAddress] = useState([]);
  const [refreshing, setRefreshing] = useState(false);

  const [loading, setLoading] = useState(true);


  const wait = (timeout) => {
    return new Promise(resolve => setTimeout(resolve, timeout));
  }

    const onRefresh = React.useCallback(() => {
      setRefreshing(true);
      wait(2000).then(() => setRefreshing(false));
    }, []);
  
  const SampleFunction=(item)=>{
 
    Alert.alert(item);
 
  }

  
  const getLocation = () => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
      }

      Location.setGoogleApiKey(APIKey);

      // console.log(status)

      let { coords } = await Location.getCurrentPositionAsync();

      // setLocation(coords);

      Setlat(coords.latitude);
      Setlong(coords.longitude);

      if (coords) {
        let { longitude, latitude } = coords;

        let regionName = await Location.reverseGeocodeAsync({
          longitude,
          latitude,
        });
        setAddress(regionName[0].city);
        console.log(regionName[0].city);
      }

    })();
  };


 
  var config = {
    method: 'get',
    url: 'https://maps.googleapis.com/maps/api/place/textsearch/json?location='+lat+','+long+'&key='+APIKey+'&status=&query='+resturant,
    headers: { }
  };

  useEffect(() => {
  
      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          SetResult(response.results);
          console.log(Result.map((name)=> name.name));
          SetNames(Result.map((name)=> name.name))
          setNamesFound(Names.length);
          console.log('API function called.')
          console.log (Names);
          
        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }
    
      getLocation();
      fetchData();
    
  }, []);
  
     
  return(
    
    <SafeAreaView style={styles.container}>
      
      {loading && <Text>Loading....</Text>}
      {!loading && isFocused && (
        <><Text style={styles.MainText}>{NamesFound} {winners}s within {address}</Text><ScrollView
          style={styles.scroll}
          refreshControl={<RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh} />}
        >
          {Names.map((item, key) => (
            <Text key={key} style={styles.TextStyle} onPress={SampleFunction.bind(this, item)}> {item} </Text>)
          )}
        </ScrollView></>
      )}
    
      {/* <Button title='CLICK ME FOR API' onPress={CallAPI} style={styles.btn}></Button> */}
      
      
      
    </SafeAreaView>
  );
};

React.js and Firebase querySnapshot.forEach replacing array with identical objects

I’ve been facing this issue for a couple of days where I have an array named tempTaskArray, which stores objects filled with data taken from my firestore database.

These objects contain the correct data on each iteration of the .forEach method but when put into my state variable, “tasks” (an array), from array tempTaskArray, all objects contain the data of the last created object.

This issue is not run into when I have an array of strings.

See code below:

      const getTasks = () => {
    db.collection("users").doc(uid).collection("tasks")
    .orderBy("epochdate", "asc")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {

          // populates array with strings
          // tempTaskArray.push(doc.data().taskname)

          // tempTaskObject is an empty object
          tempTaskObject.taskname= doc.data().taskname
          tempTaskObject.duedate= doc.data().duedate

          // gets epoch date value and stores it
          var epochDate = doc.data().epochdate;

          // gets current time
          const day = new Date();
          let currentTime = day.getTime();

          // finds time remaining in epoch 
          var timeRemaining = epochDate - currentTime;

          // finds how many days are left and rounds down
          var daysLeft = (timeRemaining / 86400000)
          daysLeft = Math.floor(daysLeft)

          tempTaskObject.duein = daysLeft

          tempTaskArray.push(tempTaskObject)

        });
        setTasks(tempTaskArray)

    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });
  }
  getTasks();

The data taken populating state variable “task” is then rendered in component Task seen below:

    <div>
      {tasks.map((task) => (
      <Task
        key={task}
        task__title={task.taskname}
        due__date={task.duedate}
        days__away={task.duein}
      />
    ))}
    </div>

I would be extremely grateful for an explanation of why this is happening. Thanks in advance

I wanna create a recursion to print this pattern with javascript [duplicate]

[50, 41, 32, 23, 14, 5, -4, 5, 14, 23, 32, 41, 50]

I did it but it’s returns undefined!!

let arr = [];
let flag = false;
const recursionPattern = (int1, int2) => {
  if (int1 < 0) {
    flag = true;
  }
  arr.push(int1);
  if (arr[0] == arr[arr.length - 1] && arr.length > 1) return arr;
  else {
    if (flag) recursionPattern(int1 + int2, int2);
    else recursionPattern(int1 - int2, int2);
  }
};

Please do I interprete this ternary operator?

Please if this function was to be converted to a “normal” if else statement, how would it look like?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I want to add another condition, but I’m finding it hard to read or digest the current flow.

Filereader AUDIO file to input type file

I am working on a feature which could drag and drop and browse audio files… browsing file is not giving any issue however the drag and drop should store file in input[type="file"].
Kindly tell me if there is any possible solution for this. If there is no solution for this then tell me if there is any work around.

<main class="container">
    <div>
      <form action="" class="w-100 pt-5" enctype="multipart/form-data" method="POST">
        <div class="uploadBox">
          <i class="fas fa-cloud-upload-alt"></i>
          <h2 class="text-center">Drag & Drop to Upload File</h2>
          <span class="text-center">OR</span>
          <label class="btn btn-outline-dark btn-lg" for="uploadBTN">&nbsp;&nbsp;Browse File&nbsp;&nbsp;</label>
          <input type="file" name="uploaded-file" id="uploadBTN" hidden />
        </div>
        <div class="tagsInput mt-3">
          <div class="form-div d-flex row justify-content-between">
            
          </div>
          <div class="form-div row d-flex justify-content-between mt-3">
            
            <input type="submit" name="Submit" class="btn pink-bg text-white mx-auto w-100 px-4 my-3" value="Upload Podcast">

          </div>
        </div>
      </form>
    </div>
  </main>
uploadBox.addEventListener("drop", e => {
    e.preventDefault();

    file = e.dataTransfer.files[0];
    let fileType = file.type;
    console.log(fileType.split("/")[0]);

    if (fileType.split("/")[0] === "audio") {
      uploadedActions(file.name);
      uploadInput.files[0] = file;
      let fileReader = new FileReader();
      fileReader.onload = function () {
        let fileURL = fileReader.result;
      };
      fileReader.readAsDataURL(file);
    } else {
      alert("This is not an audio file.");
      uploadBox.classList.remove("active");
    }
  });

Managing different endpoints for the same resource with react-query

Lets say I have a /products endpoint and also /product/{id} and I’m populating a page using react query, by calling the /products

const products = useQuery('products', queryRepo.getAllProducts)

But I could also fetch an individual product using

useQuery(['product', productId], () => queryRepo.getProduct(productId));

So, I have a mutation to update, say, a product’s price, and using a mutation and optimistic updates (As per the react query docs)

The react query docs state this can be done as follows

 useMutation(updateTodo, {
   // When mutate is called:
   onMutate: async newTodo => {
     // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
     await queryClient.cancelQueries('todos')
 
     // Snapshot the previous value
     const previousTodos = queryClient.getQueryData('todos')
 
     // Optimistically update to the new value
     queryClient.setQueryData('todos', old => [...old, newTodo])
 
     // Return a context object with the snapshotted value
     return { previousTodos }
   },
   // If the mutation fails, use the context returned from onMutate to roll back
   onError: (err, newTodo, context) => {
     queryClient.setQueryData('todos', context.previousTodos)
   },
   // Always refetch after error or success:
   onSettled: () => {
     queryClient.invalidateQueries('todos')
   },
 })

What I want to happen, is to call the mutation (Which will update the price, and optimistically update the products array, and finally, query the data again)

However, as I have the ability to get ALL products or just 1, how can these best be ‘linked’ It seems a shame to pull all the data

My Questions are;

  1. Is there a design / better design for this pattern? (I don’t want to call the ones by ID 50 times to load the page, but I also dont want to fetch 50 items at once to update 1 item)

  2. Is it somehow possible to use the getProduct useQuery hook above to update the ‘products’ data state, because react-query knows that they are the same data. getAllProducts returns an array, would it be better to be an indexed object so getProduct can update an individual product?

  3. In the case of the getProduct useQuery, is there a way to define this without a productId to tell react-query how to get an individual product.

Thanks. Maybe I’m hoping react-query is more clever than it is, or maybe I’m just confused !