Make a preventBack function not work on a certain url

I’m making a webpage to learn a bit of programming, this is my very first one, so I’m really new to this. I have a preventBack function that I’ve found on here, it works great, but I want a certain page (specifically the name is restart.html) not be affected by this script. I have been searching for some time and tried different solutions and implementations to the code but as I’m new to this, nothing has worked as I wanted to.

This is the function:

function preventBack() {
            window.history.forward();
        }
        setTimeout("preventBack()", 0);
        window.onunload = function () { null };

This is written in page1.html (for example), and it affects page2.html (because of the window.history.forward, if I’m not mistaken). I don’t really care where it is written, or even if the whole script changes, but I just want it to change behaviour so if you’ve clicked the restart button by mistake, you can just go back to the previous page and continue. I’ve tried it with if and else, also changing the number for the timeout, but it doesn’t work as I want it to.

HTML: Select multiple items dropdown

I found following code here on Stack Overflow.

$(".chosen-select").chosen({
  no_results_text: "Oops, nothing found!"
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.jquery.min.js"></script>
<link href="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.min.css" rel="stylesheet"/>

<form action="http://httpbin.org/post" method="post">
  <select data-placeholder="Begin typing a name to filter..." multiple class="chosen-select" name="test">
    <option value=""></option>
    <option>American Black Bear</option>
    <option>Asiatic Black Bear</option>
    <option>Brown Bear</option>
    <option>Giant Panda</option>
    <option>Sloth Bear</option>
    <option>Sun Bear</option>
    <option>Polar Bear</option>
    <option>Spectacled Bear</option>
  </select>
  <input type="submit">
</form>

In this question:
HTML: Select multiple as dropdown

But my implementation does not work.

I copied code above (without the first part $) and pasted it (without modification) in my .php page. Then i tried to run the code but my output looks like this.

My output

I do not include any other libraries or other codes apart from the three within the code snippet.
What should i do in order for it to work?

How can I get user’s poll answers?

I have a site with form, which user have to complete. After completing the form user clicks “Send Data” button. the “data” variable is an object into which all information from the form is written. How can I get variable data from which user? The best way for me – to create a result.html page and write “data” value there, but how?

How to Get data from a window to another one with Angular and Subject?

I would like to get data from a first windows and display them in console on another one in an Angular App. I can’t use cookies or local storage so I’m trying to do that via a Subject.

I created a service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {  
    private dataSubject = new Subject<any>();
  
    sendData(data: any) {
      this.dataSubject.next(data);
    }
  
    clearData() {
      this.dataSubject.next();
    }
  
    getData() {
      return this.dataSubject.asObservable();
    }
  
  
}


I made 2 components, one for each window.

In the first component, I have a button to send data

import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared-service.service';

@Component({
  selector: 'app-page1',
  templateUrl: '<button (click)="click()">Send data</button>',
  styleUrls: ['./page1.component.css']
})
export class Page1Component implements OnInit{
  
  constructor(private sharedService: SharedService) { }

  ngOnInit(): void {
    this.sharedService.getData().subscribe((data) => {
      console.log(data)
    });
  }

  click(){
    this.sharedService.sendData('test');
  }
}

In the second document, I would like to get the ‘test’ string from the first window to the console

import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared-service.service';

@Component({
  selector: 'app-page2',
  templateUrl: './page2.component.html',
  styleUrls: ['./page2.component.css']
})
export class Page2Component implements OnInit{

  constructor(private sharedService: SharedService) { }

  ngOnInit() {

    this.sharedService.getData().subscribe((data) => {
      console.log(data)
    });
  }
}

I’m new with Angular. Is someone can give me some advice ? Is this the good way to do or should I do something else ?

how to fetch specific data from API using RTK Query?

firstly I am new to RTK Query. I am trying to fetch some specific data from API but I don’t understand how to do it. If anyone can help me it will be great.

My API link: https://api.spacexdata.com/v3/launches

I just need some specific data like flight_number, mission_name, upcoming, launch_date_utc, rocket_name, launch_success, mission_patch_small .

I already fetched data but can’t able to fetch particular data what I want, don’t understand how to do it.

My code:
App.tsx:

import { useMissionsQuery, useMissionQuery } from "./services/missionsApi";
import "./App.css";

const App = () => {
  const { data, error, isLoading, isFetching, isSuccess } = useMissionsQuery();

  return (
    <div className="App">
      <h1>SpaceX Launches: Mission</h1>
      {isLoading && <h2>...Loading</h2>}
      {isFetching && <h2>...Fetching</h2>}
      {error && <h2>Something went wrong</h2>}
      {isSuccess && (
        <div>
          {data?.map((mission) => {
            return (
              <div className="data" key={mission.flight_number}>
                <span>{mission.mission_name}</span>
                <span>
                  <MissionDetail flight_number={mission.flight_number} />
                </span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export const MissionDetail = ({ flight_number }: { flight_number: string }) => {
  const { data } = useMissionQuery(flight_number);
  return <pre>{JSON.stringify(data, undefined, 2)}</pre>;
};

export default App;

services/missionsApi.tsx:

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { Mission } from "../models/mission.model";

export const missionsApi = createApi({
  reducerPath: "missionsApi",
  baseQuery: fetchBaseQuery({
    baseUrl: "https://api.spacexdata.com/v3/launches",
  }),
  endpoints: (builder) => ({
    missions: builder.query<Mission[], void>({
      query: () => "/",
    }),
    mission: builder.query<Mission, string>({
      query: (flight_number) => `/${flight_number}?`,
    }),
  }),
});

export const { useMissionsQuery, useMissionQuery } = missionsApi;

model
mission.model.ts:

export interface Mission {
  flight_number: string;
  mission_name: string;
  upcoming: string;
  launch_date_utc: string;
  rocket: string;
  rocket_name: string;
  launch_success: string;
  links: string;
  mission_patch_small: string;
}

and store.ts

import { configureStore } from "@reduxjs/toolkit";
import { missionsApi } from "./services/missionsApi";

export const store = configureStore({
  reducer: {
    [missionsApi.reducerPath]: missionsApi.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(missionsApi.middleware),
});

Prevent useEffect hook with two dependencies from running twice

I want to use two properties of a state in the same useEffect hook:

state.keyEvent: keydown from document (to listen to commands like Ctrl + R).

state.value: value of input (to use the value of input).

import { useEffect, useReducer } from "react";

const App = () => {
  const initialState = { keyEvent: {}, value: "builder" };
  const [state, updateState] = useReducer(
    (state: any, updates: any) => ({ ...state, ...updates }),
    initialState
  );

  function handleInputChange(event: any) {
    updateState({ value: event.target.value });
  }

  function handleDocumentKeyDown(event: any) {
    updateState({ keyEvent: event });
  }

  useEffect(() => {
    document.addEventListener("keydown", handleDocumentKeyDown);

    return () => {
      document.removeEventListener("keydown", handleDocumentKeyDown);
    };
  }, []);

  useEffect(() => {
    // if value is updated render but ignore key
    // if key is updated render and ignore
    console.log("keyEvent:", state);
  }, [state]);

  return (
    <div>
      <input
        id="input"
        type="text"
        onChange={handleInputChange}
        value={state.value}
      />
    </div>
  );
};

export default App;

This works—except the useEffect hook runs twice.

I think I have to tell the code: If state.value updates, ignore state.keyEvent and don’t run the hook again.

Is that correct? If so, how to accomplish this?

Edit useState same value rerender (forked)

Note: if I put state.keyEvent and state.useEffect in different useEffect hooks, I won’t be able to have the latest value of state.value in the hook containing state.keyEvent (because the hook containing state.keyEvent will run first than the hook containing state.value).

Issue with an event from a javascript widget (Tradingview) where only first added event is triggered when created on a loop

I have the following issue with a javascript chart widget Im using. I think my issue is more to do with my logic than with a problem with the chart library itself. I have already asked this on their GitHub repo, but again I believe this is just me not doing this properly.

This javascript widget provides events that I can act upon. This is a javascript library from TradingView (chart library), it has a function to create a line on the chart. This function is called .createOrderLine(). When you create an orderLine, it returns an object that you can manipulate (set price, events, etc)

This object has an event called onMove(), with a callback function that I can write code to. So what I am doing is, looping through an array of orders and creating a line on the chart for each order that exists. So every time I move a line on the chart, this callback is called.

When the chart is loaded initially, I add each line object to a Map by setting its key to the orderID and the value to the object itself. If I can’t find the orderID on the map, I will set it to the map.

The issue Im having that I can not figure out is, every time I move ANY of the lines created, only the code from the first order added is triggered, ie: the console.log(order.OrderID) always returns the id of the first line created, no matter which line I move. So in essence, it seems the onMove() from the first order is the only one that runs.

Here is some simplified version of my logic / code:


var objectMapOrders = new Map();

for(var order of currentSelectedMarketOrderIds){

    var apiOrderObject = objectMapOrders.get(parseInt(order.OrderID))
    if(!apiOrderObject){
    
        var apiOrderObject = widget.activeChart()
        .createOrderLine()
        .setPrice(order.EntryPrice)
        
        objectMapOrders.set(parseInt(order.OrderID), apiOrderObject);
    
    
    }else{
    
        apiOrderObject
        .setPrice(order.EntryPrice)
        .onMove(async function() {
            //Call function that updates the order price
            console.log(order.OrderID)
            updateOrder(order.OrderID,this.price())
    
        })
    
    }

}

Not sure if Im using the Map correctly or if there’s an alternative way that I can make this work?

I have tried all sorts of changes around (setting the onMove on inside each if block) to no avail

Can’t resolve module (not found) in React.js

ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./src/index.css) 5:36-88 Module not found: Error: Can’t resolve ‘./public/

i cant find this error answer anybody can help me

How do I issue an alert and restart the application if the function is running too long?

There is a calculator that works through expo.There is a function that performs counting. However, if you enter a very large expression with a factorial there, for example, the calculator will hang tightly, as in the case, for example, if the counting function works for more than 3-5s and does not produce a result, issue an error and restart / throw it out of the application

 const getResult = () => {


        return (<TextInput
                onContentSizeChange={x => {
                    //console.log(x)
                }}
                editable={true}
                style={styles.expression}
                multiline={true}
                keyboardType={"number-pad"}
                textAlign="right"
                textAlignVertical="top"

            >{highlight(expr)}</TextInput>

        )

    }

    const Display = () =>
        <View style={styles.display}>
            {}

                {getResult()}

            {}
        </View>

Here is the function itself that returns the result
I tried to do
Put

var t0 = performance.now();

before GetResult()
and




     var t1 = performance.now();
    if (t1-t0>0.01) {

        BackHandler.exitApp();

    }

    console.log("Call to doSomething took " + ( t1-t0) + " milliseconds.")

after Display(), however, when the application freezes, it does not return the end time of the function, so exiting the application does not work, please help fix it.

how to pass data to another screen in react native (and how to receive it)?

i want to pass data from this screen (Lihat.js)

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { style } from './Style';

class Lihat extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nama:'',
      nim:'',
      prodi:'',
      no_telp:'',
      alamat:'',
      listData:[],
    };
    this.url = "http://192.168.100.161/mhs/mhs.php"
    // this.url = "http://192.168.162.248/mhs/mhs.php"
  }
  componentDidMount(){
    this.ambilListData()
  }
  async ambilListData(){
    await fetch(this.url)
    .then((response)=>response.json())
    .then((json)=>{
      console.log("hasil :"+JSON.stringify(json.data.result))
      this.setState({listData:json.data.result})
    })
    .catch((error)=>{
      console.log(error);
    })
  }
  async klikDelete(id){
    await fetch(this.url+"/?op=delete&id="+id)
    .then((response)=>response.json())
    .then((json)=>{
      alert('Data berhasil didelete');
      this.ambilListData();
    })
    .catch((error)=>{
      console.log(error)
    })
  }
  render() {
    return (
      <View style={style.lihatWrapper}>
        <View style={style.viewData}> 
        {
          this.state.listData.map((val,index)=>(
            <View style={style.viewList} key={index}>
                <Text style={style.textListNama}>Nama :{val.nama}</Text>
              
              <View style={{flexDirection:'column'}}>

              {/* i want to pass data from this button / link */}
              <Text style={style.textListLihat} onPress={()=>this.props.navigation.navigate('Detail',{id:this.state.listData.map()})}>Detail</Text>


              <Text style={style.textListEdit} onPress={()=>this.props.navigation.navigate('Update')}>Edit</Text>
              <Text style={style.textListDelete} onPress={()=>this.klikDelete(val.id)}>Delete</Text>
              </View>
            </View>
          ))
        }
        </View>
      </View>
    );
  }
}

export default Lihat;

to this screen (Detail.js)

import { TabRouter, validatePathConfig } from '@react-navigation/native';
import React, { Component } from 'react';
import { View, Text, FlatList, SafeAreaView} from 'react-native';
import { style } from './Style';
import Lihat from './Lihat';

class Detail extends Component {
  route
  constructor(props) {
    super(props);
    this.state = {
        nama:'',
        nim:'',
        prodi:'',
        no_telp:'',
        alamat:'',
        listData:[]
    };
    this.url = "https://192.168.100.161/mhs/mhs.php"
    // this.url = "http://192.168.162.248/mhs/mhs.php"
  }
  componentDidMount(){
    this.ambilListData()
  }
  async ambilListData(){
    await fetch(this.url)
    .then((response)=>response.json())
    .then((json)=>{
      console.log("hasil: "+json.data.result)
      this.setState({listData:json.data.result})
    })
    .catch((error)=>{
      console.log(error);
    })
  }
  render() {
    return (
      <View style={style.viewWrapper}>
        <Text style={style.content}>
        {
          this.state.listData.map((val,index)=>(
            <View style={style.viewList} key={index}>
              <Text style={style.textListNama}></Text>
              <Text style={style.textListNama}></Text>
            </View>
          ))
        }
        </Text>
      </View>
    );
  }
}

export default Detail;

so when i press ‘detail’, the screen will navigate to detail.js and display the data detail.

Lihat.js
enter image description here

Thanks

i already read react native passing data tutorial. but i cant understand it. and when i search on youtube mostly the tutorial is using axios.

assign output of external JS function to NextJS variable

I’m a JS/TS newbie, but have to enable a feature into our existing NextJS app. That feature is to integrate an externe JS script of a service called Rewardfull.
At some point on my checkout page I need an ID generated by that external script for the next part in my checkout flow. But I have no idea how to get that ID inside the JS script into my TypeScript NextJS namespace.

In _app.tsx i load the external scripts.

<Script strategy="afterInteractive">
    {`(function(w,r){w._rwq=r;w[r]=w[r]||function(){(w[r].q=w[r].q||[]).push(arguments)}})(window,'rewardful');`}
</Script>
<Script
  strategy="afterInteractive"
  src="https://r.wdfl.co/rw.js"
  data-rewardful="xxx">
</Script>

In my checkout.tsx page I can do:

<Script>
  {`rewardful('ready', function() {
    console.log('Rewardful Ready!')
    if(Rewardful.referral) {
      // The current website visitor is a referral from an affiliate.
      console.log('referal: ',Rewardful.referral );
      // how to get Rewardful.referral into a variable here
    }
  });`}
</Script>

So now my question is how tho the the Rewardful.referral into a NextJS variable for the next steps in the checkout flow. Does anybody have an idea? There is no React/npm package available, only that external JS script.

How to operate with more than 2 numbers [duplicate]

I’m trying to build a calculator with HTML, CSS and JS but I can’t fix how to operate for example 1 + 2 + 3. Right now I’m getting 5 as a result with my actual code and the correct result should be 6. Here you have all my JS. Hope someone can help me. If you need the HTML let me know!

I want to operate with more than 2 numbers.

let operacion1;
let operacion2;
let performance;

const iniciamosCalculadoraPRO = () => {
  let resultado = document.getElementById("resultado");
  let reset = document.getElementById("reset");
  let suma = document.getElementById("suma");
  let minus = document.getElementById("minus");
  let multi = document.getElementById("multi");
  let divi = document.getElementById("divi");
  let equal = document.getElementById("equal");
  let root = document.getElementById("root");
  let one = document.getElementById("one");
  let two = document.getElementById("two");
  let three = document.getElementById("three");
  let four = document.getElementById("four");
  let five = document.getElementById("five");
  let six = document.getElementById("six");
  let seven = document.getElementById("seven");
  let eight = document.getElementById("eight");
  let nine = document.getElementById("nine");
  let cero = document.getElementById("cero");
};


one.onclick = function() {
  resultado.textContent = resultado.textContent + "1";
};
two.onclick = function() {
  resultado.textContent = resultado.textContent + "2";
};
three.onclick = function() {
  resultado.textContent = resultado.textContent + "3";
};
four.onclick = function() {
  resultado.textContent = resultado.textContent + "4";
};
five.onclick = function() {
  resultado.textContent = resultado.textContent + "5";
};
six.onclick = function() {
  resultado.textContent = resultado.textContent + "6";
};
seven.onclick = function() {
  resultado.textContent = resultado.textContent + "7";
};
eight.onclick = function() {
  resultado.textContent = resultado.textContent + "8";
};
nine.onclick = function() {
  resultado.textContent = resultado.textContent + "9";
};
cero.onclick = function() {
  resultado.textContent = resultado.textContent + "0";
};
reset.onclick = function() {
  resCalculator();
};
suma.onclick = function() {
  operacion1 = resultado.textContent;
  performance = "+";
  clearAll();
};
minus.onclick = function() {
  operacion1 = resultado.textContent;
  performance = "-";
  clearAll();
};
multi.onclick = function() {
  operacion1 = resultado.textContent;
  performance = "*";
  clearAll();
};
divi.onclick = function() {
  operacion1 = resultado.textContent;
  performance = "/";
  clearAll();
};
equal.onclick = function() {
  operacion2 = resultado.textContent;
  showingResults();
};

root.onclick = function() {
  operacion1 = resultado.textContent;
  rootOperation();
}

punto.onclick = function() {
  if (!resultado.textContent.includes(".")) {
    resultado.textContent = resultado.textContent + ".";
  }
}




const clearAll = () => {
  resultado.textContent = "";
}

const resCalculator = () => {
  resultado.textContent = "";
  operacion1 = 0;
  operacion2 = 0;
  performance = "";
}

const rootOperation = () => {
  resultado.textContent = Math.sqrt(operacion1).toFixed(3);
}



const showingResults = () => {
  let resultadosGlobales = 0;
  switch (performance) {
    case "+":
      resultadosGlobales = parseFloat(operacion1) + parseFloat(operacion2);
      break;

    case "-":
      resultadosGlobales = parseFloat(operacion1) - parseFloat(operacion2);
      break;

    case "*":
      resultadosGlobales = parseFloat(operacion1) * parseFloat(operacion2);
      break;

    case "/":
      resultadosGlobales = parseFloat(operacion1) / parseFloat(operacion2);
      break;
  }
  resCalculator();
  resultado.textContent = resultadosGlobales;
}

Why when setting the state in react doesn’t give the right value all the time?

So, I am making a todolist app and I have this code:

./components/Overlay.js
import { useState } from "react";

function Overlay({Task, SetTask}) {
    const [priority, setPriority] = useState('');
    const [text, setText] = useState('');
    return ( 
        <div className="bg-[#040e16] p-10 rounded-3xl">
            <input type="text" className="bg-[#0d1821] mr-3 w-[30rem] h-10 text-lg rounded-lg p-2" value={text} onChange={e => setText(e.target.value)}/>
            <button className="bg-[#0d1821] p-2 w-16 rounded-lg hover:bg-[#3b42a4] transition-all" onClick={() => {SetTask({
                text: text,
                priority: priority
            });
            console.log(Task)}}>Add</button><br />
            <p>Priority: {priority}</p> <br />
            <button onClick={() => setPriority('high')}><img src="/hi-priority.png" alt="" className="w-12 hover:bg-[#3b42a4] mr-5 transition-all rounded-2xl"/></button>
            <button onClick={() => setPriority('medium')}><img src="/md-priority.png" alt="" className="w-12 hover:bg-[#3b42a4] mr-5 transition-all rounded-2xl"/></button>
            <button onClick={() => setPriority('low')}><img src="/lo-priority.png" alt="" className="w-12 hover:bg-[#3b42a4] mr-5 transition-all rounded-2xl"/></button>
        </div>
     );
}

export default Overlay;
import { useState } from "react";
import NavBar from "../../components/NavBar";
import Overlay from "../../components/Overlay";
function Dashboard() {
    const [on, setOn] = useState(false);
    const [task, setTask] = useState({
        text: "",
        priority: "",
    })
    
    return ( 
        <div className="">
            <NavBar
            onClick={() =>{
                setOn(!on);
            }}
            />
            <div className="p-5">
                {on ? <Overlay Task={task} SetTask={setTask} /> : <span></span>}
            </div>
            

        </div>
     );
};
export default Dashboard;

when I console.log(task);
I use the useState with a setter function (as normal) but when updating it (when you click add) I have a delay like shown in the picture but the second time it just works, I am sure there is some problem in my code can anybody help me with it
I don’t always get the right output, it is delayed for example like this
when clicking the add button

Cannot delete file on aws s3 bucket

I am working on Nodejs and Expressjs applications. I want to delete an image on Aws-s3 which I uploaded with multer-s3.

I have tried so many examples that I saw online but none of them worked. For instance :

aws.config.update({
  secretAccessKey: '*******************',
  accessKeyId: '*****************',
  region: 'eu-west-3',
});

const s3 = new aws.S3();


  s3.deleteObject({ Bucket: 'schubox', Key: rayon.img }, (err, data) => {
    if (err) console.error(err);
    else console.log(data);
  });

This code does not throw any errors but nothing is deleted on the S3 side.
where am I making a mistake?