How can I create a bookmarklet that shows all variables in the console?

Is there a way for this code to work as a bookmarklet?

This works when placed in the console but gives an error when used as a bookmarklet.

var variables = ""
for (var name in this)
    variables += name + "n";

When used as a bookmarklet, it gives the following error:

Uncaught SyntaxError: Unexpected token 'for'

Is there any way to fix this?
Thank you for your help!

Access to XMLHttpRequest at from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’

I am facing following problem
Access to XMLHttpRequest at ‘http://127.0.0.1:5000/predict_home_price’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

  function onClickedEstimatePrice() {
    console.log("Estimate price button clicked");
    var sqft = document.getElementById("uiSqft");
    var bhk = getBHKValue();
    var bathrooms = getBathValue();
    var location = document.getElementById("uiLocations");
    var estPrice = document.getElementById("uiEstimatedPrice");
  
    var url = "http://127.0.0.1:5000/predict_home_price"; //Use this if you are NOT using nginx which is first 7 tutorials
    //var url = "/api/predict_home_price"; // Use this if  you are using nginx. i.e tutorial 8 and onwards
  
    $.post(url, {
        total_sqft: parseFloat(sqft.value),
        bhk: bhk,
        bath: bathrooms,
        location: location.value
    },
    function(data, status) {
        console.log(data.estimated_price);
        estPrice.innerHTML = "<h2>" + data.estimated_price.toString() + " Lakh</h2>";
        console.log(status);
    });
  }

ReactJS: Updating one state variable based on another state variable causes the update variable to not render

I’m a ReactJS notive and while related questions on this topic have been asked, but I couldn’t find the answer I’m looking for.

In ReactJS, I have two state variables. When one changes (let’s call it A), I want the other (B) to change. My code currently does this correctly; when I drop breakpoints or log to console, B changes correctly when A changes. However, React does not render the updated B until A changes again. What is the cause, and what is the right React pattern to ensure B renders?

Snippets of my code (happy to answer more)

This is my variable A:

  const [prompt, setPrompt] = useState(params.prompt);

This is my variable B:

  let defaultPromptsResultsArray = [{
    isLoading: true,
    prompt: params.prompt,
    counter: 0,
    URIs: [default_uri]
  }]

  const [promptsResultsArray, setPromptsResultsArray] = useState(defaultPromptsResultsArray);

This is the useEffect that depends on prompt (my state variable A):

  useEffect(() => {

    // Take 0 for the newest prompt.
    const newBackendEventSource = new EventSource(
      url,
      {withCredentials: false})

    console.log('SSE created!');

    newBackendEventSource.addEventListener('open', () => {
      console.log('SSE opened!');
    });

    newBackendEventSource.addEventListener('error', (e) => {
      console.log('SSE error!');
      if (newBackendEventSource.readyState === EventSource.CLOSED) {
        // Connection was closed.
        console.log('SSE readyState is CLOSED')
      }
      console.error('Error: ',  e);
    });

    newBackendEventSource.addEventListener('close', (e) => {
      console.log('SSE closed!');
      const data = JSON.parse(e.data);
      console.log("close data: ", data);
      newBackendEventSource.close();
    });

    newBackendEventSource.addEventListener('message', (e) => {
      const data = JSON.parse(e.data);
      console.log("message data: ", data);

      // Use React Updater function to prevent race condition.
      // See https://stackoverflow.com/a/26254086/4570472
      setPromptsResultsArray((prevPromptsResultsArray) => {
        // Since we preprend new results, we need to compute the right index from
        // the counter with the equation: length - counter - 1.
        // e.g., For counter 2 of a length 3 array, we want index 0.
        // e.g., For counter 2 of a length 4 array, we want index 1.
        // e.g., For counter 3 of a length 7 array, we want index 4.
        // Recall, the counter uses 0-based indexing.
        const index = prevPromptsResultsArray.length - data.counter - 1

        prevPromptsResultsArray[index] = {
          isLoading: false,
          prompt: prevPromptsResultsArray[index].prompt,
          counter: prevPromptsResultsArray[index].counter,
          URIs: [data.uri]}

        return prevPromptsResultsArray
      });
    });

    // Add new backend event source to state for persistence.
    setBackendEventSources(backendEventSources => [
      newBackendEventSource,
      ...backendEventSources])

  }, [prompt]);

