Promise all with axios in react native app

I’m making a react-native weather forecast app. And I’m trying to get all the data using 2 promise all methods

This is the function I call in useEffect

async function getData(){
  try{

    Promise.all(_.map(savedPlaces, getCurrentWeather)).then((response) => {console.log("current", response.data)})
    Promise.all(_.map(savedPlaces, getDailyWeather)).then((response) => {console.log("daily", response.data)})

  }
  catch(error){
    console.log(error)
  }
}

The savedPlaces variable is an array with names of the cities I want to get the weather for

And this is one of the two fuctions i use to get the data

const getCurrentWeather = async (places) =>{

  const options = {
    method: 'GET',
    url: 'https://community-open-weather-map.p.rapidapi.com/weather',
    params: {q: places.name, lang: 'null', units: 'metric', mode: JSON},
    headers: {
      'x-rapidapi-host': 'community-open-weather-map.p.rapidapi.com',
      'x-rapidapi-key': 'xxx'
    }
  };

  const request = await axios.request(options).then(response => {console.log(response.data)})

  return request

}

The other funtion is basicaly the same except little changes in options

And the issu is that I can see the data in print out in this code fragment

.then(response => {console.log(response.data)})

inside the getCurrentWeather functions but when I try to print them out in .then after Promise.all I get undefined, same with the other function.

current [undefined, undefined]

And I’m asking how to properly do it

How to bring it back the eventListener after replaceChild in vanila javascript?

Well I wanna ask something about replaceChild in here and I was got trouble when I used that function, so the problem is when I have some function addEventListener on my button, when I was replace the old button to new element then bring back again, my event listener on my old button doesn’t work like before, any suggest to keep my event listener work on my button when my button was replace? Oh ya in bellow I will give you all the link of example of my problem, you can access to understand more about my problem, thanks before have a nice day!

Link : Replace Child Problem

How do we pass a java variable with a jsp scriptlet tag in the java script onkeyup event function?

   <%String nameId[] ={"006","007"};%>

    <html:text styleId="<%=nameId[1]%>" onkeyPress="return validation(<%=nameId[1]%>,'number',0);">

The above jsp page code takes the onKeyPress javascript validaiton function like** return validation(<%=nameId[1]%>,’number’,0);**not asreturn validation(‘007′,’number’,0);

Is it possible to pass the variable like this?

How to save data from an html obtained after making an html POST request

I am making a web application to be able to store products, and I would like to add the functionality of obtaining the name automatically, for this I am using “Web scrapping” in a web page which, through the barcode, gives me the name of the product, the page It works through http requests, for now the closest I’ve been I found it here

JavaScript post request like a form submit.

I need the page, instead of being redirected, to store what it returns (the http page) in a variable, in order to obtain the data I need.
The code I have so far is the following, however I can’t prevent it from being redirected.

function post(path, params, method = 'post') {

        // The rest of this code assumes you are not using a library.
        // It can be made less verbose if you use one.
        const form = document.createElement('form');
        form.method = method;
        form.action = path;

        for (const key in params) {
            if (params.hasOwnProperty(key)) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = params[key];

                form.appendChild(input);
            }
        }
        const a = document.body.appendChild(form);
        console.log(a)
        console.log(form)
        console.log('fsdfsdfds')
        form.submit();
    }


const htmlResult = post('http://gs1ecapp.com/gs1app/', { codigo: "7707211630493", action: "gtin" });

By the way, I used this method because I need to use “Content-Type: form-data” in order to correctly send the parameters in the http request. I used PostMan to try to send in another format, but it is not possible.

Any hint that will help me with this would be greatly appreciated.

Form values from custom HTML element input field not displaying when using on-screen keyboard

I am trying to get values that I type using an on-screen keyboard into a custom HTML element input field to display.

However I am currently getting empty strings. If I use a normal input field then it works fine.

Here is a snippet of my code and a stackblitz example which will have detailed code.

HTML

<form-input
    appOskInput
    [formStatus]="formStatus"
    [parentFormGroup]="setupForm"
    [data]="{
             formControlName: 'email',
             name: 'email'
            }">
</form-input>

<app-keyboard></app-keyboard> 

Keyboard directive

 private onKey(key: string) {
    let element = this.el.nativeElement;
    let inputEl = element.querySelector('input');
    let start = inputEl.selectionStart;
    let end = inputEl.selectionEnd;
    this.measure.textContent = inputEl.value.substr(0, start) + key;
    inputEl.value = inputEl.value.substr(0, start) + key + inputEl.value.substr(end);
    if (this.control)
    this.control.control.setValue(inputEl.value)
    inputEl.focus();
    inputEl.selectionStart = inputEl.selectionEnd = start + 1;
    this.updateScrollPosition();
 }

