In React, can a useState’s value be used in a variable chain? [duplicate]

For example, if I have a useState with the string “drama” set as its value, can I use the useState’s string in the path when accessing data in an object? So console.log(movies[0].drama) would be functionally the same as something like console.log(movies[0].--useStateName--).

Specifically I’ve got an array of movies with each movie having standard data such as title, release date, rating etc. but each movie also has a data point for every possible genre as a boolean, 0 if it is that genre, 1 if it is not.

If I’m trying to console log if the first movie in the array is a drama, I can console.log(movies[0].drama) and it will give ‘1’, because the movie it’s returning is a drama.

Separately from the API, I have an array in the application made up of just the genres as an array of strings, this array has been mapped to a form select input. A useState is being updated with whichever genre is selected in the select input.

So the problem is that I need to be able to use the string saved in the useState when checking for movies that belong to whichever genre is in the useState at the time. So if the useState is the string “drama”, I need to be able to do something like console.log(movies[0].<useStateName>) and have it do the exact same thing as console.log(movies[0].drama).

Manipulating database objects on a web canvas

I’m trying to find the right way in orderto solve this problem.
Manipulate database objects using a web canvas.
The idea here is to come up with something similar (but in simplified form) to the Enovia VPM web portal, where you can see SQL objects, in the form of a box, containing some attributes (like part number, status) and of course those attributes they belong to a specific row in a sql database.
I can’t find the code to base my approach to scaling on a proper solution.

I don’t have an idea to start this. I know most of the best solutions could come from JavaScript. I found some examples where you can manipulate (pan, zoom, click) “frozen” images, but I’m not sure how to implement this with an SQL interface.

Here a nice example:

https://codepen.io/chengarda/pen/wRxoyB

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");

let cameraOffset = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
let cameraZoom = 1;
let MAX_ZOOM = 5;
let MIN_ZOOM = 0.1;
let SCROLL_SENSITIVITY = 0.0005;

function draw() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // Translate to the canvas centre before zooming - so you'll always zoom on what you're looking directly at
    ctx.translate(window.innerWidth / 2, window.innerHeight / 2);
    ctx.scale(cameraZoom, cameraZoom);
    ctx.translate(
        -window.innerWidth / 2 + cameraOffset.x,
        -window.innerHeight / 2 + cameraOffset.y
    );
    ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
    ctx.fillStyle = "#991111";
    drawRect(-50, -50, 100, 100);

    ctx.fillStyle = "#eecc77";
    drawRect(-35, -35, 20, 20);
    drawRect(15, -35, 20, 20);
    drawRect(-35, 15, 70, 20);

    ctx.fillStyle = "#fff";
    drawText("Simple Pan and Zoom Canvas", -255, -100, 32, "courier");

    ctx.rotate((-31 * Math.PI) / 180);
    ctx.fillStyle = `#${(Math.round(Date.now() / 40) % 4096).toString(16)}`;
    drawText("Now with touch!", -110, 100, 32, "courier");

    ctx.fillStyle = "#fff";
    ctx.rotate((31 * Math.PI) / 180);

    drawText("Wow, you found me!", -260, -2000, 48, "courier");

    requestAnimationFrame(draw);
}

// Gets the relevant location from a mouse or single touch event
function getEventLocation(e) {
    if (e.touches && e.touches.length == 1) {
        return { x: e.touches[0].clientX, y: e.touches[0].clientY };
    } else if (e.clientX && e.clientY) {
        return { x: e.clientX, y: e.clientY };
    }
}

function drawRect(x, y, width, height) {
    ctx.fillRect(x, y, width, height);
}

function drawText(text, x, y, size, font) {
    ctx.font = `${size}px ${font}`;
    ctx.fillText(text, x, y);
}

let isDragging = false;
let dragStart = { x: 0, y: 0 };