This is where my promptsResultsArray is used in the DOM:

          {promptsResultsArray.map((promptResults) => {
            const promptResultsKey = [promptResults.prompt, promptResults.counter].join("_");
            return (
              // Add a fragment ( a fake div ) so we can return 2 elements.
              <Fragment key={promptResultsKey}>
                <p key={`${promptResultsKey}_p1`}>Prompt: {promptResults.prompt}</p>
                {/* Creating keys from multiple values: https://stackoverflow.com/a/40425845/4570472*/}
                <ImageList cols={1} key={promptResultsKey}>
                  {promptResults.URIs.map((URI) => (
                    // Refactor to give each URI its own unique integer ID.
                    <ImageListItem key={[promptResults.prompt, promptResults.counter, 0].join("_")}>
                      <img
                        src={URI}
                        alt={promptResults.prompt}
                        style={{height: 260, width: 1034}}
                      />
                    </ImageListItem>
                  ))}
                </ImageList>
              </Fragment>
            )
          })}

promptsResultsArray is only updated when prompt is updated. Why? How do I ensure promptsResultsArray is also updated when changed by the SSE?

How can I stop a Faundb stream?

I am able to start a FaunaDB stream. The user enters a room name and the function setupStream is called

Once a stream is started, the clock is ticking and resources are being used. I would like to able to stop the stream when the user has been inactive some time. Is there a stop() method on the stream?

export function setupStream(room_name) {
    var query = window.faunadb.query;
    document_reference = query.Ref(query.Collection('rooms'), room_name);
    startStream(client, document_reference);
}

const startStream = (client, document) => {
    const stream = client.stream.document(document)
    .on('snapshot', snapshot => {
        report('snapshot', snapshot);
    })
    .on('version', version => {
        report('version', version);
    })
    .on('error', error => {
        console.log('Error:', error);
        stream.close()
        setTimeout(startStream, 1000);
    })
    .start()
};

function report(action, event) {
    var data = ('action' in event) ? event["document"].data : event.data;
    room_data.set(data);
};

return returns an undefind value [duplicate]

im having issues with return in my function, i got two functions, the first one creates a random series of letters and numbers and the other one puts a few combinations together into a key and checks the database for it (to check if it already exists and if it does then it tries again), at the end of the second function im returning the key value as im trying to use it in my post request code. here is the code:

