How to save input=file submitted files in cache to display them in browser and only upload after a few steps (javascript/php)

I’m creating a file upload/edit tool for a photography company where the users should be able to upload multiple photos, view them, select some options for each of them, then go to the shopping cart and pay for their order. I want to only actually upload the photos to the server after they’ve submitted the shopping cart, so that’s a few steps later. I also want them to be able to go back to the editing page and see the photos they upload and change the options before going back to the shopping cart. I’d like to save the photos in cookies or in the php $_SESSION variable or somewhere else so that I can still access them after the page has been refreshed or the user has navigated somewhere else on the site.
I’m using JavaScript and PHP

What I’m doing right now is, using javascript, when the files are dropped into the box, the file type input receives the files and then for each file, i create a div with the image in it and use

URL.createObjectURL(file)

to get the local path for the file. This works, the images do appear. My problem is that after submitting the form, I don’t know how to save the files in order to later be able to access them in the same way. I’m now saving the URL.createObjectURL(file) in a cookie, but then when i access that cookie with javascript, the path no longer works.

JS – JSON where in for Prisma 5.x.x

I’m trying to migrate from prisma 3.x.x, to version 5.x.x. However, I’m having a problem trying to do a where In, on a JSON column.

This use to work, but when trying in the new version produces an error. Does anyone know how to achieve this on the new version? It’s not listed in their docs. https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/working-with-json-fields#filter-on-a-json-field-simple

const result = await prisma.user.findMany({
where: {
OR: [
{
user_data: {
path: [‘user’, ’email’],
in: input.emails
}
}
],
},
})

model user {
user_id String
user_data Json // { email: String }
@@index([user_id])
}

How can i edit this Bootstrap5 dropdown menu?

I want to edit this dropdown-menu made with bootstrap5 but i can’t edit the classes/id. I want to make the menu central in the page (i’ve tryed with flex-layout but nothing changes), sticky on top when i scroll down the page and the submenu long all the width of the page. I have to make it similar to this page menu. Please help me

<nav class="navbar sticky-top navbar-expand-lg navbar-light bg-light">
            <div class="container-fluid">
                <button class="navbar-toggler border-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <i class="bi bi-chevron-down"></i>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="" role="button" data-bs-toggle="dropdown" aria-expanded="false">Lorem</a>
                            <div class="dropdown-menu">
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                            </div>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="" role="button" data-bs-toggle="dropdown" aria-expanded="false">Lorem</a>
                            <div class="dropdown-menu">
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                            </div>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="" role="button" data-bs-toggle="dropdown" aria-expanded="false">Lorem</a>
                            <div class="dropdown-menu">
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                            </div>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="" role="button" data-bs-toggle="dropdown" aria-expanded="false">Lorem</a>
                            <div class="dropdown-menu">
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                                <ul>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                    <li><a class="dropdown-item" href="">Lorem Ipsum</a></li>
                                </ul>
                            </div>
                        </li>
                     </ul>
                </div>
            </div>
        </nav>
<style>
.navbar a:hover{
    text-decoration: underline;
}

.dropdown-menu{
    font-size: 0.8rem;
    left:0;
    border:none;
    text-align:center;
    position: absolute;
    border-radius: 0;
    box-shadow: 0 10px 10px rgba(0,0,0,0.1);
    display: grid;
    grid-template-columns: auto auto auto auto auto;
    visibility: hidden;
    min-width: 100%;
    z-index: 999;
}

.dropdown:hover .dropdown-menu{
    visibility: visible;
}

.dropdown-menu.show{
    display:flex;
}

.dropdown-menu a:hover{
    color:darkgrey;
    text-decoration: none;
}

.dropdown-menu li:first-child a{
    color:darkgrey;
    padding:20px 0;
}
</style>

Performing multiple realtime database operations within firebase cloud function trigger

I am attempting to generate an invitation code based on when a user adds data to the /households/{house_id} path using the onValueCreated() trigger provided by cloud functions.

exports.onCreateHousehold = onValueCreated("/households/{house_id}", (event) => {
        // We are not interested in adding a code if the household already exists
        if (event.data.child("code").val() != null) {
            return null;
        }

        // A 6 letter/number code translates to 2,176,782,336 possible combinations
        const codeLength = 6
        return generateCode(codeLength).then((code) => {
                log(`Household code generated: ${code}`);
                // With the code generated, save the code (this is the problem)
                addCode(event.params.house_id, event.data.child("owner").val(), code).then(() => {
                    log(`The code has been added :)`);
                })
            }
        )
    }
)