Here is the stackblitz https://stackblitz.com/edit/onscreen-keyboard-hlmkvv?file=src/app/app.component.ts

You will see that the values are displaying when inputted from a normal input field but I can’t get the same to happen when using my custom HTML element input field. I have commented out the custom HTML input field in the code on the HTML page. Can anyone help please?

How to get values from 2 dynamic input fields (React Native)

Currently, I can successfully create 2 dynamic fields but when I am trying to get the data of those 2 fields only one is getting pushed(data)

Here’s my code

    const [inputs, setInput] = useState([{size:'', price:''}]); //For sizes and price

    const addHandlerAdons = () => {
        const _inputs = [...inputsAdons];
        _inputs.push({key: '', value: ''});
        setInputAdons(_inputs);
    }

    const deleteHandlerAdons = (key) => {
        const _inputs = inputsAdons.filter((inputAdons,index) => index != key);
        setInputAdons(_inputs);
    }

    const inputHandlerAdons = (text, key) =>{
        const _inputs = [...inputsAdons];
        _inputs[key].key = text;
        _inputs[key].key = key;
        setInputAdons(_inputs);
    }

here’s my display

<View style={{flex:1, marginTop: 15}}>
  <View style={{flex:1, flexDirection: 'row', marginLeft:25, marginRight:25, alignItems: 'center'}}>
    <View style={{flex:0.1}}>
      <TouchableOpacity onPress={()=> addHandlerAdons()}>
        <AntD name={ "pluscircle"} size={20} color={ "yellow"}/>
      </TouchableOpacity>
    </View>
    <View style={{flex:1}}>
      <Text style={styles.txtAdds}>Add-Ons (Optional)</Text>
    </View>
  </View>
</View>
<View style={{flex:1}}>
  {inputsAdons.map((input, key) =>(
  <View key={key} style={{flexDirection: 'row', marginLeft:25, marginRight:25, alignItems: 'center'}}>
    <View style={{flex:0.5}}>
      <TextInput placeholder="Enter size" style={{ borderBottomColor: '#ccc', borderBottomWidth: 1, color: '#000' }} placeholderTextColor="#ccc" // value={input.value} onChangeText={(text)=> inputHandlerAdons(text,key)} />
    </View>
    <View style={{flex:0.1}}></View>
    <View style={{flex:0.3}}>
      <TextInput placeholder="Enter price" style={{ borderBottomColor: '#ccc', borderBottomWidth: 1, color: '#000' }} placeholderTextColor="#ccc" // value={input.value} onChangeText={(text)=> inputHandlerAdons(text,key)} />
    </View>
    <View style={{flex:0.1}}></View>
    <View style={{flex:0.1}}>
      <TouchableOpacity onPress={()=> deleteHandlerAdons(key)}>
        <AntD name={ "minuscircle"} size={15} color={ "red"}/>
      </TouchableOpacity>
    </View>
  </View>
  ))}
</View>

When I tried to print out the output

INPUTS: [“Large”]

expected output:

size: Large , price: 90

Exporting Html with image to word

enter image description here

I am using filesaver.js and jquery.wordexpoert.js in which

// Embed all images using Data URLs
        var images = Array();
        var img = markup.find('img');
        
        for (var i = 0; i < img.length; i++) {
            // Calculate dimensions of output image
            var w = Math.min(img[i].width, options.maxWidth);
            var h = img[i].height * (w / img[i].width);
            // Create canvas for converting image to data URL
            var canvas = document.createElement("CANVAS");
            canvas.width = w;
            canvas.height = h;
            // Draw image to canvas
            var context = canvas.getContext('2d');
            context.drawImage(img[i], 0, 0, w, h);
            // Get data URL encoding of image
            **var uri = canvas.toDataURL("image/jpg");**//this part throws error tainted canvas (as shown in image above).
            $(img[i]).attr("src", img[i].src);
            img[i].width = w;`enter code here`
            img[i].height = h;
            // Save encoded image to array
            images[i] = {
                type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
                encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
                location: $(img[i]).attr("src"),
                data: uri.substring(uri.indexOf(",") + 1)
            };
        }

I am trying to export an HTML div to a word document in asp.net for which I used javascript.

How to handle onloadedmetadata event?

When we have a video file which browser can not play (issue might due to formats or codec), I want to inform the user that the file can not be plyed by the browser.

In the case of browser being unable to play the video (due to unsupportive format or codec), onloadedmetadata event does not get fired.

I would like to know-

  1. Is there an event which fires when metadata load fails?
  2. Is there an error handler for onloadedmetadata event?

min and max validation is firing when i am not using array, but not firing when i use array controls

As you can see in this stack blitz example min and max validation is firing

https://stackblitz.com/edit/angular-mat-form-field-icrmfw

But in the below stack blitz, I have made an array of the same controls , but the validation is not firing