function onPointerDown(e) {
    isDragging = true;
    dragStart.x = getEventLocation(e).x / cameraZoom - cameraOffset.x;
    dragStart.y = getEventLocation(e).y / cameraZoom - cameraOffset.y;
}

function onPointerUp(e) {
    isDragging = false;
    initialPinchDistance = null;
    lastZoom = cameraZoom;
}

function onPointerMove(e) {
    if (isDragging) {
        cameraOffset.x = getEventLocation(e).x / cameraZoom - dragStart.x;
        cameraOffset.y = getEventLocation(e).y / cameraZoom - dragStart.y;
    }
}

function handleTouch(e, singleTouchHandler) {
    if (e.touches.length == 1) {
        singleTouchHandler(e);
    } else if (e.type == "touchmove" && e.touches.length == 2) {
        isDragging = false;
        handlePinch(e);
    }
}

let initialPinchDistance = null;
let lastZoom = cameraZoom;

function handlePinch(e) {
    e.preventDefault();

    let touch1 = { x: e.touches[0].clientX, y: e.touches[0].clientY };
    let touch2 = { x: e.touches[1].clientX, y: e.touches[1].clientY };

    // This is distance squared, but no need for an expensive sqrt as it's only used in ratio
    let currentDistance =
        (touch1.x - touch2.x) ** 2 + (touch1.y - touch2.y) ** 2;

    if (initialPinchDistance == null) {
        initialPinchDistance = currentDistance;
    } else {
        adjustZoom(null, currentDistance / initialPinchDistance);
    }
}

function adjustZoom(zoomAmount, zoomFactor) {
    if (!isDragging) {
        if (zoomAmount) {
            cameraZoom += zoomAmount;
        } else if (zoomFactor) {
            console.log(zoomFactor);
            cameraZoom = zoomFactor * lastZoom;
        }

        cameraZoom = Math.min(cameraZoom, MAX_ZOOM);
        cameraZoom = Math.max(cameraZoom, MIN_ZOOM);

        console.log(zoomAmount);
    }
}

canvas.addEventListener("mousedown", onPointerDown);
canvas.addEventListener("touchstart", (e) => handleTouch(e, onPointerDown));
canvas.addEventListener("mouseup", onPointerUp);
canvas.addEventListener("touchend", (e) => handleTouch(e, onPointerUp));
canvas.addEventListener("mousemove", onPointerMove);
canvas.addEventListener("touchmove", (e) => handleTouch(e, onPointerMove));
canvas.addEventListener("wheel", (e) =>
    adjustZoom(e.deltaY * SCROLL_SENSITIVITY)
);

// Ready, set, go
draw();

(Imagine instead of that square face, a box with information given from a database)

Rerendering component when any object keys change

I have an user object with all user data inside. This object changes whenever anything changes in the database.

const [userData, setUserData] = useState(null) //will become an object when filled with user data

I then pass this as a prop in my Navbar component so I can display the data.

<Navbar key={userData} user={userData}/>

I can’t use the whole userData object as a key like shown above, and the component won’t rerender otherwise. We don’t know which value will change in the database, so I can’t give an exact key.

How can I update the Navbar when any value changes in the userData object?

Blazor Server Table Scroll Best Pratice

I’d like to know the best practices for scrolling tables in a Blazor Server app. At the moment, I am invoking a simple Javascript (see below) in the OnAfterRenderAsync method of the applicable component. That works, but the scrolling is a bit delayed. Two questions:
(1) Does the scrolling have to be done by Javascript? I haven’t found an alternative.
(2) If I need JS, is this the best way to do it (i.e. in OnAfterRenderAsync and with the JS below)? The sync OnAfterRender isn’t any better. Thanks. Steve

function Nav_ScrollIntoView(navId)
{
    var elem = document.getElementById(navId);
    if (elem === null) return;
    elem.scrollIntoView({ behavior: 'instant' });
    return;
}

await User.findOne({email}); returns fail