More specifically, I am generating a code:

/* House invitation code functions */

async function generateCode(codeLength) {
    var validCharacters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var code = "";
    for (i = 0; i <= codeLength; i++) {
        code += validCharacters.charAt(parseInt(Math.random() * validCharacters.length));
    }
    // Check this code doesn't conflict with any existing household codes
    const codeMatch = await doesCodeMatch(code);
    if (codeMatch) {
        // Perform recursion until a unique code is found
        generateCode(codeLength);
    }
    return code;
}

Checking whether this code exists in any existing households:

async function doesCodeMatch(code) {
    const householdsRef = db.ref("households");
    // Wait until the database has been checked before returning the answer
    return await householdsRef
        .equalTo(code)
        .once("value", (data) => {
            return data.exists()
        });
}

Then writing the invitation code to the household:

async function addCode(houseID, userID, code) {
    const householdData = {
        code: code
    };
    const updates = {};
    updates[`/households/${houseID}`] = householdData;
    updates[`/users/${userID}/households/${houseID}`] = householdData;
    return await update(ref(db), updates);
}

However every time this function runs I get the error RangeError: Maximum call stack size exceeded.

I have attempted to run addCode() on its own in the onValueCreated() function just to see if updating the /households/{house_id} was causing some loop where onValueCreated() would be retriggered continuously but this wasn’t a problem and the code was added to the path:

exports.onCreateHousehold = onValueCreated("/households/{house_id}", (event) => {
        if (event.data.child("code").val() != null) {
            return null;
        }

        // This works fine and F45FD3 gets added
        addCode(event.params.house_id, event.data.child("owner").val(), "F45FD3").then(() => {
            log(`The code has been added :)`);
        })
    }
)

This led me to believe then it is something to do with multiple operations being made to the realtime database. Is it possible to make multiple read/writes/updates etc. to the realtime database within a single cloud function trigger, and if so, how could this be done?

useState doesn’t update values

In short, worked quietly, but then wrote a couple of lines of code for an image that is not even related to useState just broke, other pages use the same methods as here, but they work there. I can’t explain exactly why this happens, probably due to repetition, where the first time it turns out to change the value, but then the second time it goes back to the standard value. I made this conclusion only because of the repetition in the console when I change the meaning in the text.