https://stackblitz.com/edit/angular-mat-form-field-hmmm69

    <form class="form" [formGroup]="configWeightage">
  <table class="DSA_custom-table col-md-6">
    <thead>
      <tr>
        <th scope="col">Category</th>
        <th scope="col">Weightage</th>
      </tr>
    </thead>
    <tbody>
      <ng-container>
        <tr
          *ngFor="let order of configWeightage.get('weightageFormArray').controls; let i = index"
          formArrayName="weightageFormArray"
        >
          <td>{{j_s_weightage[i].name}}</td>
          <td>
            <div class="example-container">
              <mat-form-field>
                <input
                  matInput
                  type="number"
                  class="example-right-align"
                  formControlName="i"
                  id="weightage"
                  required
                />
                <mat-error
                  *ngIf="configWeightage.get('weightageFormArray').hasError('min')"
                  >Please enter greater than 0</mat-error
                >
                <mat-error
                  *ngIf="configWeightage.get('weightageFormArray').hasError('max')"
                  >Please enter less than 100</mat-error
                >
              </mat-form-field>
            </div>
          </td>
          <td>%</td>
        </tr>
      </ng-container>
      <tr>
        <td>Total Weightage</td>
        <td class="text-center"><label>{{weightage}}</label></td>
      </tr>

      <tr>
        <td></td>
        <span class="DSA_wb_caption text-primary text-right"
          >Sum of weightage should be 100.</span
        >
      </tr>
    </tbody>
  </table>
</form>

This is my class file

    import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl,
  FormArray,
} from '@angular/forms';

/** @title Form field with prefix & suffix */
@Component({
  selector: 'form-field-prefix-suffix-example',
  templateUrl: 'form-field-prefix-suffix-example.html',
  styleUrls: ['form-field-prefix-suffix-example.css'],
})
export class FormFieldPrefixSuffixExample {
  configWeightage: FormGroup;
  formBuilder: FormBuilder;
  hide = true;
  services: FormArray;
  weightageValueArray = [];
  j_s_weightage = [];
  attrWeightage: any = { name: '' };
  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.configWeightage = this.fb.group({
      weightageFormArray: new FormArray([], [Validators.required, Validators.min(0), Validators.max(100)])
    });
    
    this.attrWeightage.name = "flexiblity";
    this.j_s_weightage.push(this.attrWeightage);
    this.attrWeightage = { name: '' };
    this.attrWeightage.name = "flexiblity2";
    this.j_s_weightage.push(this.attrWeightage);
    this.weightageValueArray.push(60);
    this.weightageValueArray.push(40);
    // console.log(this.configWeightage)
    this.services = this.configWeightage.get('weightageFormArray') as FormArray;
    let dbSize = this.services.length;
    for (; 0 < dbSize; dbSize--) {
      this.services.removeAt(dbSize - 1);
    }
    this.j_s_weightage.map((o, i) => {
      const control = new FormControl(0);
      (this.configWeightage.controls.weightageFormArray as FormArray).push(control);
    });
  }
}

persistent service worker – chrome extension manifest v3

I’m currently developing a chrome extension that requires the background script to perform a check roughly every second.

Before manifest v3 I was able to just run an interval in the background script but with service workers now I wasn’t able to find a clean way to replicate it 100%. I’ve come up with a solution that seems to work:

https://gist.github.com/ayoung19/e6f7ec367c0dd47c0b6a7b7bae51cdaf

Is this the best way to do what I need? Any suggestions are greatly appreciated!

Can a function be used to redirect?

so I have a developing a trivia game and I have am trying to have a function redirect to a page that tells them if the answer was correct or not. Below shows what I have going on.

My functions to check the answers that the end user inputed.