I am trying to create a login authentication for my form. I have created the user with a hashed password using bcrypt, I am trying to log in but it keeps returning failed. The email and password are both correct I have double checked. This is my server-side code:

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const User = require("./models/user.js");


require("dotenv").config();
const app = express();
const bcryptSalt= bcrypt.genSaltSync(10);

app.use(express.json());
app.use(cors({
    credentials: true,
    origin: "http://localhost:5173",
}));

mongoose.connect(process.env.MONGO_URL);


app.get("/test",(req,res) => {
    res.json("test ok");
});

app.post("/register",async (req,res) => {
    const{name, email, password} = req.body;
  
    try{
        const newUser = await User.create ({
            name,
            email,
            password: bcrypt.hashSync(password, bcryptSalt)
        });
        res.json(newUser);
    
    } catch (e){
        res.status(422).json(e);
    }
});

app.post("/login", async (req,res) => {
    const {email, password} = req.body;
    const newUser = await User.findOne({email});
    if (newUser){

       const passOk= bcrypt.compareSync(password, newUser.password);
       if (passOk) {
        res.json("pass ok");
       } else{
        res.status(422).json("pass not ok");
       }

    } else {
        res.json("not found");
    }

});

  

app.listen(4000);

I have checked the server logs for any errors that might be preventing the login process from working correctly. There were no error messages instead I keep getting the “login failed” alert whenever I try to log in. Here is my client-side code:

import { Link } from "react-router-dom";
import {useState} from "react"
;
function LoginPage () {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    async function handleOnSubmit (e) {
        e.preventDefault();
        try{
            await axios.post("/login", {email, password});
            alert("login successful");
        } catch (e) {
            alert("login failed");
        }
        

    }

    return (
        <div className="mt-4 grow flex items-center justify-around">
        <div className="mb-64">
        <h1 className="text-4xl text-center mb-4">Login</h1>
            <form className="max-w-md mx-auto" onSubmit={handleOnSubmit}>
                <input type="email" 
                placeholder="[email protected]" 
                value={email} 
                onChange={ev => setEmail(ev.target.value)} />
                <input type="password"
                 placeholder="password"
                 value={password} 
                 onChange={ev => setPassword(ev.target.value)} />
                <button className="primary">Login</button>
                <div className="text-center py-2 text-gray-500">
                    Don't have an account yet? <Link className="underline text-black" to={"/register"}>Register now</Link>
                </div>
            </form>
        </div>
    </div>
    )

}
export default LoginPage;

Use styled components conditional props with typescript

I’m getting the error below when I try to use logical && in a styled component prop
When I use the optional chaining “? :”, It works without any ts error but can’t use “&&”

Type 'false | InterpolationValue[] | undefined' is not assignable to type 'Interpolation<ThemedStyledProps<ClassAttributes<HTMLDivElement> & HTMLAttributes<HTMLDivElement> & ContainerProps, any>>'.
      Type 'undefined' is not assignable to type 'Interpolation<ThemedStyledProps<ClassAttributes<HTMLDivElement> & HTMLAttributes<HTMLDivElement> & ContainerProps, any>>'

Below is my code:

const hoverfragment = css`
  &:hover {
      display: unset;
  }
`;

interface ContainerProps {
  selected?: boolean;
}

const container = styled.div<ContainerProps>`
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  ${({ selected }) => selected && hoverfragment}
`;

Why does not my code show up when I press the button?

My button does not work and i dont know if it has to do with spelling mistake or if i missed somthing.

I expected my code to ask a question of what your name is and then it would alert it.

<!DOCTYPE html>



    
    


<p>Hej!</p>
    <a href="Usefull_stuff.html">
    Home</a>
    <a href="Eheheh.html">
    Random Joke</a>
    <a href="LOL.html">
    Nothing special</a>
    alert("Welcome to my page");


</br>
</br>

<button onclick="Myfunction()">Quick question!</button>

