How to change the contents of a class construcor in a javascript class and access it later?

I want to fetch data from an API, add it to the constructor of a class, and then on button Click display it to the page.

class Entry {
  constructor() {
    this.pages = [];
  }
  loadAllEntries(url) {
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        this.pages = data;
        // this would do it autuomatically, it's not what I want
        //this.displayAllEntries("#notes-list");
      });
  }

  displayAllEntries(node) {
    let ul = document.createElement("ul");
    ul.id = "display-list-note";
    this.pages.map((page) => { 
      let li = document.createElement("li");
      li.innerText = page.title;
      ul.appendChild(this.createClickableItem(page));
    });
    document.querySelector(node).appendChild(ul);
  }
  createClickableItem(item) {
    let li = document.createElement("li");
    li.innerText = item.title;
    li.addEventListener("click", () => {
        console.log(item.id);
    });
    return li;
  }
}

const courses = new Entry();
courses.loadAllEntries("http://localhost:1338/courses?favorite=true");

// on some click I want to run 

courses.displayAllEntries("#notes-list");

But, displayAllEntries acts as if loadAllEntries never ran!

later on I want to do something like courses.deleteEntry(213) and change the contents of the constructor, (a glorified todo list type of thing)

How to redirect page without nesting the url in react-router-dom

I use react-router-dom v5 for routing in my application. In some case I have route like this:

checkup/step-1/:id
checkup/step-2/:id
checkup/step-3/:id

For example, I’m at checkup/step-1/:id so I want to redirect from there to checkup/step-2/:id. To redirect I use hisory.push(). But the result is become like this:

checkup/step-1/:id/checkup/step-2/:id

But my expected result is:

checkup/step-2/:id

Mongodb watch changes in document with array element of certain value

Here is my document:

{
"_id": {
    "$oid": "6257a55d04bf2167733f5b72"
},
"attributes": {
    "CustomerName": "John",
    "CustomerID": "28374",
    "LoanID": "82349327409234"
},
"type": "Record",
"Pointers": [
    {"type":"car","token_id":"123"},
    {"type":"house","token_id":"456"}
]
}

Here is my watch query:

var watchCursor = db.loans.watch([{$match:{"$or":[{"updateDescription.updatedFields.attributes.Pointers": { $elemMatch : {"type": "car"} }},{"fullDocument.attributes.Pointers": { $elemMatch : {"type": "house"} }}]}}]);
while (!watchCursor.isExhausted()){
   if (watchCursor.hasNext()){
      print(JSON.stringify(watchCursor.next()));
   }
}

It simply does not return any result. As a test I changed the $elemMatch stage to $exists: true
and it returns the document.
what’s wrong?!

express typeorm createConnection not recognized

enter image description here

If I just type createConnection, a line keeps appearing in the middle and I can’t even create a table. I use mysql and I want solve this problem. It seems that only typeorm’s createConnection is not recognized, how can I solve it?

import morgan from "morgan";    // 웹 서버에 들어오는 요청을 shell에 출력해주는 패키지
import * as dotenv from "dotenv";
import path from "path";
import { createConnection } from "typeorm";

const app = express();
const PORT = process.env.PORT || 3000;

app.use(morgan("dev"));

app.use(express.json());
app.use(express.urlencoded({ extended : false }));

dotenv.config({ path: path.join(__dirname, "../../.env") });

app.get("/", (req: Request, res: Response, next: NextFunction) => {
    res.send("Hello, world!")
}); 
createConnection()
  .then(() => {
    console.log("데이터베이스 연결 성공");
  })
  .catch((err) => console.error(err));

app.listen(PORT, () => {
    console.log(PORT, "번 포트에서 대기 중");
});    // src/app.js



```{.       // ormconfig.ts
  module.exports = {
    type: 'mysql',
    host: process.env.HOST,
    port: 3306,
    username: process.env.USERNAME,
    password: process.env.PASSWORD,
    database: process.env.DATABASE,
    synchronize: true,
    logging: false,
    entity: ['src/entities/**/*.ts'],
    migrations: ['src/migration/**/*.ts'],
    subscribers: ['src/subscriber/**/*.ts'],
    cli: {
      entitiesDir: 'src/entities',
      migrationsDir: 'src/migrations',
      subscribersDir: 'src/subscriber',
    },
  }
};```

how to pass nested objects between microservices using TCP