function keyGen(length) {
    var result           = '';
    var characters       = '0123ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

function makeKey(company) {
    var gen1 = keyGen(6);
    var gen2 = keyGen(4);
    var gen3 = keyGen(6);

    var key = `${company}-${gen1}-${gen2}-${gen3}`;
    var rawKey = `${gen1}-${gen2}-${gen3}`;
    con.query('SELECT * FROM lkeys WHERE chars = ?', [rawKey], function(err, rows, fields) {
        console.log("here")
        if (err) throw err
        if (rows.length > 0) {
            makeKey(company)
        }
        else {
            console.log("here2")
            console.log(key)
            return key;
        }
    })
}

this is how i try to use the value from the function:

let lkey = makeKey(company);

out put for lkey is undefined

any help would be appreciated, thank you.

how to clear all inputs in react div

import "./App.css";
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { addUser} from "./features/Users";
function App() {
  const dispatch = useDispatch();
  const userList = useSelector((state) => state.users.value);

  const [name, setName] = useState("");
  const [username, setUsername] = useState("");

  return (
    <div className="App">
      {" "}
      <div className="addUser">
        <input
          type="text"
          placeholder="Name..."
          onChange={(event) => {
            setName(event.target.value);
          }}
        />
        <input
          type="text"
          placeholder="Username..."
          onChange={(event) => {
            setUsername(event.target.value);
          }}
        />
        <button
          onClick={() => {
            dispatch(
              addUser({
                id: userList[userList.length - 1].id + 1,
                name,
                username,
              })
            );
          }}
        >
          {" "}
          Add User
        </button>
      </div>
);}

I am new to react and redux. After clicking the “Add User” button, new User data from inputs in the code will be added to the backend list. I want the values in input sections to be cleared after clicking the “Add User” button, but I don’t know how to do.

Should i use backend for simple API calls?

let’s say i want to call an API from my frontend application in something like react. The API that i want to call is an external API provided by someone else. The thing is, I need to specify the API-key in header, so should i just make the call using react or should I use something like Spring Boot to make my own API that will call the external API and then pass the data to my react app? How about API-key protection in just plain frontend apps?

Type definition for array with minimun and maximum length in Typescript

How can I create a type definition for array with minimun and maximum length, as in:

var my_arr:my_type<type, {start: 1, end: 3}>;

my_arr = [1] - pass
my_arr = [1,2] - pass
my_arr = [1,2,3] - pass
my_arr = [1,2,3,4] - fail
my_arr = [1, "string"] - fail

I.E. provide the type of the elements in the array and a start index and end index of length such that if the length is less than the start index it fails, or if the length is bigger than the end index it fails.

I’ve found this solution for a fixed length array online:

type SingleLengthArray<
  T,
  N extends number,
  R extends readonly T[] = []
> = R["length"] extends N ? R : SingleLengthArray<T, N, readonly [T, ...R]>;

And I was able to create a type that works if the length of the array is either equal to the start index or end index but nothing inbetween:

type MultipleLengthArray<
  T,
  N extends { start: number; end: number },
  R extends readonly T[] = []
> = SingleLengthArray<T, N["start"], R> | SingleLengthArray<T, N["end"], R>;

What I think would work if it’s possible is to create an array of numbers from the start index up to the end index(i.e. start index = 1, end index = 5 => array would be [1,2,3,4,5]) and iterate over the array and like

type MultipleLengthArray<T, N extends {start: number, end:number}, R extends readonly T[] = []> = for each value n in array => SingleLengthArray<T, n1, R> | SingleLengthArray<T, n2, R> | ... | SingleLengthArray<T, n_last, R>

Please let me know if there is a way to do this, thank you.

Why does an array of objects return undefined, even though the array is clearly not undefined?

I have an array of objects called result, and it is all of the rows inside an SQL database. In order to access all of the users, I have written the following lines:

function getAllUsers() {
    let sql = 'SELECT * FROM usernames';
    db.query(sql, function (err, result) {
        if (err) throw err;
        else {
            console.log(result);
            return result
        }
    });
}

In this function, the console.log(result) returns the following:

[
  RowDataPacket {
    id: 8,
    username: 'username1',
    password: 'password1',
    created: 2022-06-04T18:03:20.000Z
  },
  RowDataPacket {
    id: 9,
    username: 'username2',
    password: 'test123',
    created: 2022-06-04T22:27:08.000Z
 },
 // etc etc etc
 ...
]

Which is all the rows inside the database in an array. However, when I return it and try to console.log() it inside some other function (in this case – I tried in app.listen(‘3000’) but I checked other functions and it gave me the same result) it returns for some reason undefined, even though it should clearly return the array.

app.listen('3000', function () {
    console.log(getAllUsers());
});

// The console.log(getAllUsers()) returns undefined for some unknown reason

What is the reason for this? How can I fix it and return the users? Thanks in advance!

Generating files in nodejs escape character issue

I have a NestJs project where I am trying to generate js files into the CDN blob storage.
For eg I have this object:

{
 "prop1":"${resolvedprop1}",
 "prop2":"John's pet"
}

content of the generated js file should look like:

var metadata=()=>JSON.parse('{ "prop1":"${resolvedprop1}", "prop2":"John's pet" }')

Code for generation of the file:

function writeToCDN(metadata){
    const content = `var metadata = ()=>JSON.parse('${JSON.stringify(metadata)}')`;
    //write content string to a file in CDN BLOB.
}

When I load this file into the browser and execute metadata() I get an error when parsing because the single quote is not escaped.

Important note:
I can not use backtick instead of single quote inside JSON.parse since I am expecting ${} in the prop1 value.

Thank you for your help in advance!