<p></p>


    function myFunction() {
        let text;
        let name = prompt("What is your name", "Enter here");
        if (name == null || name == "") {
            text = "Please try again!";
        } else {
            text = "Nice name " + name + "! I like it";
            alert("Have a nice day!");
        }
        document.getElementById("alert function").innerHTML = text;
    }

my printer does not print with react-native-thermal-receipt-printer-image-qr

I am trying to print with a bar code printer xprinter xp-237B my fanction works without error but the printer does not print however with another android application it has printed, I have tried another normal printer it prints without problem can you help me Please.
i use react-native-thermal-receipt-printer-image-qr

I don’t know if the xp-237b printer is compatible with
react-native-thermal-receipt-printer-image-qr
I created an issue on github to find out

How to get out of a wrong folder

I’m supposed to be in
LizzyOrji123/blog
in my GitHub.

Now I’m in
/home/lizzy123/Elizabeth -profile-picture/blog

What command should I put in to get into the right folder?

The wrong folder is not allowing me to access .json

I want to be able to access my package.json file.
Currently, it says I couldn’t find it using yarn

The conditional rendering the component error React not working

The conditional rendering React not working. I’m passing as a prop an array Tasks and trying to render the component only if the key of the array is specific, but I’m getting an error – Tasks.forEach is not a function, even though the tasks is an App.js based array. Why is that so ?

https://codesandbox.io/s/test-login-page-tasks-rmfn5j?file=/src/components/Taskslist.js:0-547

// Child component
    import React from "react";
    import Task from "./Task";

    const Taskslist = ({ Tasks }) => {
      return (
        <div className="wrapper">
          <h1>Tasks</h1>
          <div className="tasks__wrapper">
            <div className="tasks__queued-tasks">
              <h2>В очереди</h2>
              <div className="tasks__inner-wrapper">
                {Tasks.forEach((task) => task.status === 0) && (
                  <Task Tasks="Tasks" />
                )}
              </div>
            </div>
          </div>
          <button>Back</button>
        </div>
      );
    };

    export default Taskslist;



//App.js
const Tasks = [
  {
    id: "001",
    status: 0,
    priority: 2,
    title: "Develop website homepage",
    description:
      "Create a visually appealing and responsive homepage for the website",
    schedule: {
      creation_time: "2021-07-23T10:00:00"
    },
    author_name: "John Smith"
  },
  {
    id: "002",
    status: 1,
    priority: 1,
    title: "Implement user authentication",
    description: "Add user authentication feature to the website",
    schedule: {
      creation_time: "2021-07-24T14:30:00"
    },
    author_name: "Sarah Lee"
  }
]

function App() {
  return (
    <BrowserRouter>
      <div>
        <Header />
        <Switch>
          <Route path="/" exact={true}>
            <Login authors={Authors} />
          </Route>
          <Route path="/taskslist">
            <Taskslist Tasks="Tasks" />
          </Route>
          <Route path="/errorlogin">
            <ErrorLogin />
          </Route>
        </Switch>
      </div>
    </BrowserRouter>
  );
}

HTML page title is not set correctly except on setShortBreak()


function setWork() {
    if (playing == false) {
        startingMinutes = document.getElementById("workInput").value;
        (startingMinutes < 10)? document.querySelector("#minutes").innerHTML = '0' + startingMinutes  :  document.querySelector("#minutes").innerHTML = startingMinutes;
        document.querySelector("#seconds").innerHTML = '00';
        (startingMinutes < 10)? document.querySelector("#title").innerHTML = '0' + startingMinutes + ':' + '00'  :  document.querySelector("#title").innerHTML = startingMinutes;
    } else {
        return;
    }
}