function CreateProduct({ navigation }) {
  const [error, setError] = useState("");
  const [categories, setCategories] = useState([])
  const [loading, setLoading] = useState(<TouchableOpacity style={styles.button} onPress={()=>{handleSubmit()}}><Text style={styles.buttonText}>Створити</Text></TouchableOpacity>)
  const [image, setImage] = useState("https://img.icons8.com/material-outlined/96/add-image.png");
  const [data, setData] = useState({
    name: "",
    price: "",
    description: "",
    category: 0
  });
  function handleChange(name, value) {
      setData((prevState) => ({...prevState,[name]: value,}))
    
  }
  async function getProfile() {
      fetch(`${url}/user`,{
        method: "GET",
        headers: {
          "apikey": await AsyncStorage.getItem('apikey')
        }
      })
      .then(response => response.json())
      .then(data => {
        if (data.data.length <= 0 || data.error) {
          navigation.navigate('Login')
        }
      })
      .catch(error => {
        navigation.navigate('Login')
      })
  }
  function getCategories(){
    fetch(`${url}/categories`,{
      method: "GET"
    })
    .then(response => response.json())
    .then(data => {
      setCategories(data.categories)
    })
  }


  async function handleSubmit() {
    setError("")
    if (!data.name){
      setError("Enter a name")
      return
    }
    if (!data.price){
      setError("Enter a price")
      return
    }
    if (!data.description){
      setError("Enter a desc")
      return
    }
    if (data.category == 0){
      setError("Choose a category")
      return
    }
    if (image == "https://img.icons8.com/material-outlined/96/add-image.png"){
      setError("Add an image")
      return
    }

    fetch(`${url}/productMobile`, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'token': await AsyncStorage.getItem('apikey')
      },
      body: JSON.stringify({
        name: data.name,
        price: data.price,
        desc: data.description,
        image: image,
        cat: data.category
      }),
    })
    .then(response => response.json())
    .then(async data => {
      if (data.error) {
        setLoading(<TouchableOpacity style={styles.button} onPress={()=>{handleSubmit()}}>
        <Text style={styles.buttonText}>Створити</Text>
      </TouchableOpacity>)
        setError("Error while uploading Image");
      } else {
        setError("")
        navigation.navigate("Account")
      }
    })
  }

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 0.5,
      base64: true,
    });
    if (!result.cancelled) {
      setImage(`data:${result.assets[0].mimeType};base64,${result.assets[0].base64}`);
    } else {
      setError("Не вдалося додати зображення")
    }
  };

  useEffect(() => {
    getCategories();getProfile()
  }, [])


  return(
    <View style={styles.containerShop}>
      <View style={{backgroundColor: '#7F27FF', width: '100%', height: 70, alignItems: 'center', justifyContent: 'center'}}>
        <Text style={{color: 'white', fontSize: 30, fontWeight: 'bold'}}>Створення</Text>
      </View>
      <ScrollView style={{width: '100%'}}>
        <View style={{alignItems: 'center', justifyContent: 'center', marginTop: 20, marginBottom: 20}}>
      
      <TouchableOpacity onPress={pickImage}>
          <Image style={styles.uploadImg} source={{ uri: image}}/>
      </TouchableOpacity>


      <View>
          <Text style={styles.inputLabel}>Ім'я товару</Text>
          <TextInput
            style={styles.input}
            onChangeText={(value) => {handleChange('name',value)}}
            placeholder=" ..."
            value={data.name}
          />
      </View>

      <View>
          <Text style={styles.inputLabel}>Ціна товару</Text>
          <TextInput
            style={styles.input}
            onChangeText={(value) => {handleChange('price',value)}}
            placeholder=" ..."
            keyboardType="numeric"
            value={data.price}
          />
      </View>

      <View style={{width: "90%", marginTop: 10, marginBottom: 10}}>
          <Text style={styles.inputLabel}>Категорія</Text>
          <View style={styles.picker}>
          <RNPickerSelect value={data.category} onValueChange={(value) => {handleChange('category',value)}} 
          items={categories && categories.map(item => ({label: item.name, value: item.id}))} />
          </View>

     
      </View>


      <View>
          <Text style={styles.inputLabel}>Опис</Text>
          <TextInput
            style={styles.inputDesc}
            value={data.description}
            onChangeText={(value) => {handleChange('description',value)}}
            placeholder=" ..."
          />
      </View>

      <Text style={styles.error}>{error}</Text>

      {loading}

      </View>
      </ScrollView>
      <View style={styles.footer}>
          <TouchableOpacity style={{flexDirection: 'column', alignItems: 'center'}} onPress={()=>{navigation.navigate('Main')}}>
            <Image source={require('./assets/home.png')} style={{width: 40, height: 40}}/>
            <Text style={{fontSize: 18, fontWeight: 'bold', color: 'white'}}>Головна</Text>
          </TouchableOpacity>
          <TouchableOpacity style={{flexDirection: 'column', alignItems: 'center'}} onPress={()=>{navigation.navigate('CreateProduct')}}>
            <Image source={require('./assets/add.png')} style={{width: 40, height: 40}}/>
            <Text style={{fontSize: 18, fontWeight: 'bold', color: 'white'}}>Створити</Text>
          </TouchableOpacity>
          <TouchableOpacity style={{flexDirection: 'column', alignItems: 'center'}} onPress={()=>{navigation.navigate('Account')}}>
            <Image source={require('./assets/user.png')} style={{width: 40, height: 40}}/>
            <Text style={{fontSize: 18, fontWeight: 'bold', color: 'white'}}>Акаунт</Text>
          </TouchableOpacity>
      </View>
    </View>
  )
}

I tried removing function call retry using useState, which checks for function dispatches and also useEffect, useTimeout, but they didn’t help anywhere close. I then started thinking about using useEffect to call 2 functions when running the page, I thought it was because of them, but even after deleting useEffect, nothing changed. And, unfortunately, apart from these assumptions, there were no others.

Issues with slider interaction when component is nested

I’m trying to get into React, so thought I’d set myself a project of creating a web audio stem player. Everything seemed to be working until I tried to integrate drag and drop functionality. I got the drag and drop working, however the interactive elements of each of my tracks stopped working.

If the Track is rendered directly in the App, the sliders and knobs work fine, but if they’re within another component (in the example the TrackWrapper) they stop working. They can’t be moved, though the values they’re setting seem to be correct i.e. if you console log the values in setStemVolume and setStemPan, they’re the correct values dependent on where on the slider is clicked.

I’ve a feeling it’s to do with the way I’m setting/getting state of the elements but I can’t seem to figure it out. I’m not sure if on the re-renders the elements are getting reset to some default value.