function Question(stem, answer, type){
    this.stem = stem; 
    this.answer = new Array(rowLimit);
    this.answer.push(answer);
    this.type = type;
}
function score(userAnswer){
    var result = "";
    console.log("Data returning for this.answer: " + this.answer);
    var lowerUserAnswer = userAnswer.toLowerCase().trim();

    for(var a = 2;  a < this.answer.length; a++){
        lowerAnswer = this.answer[a].trim().toLowerCase();
      
        if (type == 1) { // this is a true / false question
            console.log('Inside type 1');
            result = trueFalseResponses(lowerUserAnswer, lowerAnswer);
        } else if (type == 2) {// single word question
            console.log('Inside type 2');
            result = singleWordResponses(lowerUserAnswer, lowerAnswer);
        } else if (type == 3){ // sentence question
            console.log('Inside type 3');
            result = sentenceResponses(lowerUserAnswer, lowerAnswer);
        } else {
            console.log('Inside of else');
            console.log("Question type is needed.");
        }
        return result;
    }
}
function trueFalseResponses(userInput, realAnswer){
   if(userInput.charAt(0) == realAnswer.charAt(0)) {
        console.log('Inside of if trueFalseResponses');
        correctAnswerIncrease();
    }
   else {
        console.log('Inside of else trueFalseResponses');
        incorrectAnswerIncrease();
    }
   return "";
}
function singleWordResponses(userInput, realAnswer){
   if(userInput === realAnswer) {
        console.log('Inside of if singleWordResponses');
        correctAnswerIncrease();
   }
   else {
        console.log('Inside of else singleWordResponses');
        incorrectAnswerIncrease();
   }
   return "";
}
function sentenceResponses(userInput, realAnswer){
   if(userInput.includes(realAnswer)) {
        console.log('Inside of if sentenceResponses');
        correctAnswerIncrease();
   }
   else {
        console.log('Inside of else sentenceResponses');
        incorrectAnswerIncrease();
   }
   return "";
}
function correctAnswerIncrease (req, res, next){
    console.log('Inside of if correctAnswerIncrease');
    incremented = incremented + 1;
    soulTracker = soulTracker + 1;
    res.redirect('/correct');
}
function incorrectAnswerIncrease(req, res, next){
    console.log('Inside of if incorrectAnswerIncrease');
    res.send('/incorrect');
    incremented = incremented + 1;

Web pages that tells them if the response was correct or not…

app.get('/correct', (req, res, next) => {
    res.render('correct');
});
app.get('/incorrect', (req, res, next) => {
    res.render('incorrect');
});
app.post('/correct', (req, res, next) => {
    res.render('correct');
});
app.post('/incorrect', (req, res, next) => {
    res.render('incorrect');
});

So when the answer is inputed, depending on the type of response the question can take, it’s passed from score, to the question type which is either trueFalseResponses, singleWordResponses, or sentenceResponses. If the response was correct, or incorrect, I want the page to redirect them to /correct or /incorrect. However, when I attempted that, I received the following error.

TypeError: Cannot read properties of undefined (reading ‘redirect’)
at correctAnswerIncrease (/Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/catchingSoulsServer.js:244:9)
at trueFalseResponses (/Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/catchingSoulsServer.js:210:9)
at score (/Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/catchingSoulsServer.js:193:22)
at /Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/catchingSoulsServer.js:440:5
at Layer.handle [as handle_request] (/Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/node_modules/express/lib/router/layer.js:95:5)
at /Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/jonathandameus/Library/CloudStorage/OneDrive-Personal/Business Files/Jon Does Tech/Code Development/Personal Project/VisualStudio/Bible Trivia/node_modules/express/lib/router/index.js:341:12)

I have tried to use window.location.href, window.location.href and window.location.replace but that has not helped as well. The goal is to redirect them to /correct or /incorrect if the response from the user was correct or incorrect.

Check the user’s presence on a tab

I want to do something for the sponsor when exactly the sponsor link of my site is clicked. Go to a new tab and open the brush site there, and after staying on the sponsor site for 25 seconds, send a request to the server in JavaScript and ajax.

tip :
Sponsors are not the same.

ReactRouterDOM does not return to ‘home’ page on reload/refresh

In my current project, I am using React Router Dom to navigate between components and allow for a normal web-page look for links.
However, I have run into an issue I have been putting off for a while now.
I currently have 3 components that contain screens within them.
Login, Main, and Viewer.
Login is equivalent to a landing page/home page. It’s path is …/ which is also …/login
Main is where all the data is displayed for user. It’s path is …/main
Viewer is another component with displays attached data for various parts of the main screen. It’s path is …/main/viewer.

Now let’s get into how I’ve done this.
App.js contains these references:

                    <Switch>
                        <Route path="/login" render={(props) => <LoginSequence
                            ...
                        />}/>
                        <Route path="/main" render={(props) => <MainScreen
                            ...
                        />}/>
                        <Redirect path="/" exact to="/login"/>
                        <Redirect path="/protis-react" exact to="/login"/>
                    </Switch>

Within the Login Sequence component, I have a button for submitting data that does a few things for data request and selection on user

    dataSubmitted = () => {
    ...
    this.props.history.push("/main/");
};

It does a few callbacks and receives proper data for user, which it then sets as reference from there on, which gets further data from the server , and then redirects to the Main screen, which is where the bulk of everything is.

Now that I am in the /main screen, if I was to refresh the page, it would not return to the /login like I expect it, but just refreshes the /main screen. Of course, at this point, on a refresh, for safety reasons, there is no data. And while my components are set up to display no data in most cases, it is expected that on a full page refresh, the user would have to log back into the database (At least this is the scope at this stage for how it should operate)

What am I missing, that makes a page-refresh behave this way, rather than redirect to …/login or …/protis-react or just …/ even?

I suspect that it’s the same issue with my Viewer component, since I transfer via RRD the same way, so if this is fixed, I can go for implementing a similar fix to rest of code.