function setShortBreak() {
    if (playing == false) {
        startingMinutes = document.getElementById("shortBreakInput").value;
        (startingMinutes < 10)? document.querySelector("#minutes").innerHTML = '0' + startingMinutes  :  document.querySelector("#minutes").innerHTML = startingMinutes;
        document.querySelector("#seconds").innerHTML = '00';
        (startingMinutes < 10)? document.querySelector("#title").innerHTML = '0' + startingMinutes + ':' + '00'  :  document.querySelector("#title").innerHTML = startingMinutes;
    } else {
        return;
    }
}


function setLongBreak() {
    if (playing == false) {
        startingMinutes = document.getElementById("longBreakInput").value;
        (startingMinutes < 10)? document.querySelector("#minutes").innerHTML = '0' + startingMinutes  :  document.querySelector("#minutes").innerHTML = startingMinutes;
        document.querySelector("#seconds").innerHTML = '00';
        (startingMinutes < 10)? document.querySelector("#title").innerHTML = '0' + startingMinutes + ':' + '00'  :  document.querySelector("#title").innerHTML = startingMinutes;
    } else {
        return;
    }
}

With each function I set the page title of the website to the current timer but if i run the function setWork() or setLongBreak instead of 25:00 it is only 25

NextJS component not applying styles

I am trying to build a NextJS App but my Navigation component is not styled as expected and not errors are displayed.

I have the src/components/navigation.js file with the following code:

import Link from 'next/link';
import styles from '../styles/Navigation.module.css';

const Navigation = () => {
  return (
    <nav className={styles.nav}>
      <Link href="/" className={styles.logo}>
        My App
      </Link>
      <ul className={styles.menu}>
        <li className={styles.menuItem}>
          <Link href="/about">
            About
          </Link>
        </li>
        <li className={styles.menuItem}>
          <Link href="/features">
            Features
          </Link>
        </li>
        <li className={styles.menuItem}>
          <Link href="/faq">
            FAQ
          </Link>
        </li>
        <li className={styles.menuItem}>
          <Link href="/contact">
            Contact
          </Link>
        </li>
      </ul>
    </nav>
  );
};

export default Navigation;

And the src/styles/Navigation.module.css file:

.nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 2rem;
    background-color: #007acc;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
}

.logo {
    font-size: 1.5rem;
    font-weight: bold;
    color: #161616;
    text-decoration: none;
    cursor: pointer;
    display: inline-block;
}

.menu {
    display: flex;
    list-style-type: none;
    margin: 0;
    padding: 0;
}

.menuItem {
    margin-left: 1.5rem;
}

.menuItem a {
    text-decoration: none;
    color: #333;
    transition: color 0.2s;
}

.menuItem a:hover {
    color: #676767;
}

Then I load the Navigation component in the src/pages/_document.js:

import Navigation from '@/components/navigation'
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="en">
      <Head />
      <body>
        <Navigation />
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

I have tried changing the paths of the styles and the component but the result remains.

The src/pages/index.js page is styled correctly and the styles paths are the same.

As you can see in the image above, there is a global.css file affecting the src/_app.js. But it just loads the Roboto font-family for the body.

So, in conclussion: It seems there is a component and a page that have the exact methodology to load CSS but only the page’s style is being loaded. What’s wrong here?

Can’t configure Cors on java spring / vue js

I have controller like this

@RestController
@RequestMapping("/api/v1/country/")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:8082")
public class CountryController {
    private final CountryService countryService;

    @GetMapping("getAll")
    public ResponseEntity<GetAllCountriesResponse> getAllCountries() {
        return ResponseEntity.ok(countryService.getAllCountriesResponse());
    }
}

and i’m trying to send request from vue js app on http://localhost:8082/ to server on http://localhost:8081/

like so

axios(“http://localhost:8081/api/v1/country/getAll”)

when i’m using postman everything is fine, but when i try to do this in vue js i get

Acess to XMLHttpRequest at ‘http://localhost:8081/api/v1/country/getAll’ from origin ‘http://localhost:8082’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

How can i configure this on spring v3.0.1