I am really not sure what’s going on here….I have a two microservices and a gateway (nestjs) passing nested objects between each. I am using TCP transport to communicate between microservices. I now have a problem where I cannot access to objects returned to the gateway. This is a login authentication process where I am calling the gateway from a client…the gateway call the Auth microservice which do a bunch of stuff including creating the jwt token….the problem occurs when the Auth microservice returns the a nested object, including the jwt to the gateway….the properties in the nested objects are undefined to the gateway. I seen this problem before where you get an [object, Object] object and you cannot destructure it. below is the nested object as displayed with in the Auth microservice before the RETURN: {"jwt_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1haWwybWljaGFlbGVubmlzQGdtYWlsLmNvbSIsImZpcnN0X25hbWUiOiJNaWNoYWVsIiwibGFzdF9uYW1lIjoiRW5uaXMiLCJ0ZWxlcGhvbmUiOiIrMTg3NjM4MTM5MzIiLCJjYXRlZ29yeSI6InN0dWRlbnQiLCJtZW1iZXJfc3RhdHVzIjoicGVuZGluZyIsImFzc29jaWF0aW9uIjoiSGlsbCBUb3AgUHJpbWFyeSIsInJvbGVzIjpbImd1ZXN0Il0sImlhdCI6MTY1MDU3MTcyOSwiZXhwIjoxNjUzMTYzNzI5fQ.L_MqyMO9vdZ2iP1pZ8hBHq3yMPXa__IHXuWfFHV517M","userProfile":{"email":"[email protected]","first_name":"Michael","last_name”:”Brown,”telephone":"+19995553932","category":"student","member_status":"pending","association":"Hill Top ","roles":["guest"]}}

as you can see the objects are .jwt_token and .userProfile but I cannot display access the objects. Below is the snippet of code ….call to the Auth microservice:

const validated_user =
await this.msConnector.requestAuth({email: email,password: password});
const { jwt_token } = validated_user; one attempt at accessing the properties
logger.log(VALIDATED USER.....${jwt_token}); *undefined

I really suspect I am just tired and can’t see the obvious bug….Sorry if the question is not more clear. I would really appreciate better eyes than mine given me an answer.

Lat and Long is showing not defined when using template literals [duplicate]

Using Accuweather API to create a weather app. I believe I have messed up somewhere with syntax but I can’t figure out where I went wrong. Any advice?

Line 26:100: ‘lat’ is not defined no-undef

Line 26:109: ‘long’ is not defined no-undef

import { useEffect, useState } from "react";
    
    function Location() {
      let [data, setData] = useState([]);
      const key = process.env.REACT_APP_API_KEY;
      
    
      useEffect(() => {
        if (!data) return;
    
       if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(successFunction, console.log());
       } else {
         alert(
           "It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser that supports it."
         );
       }
        function successFunction(latlong) {
          const lat = latlong.coords.latitude;
          const long = latlong.coords.longitude;
          console.log("latlong = " + lat + ", " + long);
        
        }
        
        fetch(
          `http://dataservice.accuweather.com/locations/v1/cities/geoposition/search?apikey=${key}&q=${lat}%2C${long}`
        )
          .then((response) => response.json())
          .then((data) => setData(data))
          .catch((err) => console.log(`Error Meassage ${err}`));
      }, []);
      console.log("location key = ", data.Key);
    }
    
    export default Location;

Best practices to check if the session still valid with auth0

I’ve implemented silent auth using the Auth0 example on my Gatsby application.

export const silentAuth = callback => {
    if (!isBrowser) return;
    if (!isAuthenticated()) return callback()

    auth0.checkSession({}, setSession(callback))
}

The following snippet is on my ‘gatsby-browser.js’ file

handleCheckSession = () => {
    this.setState({ loading: false })
  }

  componentDidMount() {
    silentAuth(this.handleCheckSession)
  }  

I want to check periodically if the session is not expired or if it stills valid.
What is the best way to do that?

Additional information:
I’m saving the expiration time on a expiresAt localStorage variable.
setSession is a function that login the user based on the auth0 client info, sets some localStorage variables, and do some other work.

matrix with different colors javascript

I need to build 2d matrix 50×50 representing boxes with random colors, but if the boxes which are close to each other have the same colors, they should get different random color from each other, until it’s different and then continue building.

Here I made matrix with boxes inside it works fine, but colors sometimes do match:

function onLoad(evt)
{       
        
        var matrix = [];
        

        for (var i = 0; i < 50; i++) {
            var row = [];
            for (var j = 0; j < 50; j++) {
                var randColor = Math.floor(Math.random()*16777215).toString(16);
                row.push(MyComponent(randColor));
                }
                matrix.push(row);
            }
        
        
        var newData = matrix.map(function(row) {
                return row.map(function(x) {
                        return x;
       })})
       
     
           
         
}

getting video length of mov file with no audio error chrome js

Is there an accurate way to determine the length of a .mov file with chrome? On our website we currently use video.onloadedmetadata but it’s causing errors.

Example:

upload(data) {
 const file = data.body.get('file');
 const filename = file.name;

 const video = document.createElement('video');
 video.preload = 'metadata';
 video.onloadedmetadata = () => {
   const videoDuration = Math.floor(video.duration);
 }

 video.onerror = (error) => {
   debugger;
   console.error(error);
 };
};

Image of error:
[enter image description here][1]
[1]: https://i.stack.imgur.com/S4Tc1.png

Express session works fine locally but stop working after deploying on Heroku

Before I deployed, the express session in my backend works just fine. However, after I deployed to Heroku, the session isn’t storing any data now, so if I now store a piece of information into req.session and make a request to fetch it, the console log information shows: console log message

My index.js at backend:

const express = require('express')
const mysql = require('mysql')
const cors = require('cors')
const session = require('express-session')
// const session = require('cookie-session')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const FileStore = require('session-file-store')(session);
const fileStoreOptions = {
  path: process.env.SESSION_PATH || './sessions'
};

const port = 3010

const app = express()

app.use(express.json())
app.use(cors({
  origin: ["https://xxx.netlify.app"],
  methods: ["GET", "POST"],
  credentials: true
}))

app.use(cookieParser())
app.use(bodyParser.urlencoded({extended: true}))
app.set('trust proxy', 1)
app.use(
  session({
    // store: new FileStore(fileStoreOptions), // the line that causes crashes
    key: "userId",
    secret: "subscribe",
    resave: false,
    saveUninitialized: false,
    proxy: true,
    cookie: {
      // expires: 60 * 60 * 24,
      httpOnly: false,
      // secure: (process.env.NODE_ENV && process.env.NODE_ENV == 'production') ? true:false
      secure: true
    },
  })
)

app.post('/login', (req, res) => {
  const username = req.body.username
  const password = req.body.password
  console.log("username");
  console.log(username);
  console.log("password");
  console.log(password);

  db.query(
    'SELECT * FROM user where username = ? AND password = ?',
    [username, password],
    (err, result) => {
      console.log("result");
      console.log(result);
      if (err) {
        res.send({ err: err })
      }
      if (result.length) {
        req.session.user = result;
        console.log("req.session.user");
        console.log(req.session.user);
        res.send(result);
      } else {
        res.send({ message: 'Wrong username or password.' });
      }
    },
  )
})

app.get('/login', (req, res) => {
  console.log("req.session.user");
  console.log(req.session.user);
  if(req.session.user) {
    res.send({isLoggedIn: true, user: req.session.user})
  } else {
    res.send({isLoggedIn: false})
  }
})

app.listen(process.env.PORT || port, () => {
  console.log('Successfully Running server at ' + port + '.')
});

I noticed that some people use session fileStore and fileStoreOption to fix, but after we add the line of session store the backend in Heroku crashes, with error message ‘H10’.

How should we fix it?

Unable to run unique iterations for individual objects

I’m trying to present 25 entries {name, company, skill, etc.) on the page and am having trouble getting the unique information, i.e. I’m only seeing the first entry over and over. I’m not sure how to reiterate with new information since it’s only going to response.data.students[0]. This is what my code looks like now, where the mapping is:

export default function StudentList() {
  let [loaded, setLoaded] = useState(false);

  let [students, setStudent] = useState(" ");
  function doInfo(response) {
    console.log(response.data);
    setStudent(response.data.students[0].id);
    setLoaded(true);
  }

  if (loaded) {
    return (
      <div className="StudentList">
        <div className="row">
          <div className="col">
            {students.map(function (id) {
              return <StudentInfo data={id} />;
            })}
          </div>
        </div>
      </div>
    );
  } else {
    let url = "https://api.hatchways.io/assessment/students";
    axios.get(url).then(doInfo);
  }
}

Can someone help me code it so it runs through all 25 entries, not just the first one?

How to display value from object in tooltip on mouseover?

In my project, players can generate items with random name and stats. Each item has its own set of properties as a name, attack value, defense value, etc.