There’s a CodeSandbox stripped down version of what I’ve been working on linked here, that features just a slider and knob that don’t really do anything.

return (
    <div>
      {stems.map((track) => (
        // This doesn't work

        <TrackWrapper key={track.file} track={track} 
        onSliderInput={(e) => setStemVolume(e, track.gainNode, track.uuid)}
        onPanSliderInput={(newValue) =>
          setStemPan(newValue, track.panNode, track.uuid)
        }/>

      //   This works
      //   <Track
      //   key={track.file}
      //   backgroundColour={track.colour}
      //   muteState={track.muted}
      //   soloState={track.soloed}
      //   volume={track.volume}
      //   pan={track.pan}
      //   onSliderInput={(e) => setStemVolume(e, track.gainNode, track.uuid)}
      //   onPanSliderInput={(newValue) =>
      //     setStemPan(newValue, track.panNode, track.uuid)
      //   }
      // />

      ))}
    </div>
  );

Thanks in advance for any help you can provide!

Don’t understand how “this” functions here [duplicate]

can someone please explain to me what “this” refers to in <li onclick=selectInput(this)> and why that is? For context, result is just an array with some strings. This is a code I saw in a youtube tutorial for making an autocomplete searchbox (this video, around 20 minutes: https://www.youtube.com/watch?v=pdyFf1ugVfk)

function display(result) {
  const content = result.map((list) => {
    //not sure how 'this' works here below
    return "<li onclick=selectInput(this)>" + list + "</li>";
  });
  results.innerHTML = "<ul>" + content.join("") + "</ul>";
}
function selectInput(list) {
  inputBox.value = list.innerHTML;
  results.innerHTML = "";
}

How to migrate a public scoped package from Google Artifact Registry to NPM registry

I have published a scoped public package into Google Artifact Registry, now I would like to move this to NPM/Github Packages registry.

Is there any documentation or way on how to achieve this.

I have tried deleting the package from Google Artifact Registry, waited for 24hrs, and tried publishing after creating an account in npm. But it doesn’t work.

npm ERR! 404 Not Found - PUT https://registry.npmjs.org/@org-scoped/xxx - Not found

How to remove sunday and holdiay hours in between two given datetime

Any suggestions or ways to approach to calculating idleTime? For the given two date time.

Cases for I’m struggling to solve,

  1. If the start Date is Sunday or Holiday: remaining Sunday hours + morning of the next day(till 6: 30 AM ) should not be considered to idle time.

  2. if the end Date is Sunday or Holiday , the time of the day must not be considered to idle time.

The code that I have mentioned below is not accurate.

Expected output for:

startTime = "2024-05-05T12:00:00Z"; // Assuming UTC format <br>
endTime = "2024-05-06T13:00:00Z";   // Assuming UTC format

o/p => 7 hours <br>
difference hours ( endTime - startTime )= 25.000 ,  sundayHours =  18, differenceHours - sundayHours - holidayHours = 7

What I have tried so far,

function calculateIdleTimeExcludingSundaysAndHolidays(startTime, endTime) {
var startUtc = new Date(startTime).getTime();
var endUtc = new Date(endTime).getTime();
var totalIdleTime = 0;

    for (var currentTime = startUtc; currentTime < endUtc; currentTime += 60 * 1000) { // Increment by 1 minute
        var currentDateTime = new Date(currentTime);
        if (currentDateTime.getUTCDay() !== 0 /* Not Sunday */ ) {
            totalIdleTime += 1; // 1 minute in seconds
        }
    }
    
    return totalIdleTime;

}


// Example usage
var startTime = "2024-05-13T12:00:00Z"; // Assuming UTC format
var endTime = "2024-05-15T13:00:00Z";   // Assuming UTC format

var idleTimeInMinutes = calculateIdleTimeExcludingSundaysAndHolidays(startTime, endTime);<br>
console.log("Idle time in minutes (excluding Sundays and holidays):", idleTimeInMinutes);

React Router redirect function not working

I am implementing a fake authentication system in React router that re-directs the user to the login page with route “/login” when the user is not logged in. The function is in utils.js and I am exporting it to my App.js file where the routes are defined.

The function in utils.js is very basic and looks like this

import { redirect } from "react-router-dom"

export async function requireAuth() {
    const isLoggedIn = false

    if(!isLoggedIn) throw redirect("/login")
}

Then I am importing and providing the function call directly in my loader prop in App.js, like this

import React from 'react';
import { 
  Route, 
  RouterProvider, 
  createBrowserRouter, 
  createRoutesFromElements,
} from 'react-router-dom';
import './server.js';
import './App.css';
import Home from './pages/Vans/Home';
import About from './pages/Vans/About';
import Vans, { loader as vansLoader } from './pages/Vans/Vans';
import Login from './pages/Auth/Login.jsx';
import VanDetail, { loader as vanLoader } from './pages/Vans/VanDetail';
import Layout from './components/Layout';
import HostLayout from './components/HostLayout';
import Dashboard from "./pages/Host/Dashboard";
import Income from './pages/Host/Income';
import HostVans, { loader as hostVansLoader } from "./pages/Host/HostVans";
import HostVanDetail, { loader as hostVanLoader } from './pages/Host/HostVanDetail';
import HostVanInfo from './components/HostVanInfo.jsx';
import Reviews from './pages/Host/Reviews';
import HostVanPrice from './components/HostVanPrice.jsx';
import HostVanPhotos from './components/HostVanPhotos.jsx';
import NotFound from './components/NotFound.jsx';
import Error from './components/Error.jsx';
import { requireAuth } from './utils.js';

const router = createBrowserRouter(createRoutesFromElements(
  <Route path="/" element={<Layout />} errorElement={<Error />}>
    <Route index element={<Home />} />
    <Route path="about" element={<About />} />
    <Route
      path="login"
      element={<Login />}
    />
    <Route
      path="vans"
      element={<Vans />}
      loader={vansLoader}
    />
    <Route 
      path="vans/:id" 
      element={<VanDetail />} 
      loader={vanLoader}
    />
    <Route path="host" element={<HostLayout />}>
      <Route
        index
        element={<Dashboard />}
        loader={async () => await requireAuth()} 
      />
      <Route
        path="income"
        element={<Income />}
        loader={async () => await requireAuth()}
      />
      <Route
        path="reviews"
        element={<Reviews />}
        loader={async () => await requireAuth()}
      />
      <Route
        path="vans"
        element={<HostVans />}
        loader={hostVansLoader}
      />
      <Route
        path="vans/:id"
        element={<HostVanDetail />}
        loader={hostVanLoader}
      >
        <Route
          index
          element={<HostVanInfo />}
          loader={async () => await requireAuth()}
        />
        <Route
          path="pricing"
          element={<HostVanPrice />}
          loader={async () => await requireAuth()}
        />
        <Route
          path="photos"
          element={<HostVanPhotos />}
          loader={async () => await requireAuth()}
        />
      </Route>
    </Route>
    <Route path="*" element={<NotFound />} />
  </Route>
))

function App() {
  return (
    <div className="App">
      <RouterProvider router={router} />
    </div>
  );
}

export default App;

I was expecting the React router to route to the /login page when I try to go to /host route it renders a blank page to the screen. I checked the Network tab in dev-tools and its not fetching the login page document but rather the same host document with HTTP code 304. Can somebody help me fix this issue?

JavaScript – Overlay from Image transforming in the video

I’m not good at English but I will try to explain better.

    <!-- FILM -->
    <!-- CONTAINER FILM -->
    <div class="container-fluid text-white">
        <!-- RIGA FILM -->
        <div class="row">
            <!-- COLONNA FILM -->
            <div class="col-11 fs-5 pt-3" style="margin-left: 35px;">
                <strong style="color: #fd0167;">Film</strong> / Novità
            </div>
            <!-- IMMAGINI CON I RISPETTIVI LINK -->
            <div class="col-11 d-flex justify-content-between" style="margin-left: 50px; margin-top: 20px;">
                <a href="page3.html">
                    <img id="myImg" src="img/carousel/comedy-shot.png"
                        class="d-block" width="250" alt="Commedia" title="Clicca qui per vedere il film commedia">
                    <video id="myVideo" src="video/video.mp4"
                        style="display: none; width: 250px; position: absolute; top: 90px;"></video>
                </a>
                <a href=" page3.html"><img src="img/carousel/dramatic-shot.png" class="d-block" width="250"
                        alt="Drammatico" title="Clicca qui per vedere il film drammatico"></a>
                <a href="page3.html"><img src="img/carousel/matrix-shot.png" class="d-block" width="250" alt="Matrix"
                        title="Clicca qui per vedere il film Matrix"></a>
                <a href="page3.html"><img src="img/carousel/action-shot.png" class="d-block" width="250" alt="Azione"
                        title="Clicca qui per vedere il film Azione"></a>
                <a href="page3.html"><img src="img/carousel/starwars-shot.png" class="d-block" width="250"
                        alt="StarWars" title="Clicca qui per vedere il film Star Wars"></a>
            </div>
        </div>
    </div>
    <!-- FINE FILM -->

This is my HTML code and HOW can I do that the image will be hovered with the video? “WDYM” you will say. I’ll explain better. I have multiple images and you can notice, now I need that each image (that have different positions each) have the hover effect that will change in video with the same width of the image (all images have the same width, 250px) I repeat, but the positions of the image are different. For positions I am saying (just an example):

Image 1: X: 10 Y: 10
Image 2: X: 20 Y: 15
Image 3: X: 25 Y: 40

// And others…

(In this case I’m using Bootstrap 5.3 that have the columns with d-flex and justify-content-between)

But I do not need only video, do you have present that card layout? Image (in my case the video), texts (title and a paragraph) and optionally a button that says “Play” with the icon of play. And if is out of the range of hovering (so outside of the video) will return the original image.

Hope you understood and if you do not understood the question that I made, just comment.
Have a good day.

Languages:

HTML, CSS and JS

Is there a way to make an api call using insomnia WITHOUT using url encoding & escaping the character?

Here is the premise:

I have this backend which has routers which take query in api calls (GET calls to be precise).
Now I have a JSONPath(Just an npm package to filter out JSON inputs using some standardized queries) implementation in one of the routers. This implementation requires queries from the API calls.

Now the requirement is to follow simple query format with logical && || == etc. in the api call & return the result. Problem in short is that using some symbols causes query to break & work unexpectedly.

Also,I have used “Automatically encode special characters in URL” Option in Insomnia. So that doesn’t really help in case of &(ampersand).

Here’s an example query for some example from JSONPath npm page:

?filter=$..book[?(@.price<30 && @.category=="fiction")]

which should result in a dictionary/js object like: {filter : "$..book[?(@.price<30 && @.category=="fiction")]"}

The problem arises when we make a request to the API & pass the query with an ampersand(&) symbol.
The query splits in 2 parts & results in unexpected errors as JSONPath only takes 1 query and 1 json at a time.
something like this(an array of wrong queries): {filter: ['$..book[?(@.price<30', '@.category=="fiction")']

Alternative is to use % encoding: ?filter=$..book[?(@.price<30 %26%26 @.category=="fiction")]

*I need to avoid %26 as encoding in api call so as to make queries simple but can’t find some way to escape or read api calls at time of calling itself.. they just can’t seem to be processed before reaching my program..

*

If anyone knows a way, please give some suggestions.
Thanks.

Open Batch Script in Neutralino JS

(Windows, Neutralino js)
I need to open a batch script in resources directory of Neutralino JS, i tried using

Neutralino.os.execCommand("start test.bat")

but it didn’t work, i tried resources test.bat, resources test.bat, all kinds of combinations, but they didn’t work.
Is this even possible?

function disableTelemetry() {
    Neutralino.os.execCommand('start /resources/telemetry.bat')
}

ReferenceError: Amplify is not defined in javascript and cognito setup

I have a web app using javascript, lambda and cognito. I need to get the current user after sign in. I couldn’t find much resource on how to get the current session info and current user.
I found the following solution on the Web and tried but it gives mainpage.html:19 Uncaught ReferenceError: Amplify is not defined.
When I search for this, I couldnt find a useful solution. How to I correct it or is there an easier way to get the current user?

<script src="https://cdnjs.cloudflare.com/ajax/libs/aws-sdk/2.1167.0/aws-sdk.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/aws-amplify/4.3.5/amplify.min.js"></script>
    <script>
        // Initialize Amplify
        Amplify.configure({
            Auth: {
                // Your AWS Cognito configuration here

                // region: 'YOUR_REGION',
                region: 'us-east-1',
                // userPoolId: 'YOUR_USER_POOL_ID',
                userPoolId: 'us-east-1_xxxxxxxxx',
                // userPoolWebClientId: 'YOUR_APP_CLIENT_ID'
                userPoolWebClientId: 'xxxxxxxxxxxxxxxxxxxxx'
            }
        });

        // Function to get currently logged in user
        async function getCurrentUser() {
            try {
                const user = await Auth.currentAuthenticatedUser();
                return user;
            } catch (error) {
                console.error('Error getting current user:', error);
                return null;
            }
        }
</script>