I want to make a tooltip that show the item values on hover knowing :
1- I can’t hard write it in HTML (I might create a div with element inside for each item and link a class to show/hide on hover… But it would be tedious and I’m not sure it would be performance-wise in the long run (100+ items ?).
2- I want to avoid JQuery / boostrap and other library unless impossible without them.

I’ve seen basic solution with data attribute but each item should have maybe a dozen key:value to show among hundreds, so, probably not useful to me.
I tried to make a CSS variable modified by a JS function but… Well, that’s not how CSS var. works apparently.

let myObject = {
    prop1 : "name",
  prop2 : 12,
};

document.getElementById("myID").addEventListener('mouseenter', function() {
    displayEquipmentStats(myObject);
})

function displayEquipmentStats(item) {
    let toDisplayContent = "";
    toDisplayContent += item.prop1 + " att : ";
    toDisplayContent += item.prop2;
    document.body.style.setProperty("--EquipmentStats", toDisplayContent);
 }
:root {
  --Content: "";
}

#myID:hover::after {
    white-space: pre;
    content: "hi there"; /* I wanted to display var(--Content) here, sadly, it's not possible */
    position: absolute;
    top: 1.5em;
    left: 3em;
    z-index: 1;
    padding: 0.4em;
    background: #413219;
    color: #fff;
    border-radius: 4px;
}
<div id="myID"> some random text</div>

Here is a snippet showing more or less what I want to achieve (Again, I understand that CSS var won’t work like that).
Any insight for a similar method welcome at this point, thank you.

React: How to implement functional state updates to empty array? [duplicate]

I have a click handler that intends to (1) clear two instances of state and (2) execute an async function that updates state from (1). Here’s the function:

function clickHandler(result) {
    setState1((state1) => []);
    setState2((state2) => []);
    asyncFunc(result).then((newResult) => {
      setState1([...state1, { key: newResult }]);
    });
}

While the function executes, setState1 doesn’t set state1 to an empty array, despite using a functional state update. This leads to a non-empty array when de-structuring state1 inside asyncFunc.

Am I implementing the functional state update properly? How can I modify asyncFunc to clear state before executing asyncFunc and append { key: newResult } to an empty array?

I’ve looked at answers here and here, but both don’t directly apply. The former comes close, but I don’t think using useEffect would be appropriate here.

Uncaught TypeError: setCoords is not a function

I am using the GoogleMapReact component and need the coords and setCoords to work properly. I am receiving this error message whenever I try to start my application.
Can anyone explain to me what I did wrong?
I declared coords and setCoords in my app.js to have an empty value in the UseState and I think thats where my issue is coming from but if anyone can chime in I would appreciate it.

This is my app.js

const App = () => {
    const [type, setType] = useState('restaurants');
    const [rating, setRating] = useState('');
  
    const [coords, setCoords] = useState();

    const [bounds, setBounds] = useState(null);
  
    const [weatherData, setWeatherData] = useState([]);
    const [filteredPlaces, setFilteredPlaces] = useState([]);
    const [places, setPlaces] = useState([]);
  
    const [autocomplete, setAutocomplete] = useState(null);
    const [childClicked, setChildClicked] = useState(null);
    const [isLoading, setIsLoading] = useState(false);

    console.log(coords);


    useEffect(() => {
        navigator.geolocation.getCurrentPosition(({ coords: {latitude, longitude} }) => {
            setCoords({ lat: latitude, lng: longitude});

        });

    }, []);
    

    useEffect(() => {
        const filtered = places.filter((place) => Number(place.rating) > rating);

        setFilteredPlaces(filtered);
    }, [rating]);
     
    useEffect(() => {
        if(bounds) {
        setIsLoading(true);

        getWeatherData(coords.lat, coords.lng)
        .then((data) => setWeatherData(data));

        getPlacesData(type, bounds.sw, bounds.ne)
        .then((data) => {
            setPlaces(data.filter((place) => place.name && place.num_reviews > 0));
            setFilteredPlaces([]);
            setRating('');
            setIsLoading(false);
        });
    }

    },[bounds, type, coords]);

    const onLoad = (autoC) => setAutocomplete(autoC);
    
    const onPlaceChanged = () => {
        const lat = autocomplete.getPlace().geometry.location.lat();
        const lng = autocomplete.getPlace().geometry.location.lng();

        setCoords({ lat, lng });
    };


    return (
     <>
     <CssBaseline />
     <Header onPlaceChanged={onPlaceChanged} onLoad={onLoad} />
     <Grid container spacing ={3} style={{ width: '100%' }}>
         <Grid item xs={12} md={4}>
             <List 
             places={filteredPlaces.length ? filteredPlaces : places}
             childClicked={childClicked}
             isLoading={isLoading}
             type={type}
             setType={setType}
             setRating={setRating}
             rating={rating}
             
             />
             


         </Grid>
         <Grid item xs={12} md={8} style={{display: 'flex', justfiyContent: 'center', alignItems: 'center' }}>
             {coords && <Map 
             setChildClicked={setChildClicked}
             setCoordinates={setCoords}
             setBounds={setBounds}
             coords={coords}
             places={filteredPlaces?.length ? filteredPlaces : places}
             weatherData={weatherData}
             />}
             
         </Grid>

     </Grid>

     
     </>
    );
};

export default App;

this is my map.jsx



const Map = ({coords, setCoords, setBounds, places, setChildClicked, weatherData}) => {
    const classes = useStyles();
    const matches = useMediaQuery('(min-width:600px)');


    return (
        <div
       className={classes.mapContainer}>
            <GoogleMapReact
                bootstrapURLKeys={{ key: process.env.REACT_APP_GOOGLE_MAPS_API_KEY }}
                defaultCenter={coords}
                center={coords}
                defaultZoom={14}
                margin={[50, 50, 50, 50,]}
                options={{ disableDefaultUI: true, zoomControl: true, styles: mapStyles }}
                onChange={(e) => {
                    setCoords({ lat: e.center.lat, lng: e.center.lng });
                    setBounds({ ne: e.marginBounds.ne, sw: e.marginBounds.sw });
                }}

                onChildClick={(child) => setChildClicked(child)}

            >
                {places?.length && places?.map((place, i) => (
                    <div
                        className={classes.markerContainer}
                        lat={Number(place.latitude)}
                        lng={Number(place.longitude)}
                        key={i}
                    >

                        {!matches ?
                            <LocationOnOutlinedIcon color="primary" fontSize="large" />
                            : (
                                <Paper elevation={3} className={classes.paper}>
                                    <Typography className={classes.typography} variant="subtitle2" gutterBottom> {place.name}</Typography>
                                    <img
                                        className={classes.pointer}
                                        src={place.photo ? place.photo.images.large.url : 'https://www.rlare.com/wp-content/uploads/2019/12/Inside-1-1.jpg'}
                                        alt={place.name}
                                    />
                                    <Rating size="small" value={Number(place.rating)} name="read-only" />

                                </Paper>
                            )}

                    </div>
                ))}

                {weatherData?.list?.length && weatherData.list.map((data, i) => (
                    <div key={i} lat={data.coord.lat} lng={data.coord.lon}>
                        <img src={`https://openweathermap.org/img/w/${data.weather[0].icon}.png`} height="70px" alt="map"/>

                    </div>
                ))}

            </GoogleMapReact>
        </div>
    );
}

export default Map;

Div Update From Selecting HTML Option

Getting 3 console errors:

  1. Can’t find variable myFunction.
  2. Unexpected end of script.
  3. Unterminated regular expression literal '/body&gt;'.

Code here:

<!DOCTYPE html>
<html>
<head>
<script   src="https://code.jquery.com/jquery-3.6.0.min.js"   integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="   crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script> // In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
    $("#cars2").select2();
});
</script>
<script>
<!--Need help here I think.-->
function myFunction(){
 var x = document.getElementById("myDIV");
var y = this.value;
  switch (y) {
case '1':
x.innerHTML = "<p>Volvo dude</p>";
break;
case '2':
x.innerHTML = "<p>Roy!</p>";
}
}
</script>

<style>
select {
width: 150px;

}
</style>
</head>
<body>
<div id="myDIV">Hello</div>

<label for="cars">Choose a car:</label>

<select id="cars2" onchange="myFunction()">
<option value="0">Pick something</option>
  <option value="1">Volvo</option>
  <option value="2">Saab</option>
  <option value="3">Opel</option>
  <option value="4">Audi</option>
</select>
</body>
</html>

I can’t use the snippet editor ’cause all I have is an iPad.

JSFiddle here: https://jsfiddle.net/CoolBuys1290/59qmbt0f/19/

Please help me update the div text based on selecting an option.

Updated braces.

Thanks.