React Error while importing Google Maps module

I have created a webpage using react that displays a real-time map using Google Maps API, an array of strings with geographical addresses is given. All those addresses are to reflect on Google Maps using a marker at their respective addresses. However, I am getting the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

Check the render method of Map.
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

Check the render method of Map.
at createFiberFromTypeAndProps (http://localhost:3001/static/js/bundle.js:47804:21)
at createFiberFromElement (http://localhost:3001/static/js/bundle.js:47825:19)
at reconcileSingleElement (http://localhost:3001/static/js/bundle.js:36916:27)
at reconcileChildFibers (http://localhost:3001/static/js/bundle.js:36966:39)
at reconcileChildren (http://localhost:3001/static/js/bundle.js:39908:32)
at mountIndeterminateComponent (http://localhost:3001/static/js/bundle.js:40745:9)
at beginWork (http://localhost:3001/static/js/bundle.js:41973:20)
at HTMLUnknownElement.callCallback (http://localhost:3001/static/js/bundle.js:26983:18)
at Object.invokeGuardedCallbackDev (http://localhost:3001/static/js/bundle.js:27027:20)
at invokeGuardedCallback (http://localhost:3001/static/js/bundle.js:27084:35)

My Map component code is:

import React, { useState, useEffect } from 'react';
import { MapContainer, Marker, GoogleApiWrapper } from 'google-maps-react';
import { Loader } from '@googlemaps/js-api-loader';

const Map = ({ google }) => {
  const [addresses, setAddresses] = useState([
    '1600 Amphitheatre Parkway, Mountain View, CA',
    '1 Infinite Loop, Cupertino, CA',
    '350 Fifth Avenue, New York, NY',
  ]);

  const [coordinates, setCoordinates] = useState([]);

  useEffect(() => {
    const loader = new Loader({
      apiKey: 'YOUR_API',
      version: 'weekly',
      libraries: ['places'],
    });

loader.load().then(() => {
  const geocoder = new google.maps.Geocoder();

  const fetchCoordinates = async () => {
    const coordinates = [];

    for (let i = 0; i < addresses.length; i++) {
      const result = await new Promise((resolve, reject) => {
        geocoder.geocode({ address: addresses[i] }, (result, status) => {
          if (status === 'OK') {
            resolve(result[0].geometry.location);
          } else {
            reject(status);
          }
        });
      });

      coordinates.push(result);
    }

    setCoordinates(coordinates);
  };

  fetchCoordinates();
});
}, [addresses, google.maps.Geocoder, google.maps.places]);

return (
  <MapContainer google={google} center={{ lat: 37.7749, lng: -122.4194 }} zoom={10}>
    {coordinates.map((coordinate, index) => (
      <Marker key={index} position={{ lat: coordinate.lat(), lng: coordinate.lng() }} />
    ))}
  </MapContainer>
);
};

export default GoogleApiWrapper({
  apiKey: 'YOUR_API',
})(Map);

My App.js code is:

import { GoogleApiWrapper } from 'google-maps-react';
import Map from './components/locator/loc';

function App(props) {
  return (
    <div className="App">
      <Map google={props.google} />
    </div>
  );
}

export default GoogleApiWrapper({
  apiKey: 'YOUR_API',
})(App);

Problem with connecting yandex maps components to reactjs

I tried adding placemark as a function, the result is similar. From the import at the top, react takes components only into markup. React outputs the following error: ymaps.Placemark is not a constructor.

import React from "react";
import './SearchPower.css';
import { YMaps, Map, Placemark} from '@pbe/react-yandex-maps';

function App() {

    const ymaps = (Map, Placemark)
    // The error is here   var placemark = new ymaps.Placemark([55.75, 37.61], {
      balloonContent: '<img src="http://img-fotki.yandex.ru/get/6114/82599242.2d6/0_88b97_ec425cf5_M" />',
  }, {
      preset: "islands#yellowStretchyIcon",
      balloonCloseButton: false,
      hideIconOnBalloonOpen: false
  });
  const myMap = React.useMemo(
    () => ({ center: [lat, lng], zoom: 9 })
  );

    return (
      <div className="ContextSP">
        <div className="DivMarks">
        <img className="MarkLeftImage" src="images/Marks/ZemMark.png"/>
        <img className="MarkImage" src="images/Marks/Redcar1Mark.png"/>
        <img className="MarkImage" src="images/Marks/Redcar2Mark.png"/>
        <img className="MarkImage" src="images/Marks/GreencarMark.png"/>
        <img className="MarkRightImage" src="images/Marks/YellowcarMark.png"/>
        </div>
          <YMaps>
          <Map style={{width: '100%', height: '100%', margin: '0 0 10px 0'}} state={myMap}>
          <Placemark geometry={[lat, lng]} 
              options={{
                iconLayout: 'default#image',
                iconImageHref: IconGeoPosition,
                iconImageSize: [40, 40],
                iconImageOffset: [100, -10]
              }}/>
          </Map>
          </YMaps>
        </div>
        )
    }
    export default App;

Uncaught TypeError: “SinkShip” is not a function at window.onload

I’m new to JS and I don’t understand why this code is not working?

I want to call a class every time the page is loaded or refreshed.
To test this I added the initialises method to the constructor.
Unfortunately I get this error and I don’t understand why:

script.js:16 Uncaught TypeError: SinkShip is not a function
    at window.onload 

This is my .js Code so far.

class SinkShip{

    constructor(){
        this.initialies
    }

    initialies(){
        alert('it works');
    }

}

window.onload = (event)=>{
    console.log('HIIIII');
    let SinkShip;
    SinkShip();
};

Webpack generates one chunk always

I have tried different webpack configuration settings – always 1 big chunk, and even though Webpack documentation says that its SplitChunksPlugin is well configured by default

I have react application.
Webpack related versions are:

"webpack": "5.78.0",
"webpack-bundle-analyzer": "^4.8.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.13.2"

My Webpack config:

const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const WebpackManifestPlugin = require('webpack-manifest-plugin').WebpackManifestPlugin
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const dotenv = require('dotenv')

const env = dotenv.config().parsed
const isProdBuild = ['staging', 'production'].indexOf(env.NODE_ENV) > -1

const postcssLoaderConfig = {
  postcssOptions: {
plugins: [
  ['postcss-preset-env'],
  ['autoprefixer']
]
  }
}

const plugins = [
  /*new webpack.EnvironmentPlugin([
  'CLOUDINARY_BUCKET',
  'AUTH0_CLIENT_ID',
  'AUTH0_DOMAIN',
  ]),
  new MiniCssExtractPlugin({
filename: 'styles/[name]-[contenthash].css'
  }),*/
  /*new HtmlWebpackPlugin({
chunks: ['app'],
base: '/admin',
filename: 'index-admin.html',
hash: true,
minify: isProdBuild ? {
  removeComments: true,
  collapseWhitespace: true,
  removeRedundantAttributes: true,
  useShortDoctype: true,
  removeEmptyAttributes: true,
  removeStyleLinkTypeAttributes: true,
  keepClosingSlash: true,
  minifyJS: true,
  minifyCSS: true,
  minifyURLs: true
} : {}
  }),*/
  /*new CopyWebpackPlugin({
patterns: [
  {
    from: path.resolve(__dirname, '../assets/images'),
    to: 'images',
    globOptions: {
      ignore: ['**!/.gitkeep']
    }
  },
  { from: path.resolve(__dirname, '../assets/favicon.png') },
  { from: path.resolve(__dirname, '../assets/favicon.ico') }
]
  }),
  new WebpackManifestPlugin(),*/
]

if (!isProdBuild) {
  plugins.push(new BundleAnalyzerPlugin())
}

module.exports = {
  entry: {
main:  path.resolve(__dirname, '../assets/js/app/index.jsx'),
  },
  output: {
path: path.resolve(__dirname, '../public/assets'),
filename: 'js/[name]-[contenthash].js',
publicPath: '/'
  },
  module: {
rules: [
  {
    test: /.css$/,
    use: [
      MiniCssExtractPlugin.loader,
      {
        loader: 'css-loader'
      }
    ]
  },
  {
    test: /.(js|jsx)$/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          '@babel/preset-env',
          ['@babel/preset-react', {'runtime': 'automatic'}]
        ]
      }
    },
    exclude: /(node_modules/(?!(screenfull)/))|(assssets/js/).*/,
  },
  {
    test: /.scss$/,
    use: [
      MiniCssExtractPlugin.loader,
      {
        loader: 'css-loader'
      },
      {
        loader: 'postcss-loader',
        options: postcssLoaderConfig
      },
      {
        loader: 'fast-sass-loader'
      }
    ]
  },
  {
    test: /.(ttf|otf|eot|svg|woff(2)?)(?[a-z0-9]+)?$/,
    use: {
      loader: 'file-loader',
      options: {
        name: 'fonts/[name].[ext]'
      }
    }
  },
  {
    test: /.(png|jpg|gif|svg)$/,
    type: 'asset/resource'
  }
]
  },
  resolve: {
extensions: ['', '.js', '.jsx'],
  },
  plugins
}

Insert HTML at caret in a contenteditable div in react

How can we use React to add a span tag to the last place where the cursor is in a div whose contentEditable property is already set to true(package react-contenteditable)? This div contains only plain text and a span tag. The span tag should be treated as a single character, and nothing else should be created within it. A button should be used to insert a new span at the last point where the cursor was.

Attention : The user should not be able to add anything in the selected text again.

codesandbox project

like this :

svg

My deployed page on github is going to another page which does not exist

I am learning React and I have completed a project and deployed it using GitHub page. But when its deployed, its pointing to textutils–React but I have no such page it should be pointing to the home page. And when I click the home page or about page in the website, it works fine.
I want the deployed page to take me to the home page directly when opening my project using GitHub page.

GitHub page

Link - <https://github.com/shresthgour/textutils--React>  
Website Link on GitHub - <https://shresthgour.github.io/textutils--React/>  
Correct Link - <https://shresthgour.github.io/>

How rewrite this code using promise chaining?

function getSmth(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(num * num), 500)
  });
}
function func() {
  getSmth(2).then(res1 => {
    getSmth(3).then(res2 => {
      getSmth(4).then(res3 => {
        console.log(res1 + res2 + res3);
      });
    });
  });
}
   func();
function getSmth(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(num * num), 500)
  });
}
function func() {
  getSmth(2)
    .then(res1 => getSmth(3))
    .then(res2 => getSmth(4))
    .then(res3 => {
      console.log(res1 + res2 + res3);
    })
}
func();

Should output 29 to the console but it’s not work.

Click image and display details & Pages not dynamic

here is my item list code:

<!DOCTYPE html>
<html>
<head>
    <title>Item List Page</title>
    <link rel="stylesheet" href="css/theme.css">
    <script src="javascript.js"></script>
</head>
<body>
    <div class="search-box">
        <label for="search"></label>
        <input type="text" id="search" name="search">
        <button id = "searchButton" onclick="searchItems()">Search</button>
    </div>
    <div class="filter">
    <label for="category">Filter by category: </label>
    <?php $category = $_GET['category'] ?? 'all'; ?>
    <select id="category" name="category" onchange="window.location.href = '?category=' + this.value;'">
        <option value="all" <?= $category === 'all' ? 'selected' : '' ?>>All</option>
        <option value="dark chocolate" <?= $category === 'dark chocolate' ? 'selected' : '' ?>>Dark Chocolate</option>
        <option value="milk chocolate" <?= $category === 'milk chocolate' ? 'selected' : '' ?>>Milk Chocolate</option>
        <option value="white chocolate" <?= $category === 'white chocolate' ? 'selected' : '' ?>>White Chocolate</option>
    </select>
    </div>
    <div class="list_container">
        <div id="items-list">
            <?php 
                session_start();
                $category = isset($_GET['category']) ? $_GET['category'] : 'all';
                $search = isset($_GET['search']) ? $_GET['search'] : '';
                $conn = new mysqli('localhost', 'root', '', 'chocolate');
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }

                // Set number of results to display per page
                $results_per_page = 3;

                // Determine current page number
                if (isset($_GET['page']))
                    $current_page = $_GET['page'];
                else
                    $current_page = 1;

                // Calculate starting and ending limit for results
                $start_limit = ($current_page - 1) * $results_per_page;
                $end_limit = $start_limit + $results_per_page;

                // Retrieve total number of results from database
                if ($category === 'all') {
                    $sql = "SELECT COUNT(*) as total FROM items WHERE name LIKE '%$search%'";
                } else {
                    $sql = "SELECT COUNT(*) as total FROM items WHERE category = '$category' AND name LIKE '%$search%'";
                }
                $result = mysqli_query($conn, $sql);
                $row = mysqli_fetch_assoc($result);
                $total_results = $row['total'];

                // Calculate total number of pages
                $total_pages = ceil($total_results / $results_per_page);

                // Retrieve results from database for current page
                if ($category === 'all') {
                    $sql = "SELECT * FROM items WHERE name LIKE '%$search%' LIMIT $start_limit, $results_per_page";
                } else {
                    $sql = "SELECT * FROM items WHERE category = '$category' AND name LIKE '%$search%' LIMIT $start_limit, $results_per_page";
                }
                $result = mysqli_query($conn, $sql);

                // Display items
                if ($result->num_rows > 0) {
                    while($row = $result->fetch_assoc()) {
                        echo "<div class='item'>";
                        echo "<a href='http://localhost/as/item-details/item-detail.php? id=" .$row["id"]. "'><img src='" . $row["image1"] . "' alt='" . $row["name"] . "' /></a>";
                        $_SESSION["id"] = $row["id"];
                        echo "<h2>" . $row["name"] . "</h2>";
                        echo "<p>" . $row["description"] . "</p>";
                        echo "<p>Price: $" . $row["price"] . "</p>";
                        echo "</div>";
                    }
                } else {
                    echo "No items found.";
                }
            ?>
        </div>
        <div class="pagination">
            <p>Pages: </p>
            <button class="btn1" onclick="prevPage()"><img src="images/arrow1.jpg"></button>
            <ul>
                <?php
                  echo '<div class="pagination">';
                  
                  for ($i = 1; $i <= $total_pages; $i++) {
                    if ($i == $current_page) {
                      echo '<li class="link active">' . $i . '</li>';
                    } else {
                      echo '<li class="link"><a href="?page=' . $i . '">' . $i . '</a></li>';
                    }
                  }
            
                  echo '</div>';
                  $conn->close();
                ?>
            </ul>
            <button class="btn2" onclick="nextPage()"><img src="images/arrow2.jpg"></button>
        </div>
    </div>

    <script>
    function prevPage() {
        var currentPage = <?php echo $current_page ?>;
        if (currentPage > 1) 
        {
            window.location.href = "?page=" + (currentPage - 1);
        }
    }

    function nextPage() 
    {
        var currentPage = <?php echo $current_page ?>;
        var totalPages = <?php echo $total_pages ?>;
        if (currentPage < totalPages) 
        {
            window.location.href = "?page=" + (currentPage + 1);
        }
    }
    
    function searchItems() {
          var searchInput = document.getElementById("search").value;
          var category = "<?php echo $category ?>";
          window.location.href = "?category=" + category + "&search=" + searchInput;
    }
    </script>
</body>
</html>

here is my item details code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hazelnut</title>
    <link rel="stylesheet" href="style/myStyle.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.css"/>
  </head>
  <body>
      <header>
          <h1>Item Details Page</h1>
      </header>
   <?php
    session_start();
    $conn = new mysqli('localhost', 'root', '', 'chocolate');
    if($conn->connect_error){
        die("connection failed: " . $conn->connect_error);
    }
    
    if(isset($_SESSION['id']) && !empty($_SESSION['id'])) {
        $id = intval($_SESSION['id']);
        $sql = "SELECT * FROM items WHERE id = $id";
        $result = $conn->query($sql);
        // Check if query returned any results
    if ($result->num_rows > 0) {
        // Fetch the data and store it in variables
        $row = $result->fetch_assoc();
        $id = $row["id"];
        $image1 = $row["image1"]; 
        $image2 = $row["image2"];
        $name = $row["name"];
        $description = $row["description"];
        $price = $row["price"];
        $quantity = $row["quantity"];
  ?>
  <main>
  <div class="product-details">
    <div class="product-image">
        <div class="swiper">
            <div class="swiper-wrapper">
                <div class="swiper-slide"><img src="<?php echo $image1; ?>" onclick="showImage(this)"></div>
                <div class="swiper-slide"><img src="<?php echo $image2; ?>" onclick="showImage(this)"></div>
            </div>
            <div class="swiper-pagination"></div>
            <div class="swiper-button-prev"></div>
            <div class="swiper-button-next"></div>
        </div>
    </div>
    <div id="myModal" class="modal">
        <span class="close">&times;</span>
        <img class="modal-content" id="img01">
    </div>
    <div class="product-description">
      <h2 class="product-title"><?php echo $name; ?></h2>
      <p class="product-price"><?php echo "RM " . $price; ?></p>
      <p class="product-info"><?php echo $description; ?></p>
      <form id="myform" method="POST" class="quantity" action="#">
        <label for="quantity">Quantity</label>
        <input type="button" value="-" class="qtyminus minus" field="quantity" />
        <input type="text" name="quantity" value="<?php echo $quantity; ?>" class="qty" />
        <input type="button" value="+" class="qtyplus plus" field="quantity" />
      </form>
      <div class="product-buttons">
        <button class="product-button add-to-cart">Add to Cart</button>
        <button class="product-button add-to-wishlist">Add to Wishlist</button>
      </div>
    </div>
  </div>
</main>
<?php
    } else {
        echo "0 results";
    }
} else {
    echo "No item selected.";
}
$conn->close();
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" charset="utf-8"></script>
<script src="javascript/quantitySelector.js" charset="utf-8"></script>
<script src="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js" charset="utf-8"></script>
<script src="javascript/imageSwiper.js" charset="utf-8"></script>
<script src="javascript/zoom.js" charset="utf-8"></script>
</body>
</html>

here is my sql code:

CREATE TABLE items (
  id INT NOT NULL AUTO_INCREMENT,
  image1 VARCHAR(255) NOT NULL,
  image2 VARCHAR(255) NOT NULL,
  name VARCHAR(255) NOT NULL,
  description TEXT NOT NULL,
  price DOUBLE(10, 2) NOT NULL,
  quantity INT NOT NULL,
  category VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

INSERT INTO items (id, image1, image2, name, description, price, quantity, category) 
VALUES 
(1, 'images/bitter1.jpg',  'images/bitter2.jpg', '70% bitter-sweet dark chocolate', 'Our best-selling dark chocolate ganache expresses the original outstanding flavor of cocoa that is crafted carefully with cacao beans from Europe. It is refined chocolate that highlights a balanced taste with an intense bitter cocoa and pleasant citrus, mild bitterness note that simply melts in your mouth! Perfect for everyone! Indulge the healthier way with our rich, balanced, and smooth bitter-sweet dark chocolates.', 28, 5, 'dark chocolate'), 
(2, 'images/orrange1.jpg',  'images/orrange2.jpg', 'Orange dark chocolate', 'That chocolate with a hint of sunshine brightens up your day with the light, citrus flavour of orange paste mixed with our rich and smooth Belgian dark chocolate giving you a delicious taste experience. Perfect for everyone and fun for kids!', 28, 5, 'dark chocolate'), 
(3, 'images/durian1.jpg',  'images/durian2.jpg', 'Musang King Durian dark chocolate', 'King of all fruits and the best you have ever tasted! It is a piece of confectionery with 100% Pure Musang King Durian flesh blended with our Belgian dark chocolate that will uniquely invade all your five senses. You can even smell the rich fragrant of Durian before you open the box! Sit back, relax and let the flavours blow you away. Perfect for Durian Lovers! A must-try for everyone!.', 28, 5, 'dark chocolate'), 
(4, 'images/capp1.jpg',  'images/capp2.jpg', 'Cappuccino dark chocolate', 'The classic pair of love - the sensual cappuccino blend with our rich and well-bodied Belgian dark chocolate gets you in the love-spiked mood. This is your kind of chocolate to start the day off right and for the night of seduction with just a bite!', 28, 5, 'dark chocolate'), 
(5, 'images/mint1.jpg',  'images/mint2.jpg', 'Mint dark chocolate', 'The classic pair of love - the sensual cappuccino blend with our rich and well-bodied Belgian dark chocolate gets you in the love-spiked mood. This is your kind of chocolate to start the day off right and for the night of seduction with just a bite!', 28, 5, 'dark chocolate'), 
(6, 'images/teh1.jpg',  'images/teh2.jpg', 'Teh tarik milk chocolate', '“Boss! Teh tarik satu!”  A popular Malaysian mamak’s drink - Teh tarik, or so-called pulled Malaysian tea infused in our popular Belgian milk chocolate. You can now enjoy it in a chocolate form with a floral, almost earthy aftertaste.', 28, 5, 'milk chocolate'), 
(7, 'images/salt1.jpg',  'images/salt2.jpg', 'Seasalt caramel milk chocolate', 'A perfectly balanced combination of sweet, creamy caramel with Milk chocolates and seasoned with a pinch of sea salt to excite your taste buds in this delicious and indulgent chocolates. The enormous appeal of this sweet and salty combination is what leads to fireworks on your tongue.', 28, 5, 'milk chocolate'), 
(8, 'images/haze1.jpg',  'images/haze2.jpg', 'Hazelnut milk chocolate', 'This hazelnut milk chocolate is generously blended with Pure hazelnut paste from Italy that gives you a nutty and caramelized goodness in every bite. It is exceptionally creamy and has a melt-in-mouth texture that delivers a unique chocolate experience offering a distinctly smooth, milky and rich, gourmet taste.', 28, 5, 'milk chocolate'), 
(9, 'images/peanut1.jpg',  'images/peanut2.jpg', 'Jobbie peanut butter milk chocolate', 'Everyone loves a nostalgic classic, but whats even better is a classic done right! We have collaborated with famous local peanut butter guru, Jobbie in creating this masterpiece with a modern and healthier take on our First Love Chocolate with Jobbie Peanut Butter!', 28, 5, 'milk chocolate'), 
(10, 'images/sesame1.jpg',  'images/sesame2.jpg', 'Black sesame white chocolate', 'Black Sesame is a common ingredient in various cuisines, especially in Asia Countries. Our Black Sesame Dark Chocolate has a delectable taste with a dry roasted nutty aroma.', 28, 5, 'white chocolate'), 
(11, 'images/soya1.jpg',  'images/soya2.jpg', 'Soya white chocolate', 'Soya may be something commonly found it street drink, but soya chocolate is different. Mixing soya with white chocolate came out with a taste that’s a bit milk-ish, and an endnote with soya aroma that lingers in your mouth and adds a little sweetness to your heart. It is another creative development where our chocolatier pairs traditional household flavour with chocolate to create infinite possibilities of tastes.', 28, 5, 'white chocolate'); 

I have 2 problem that i faced:

  1. When i clicked on different images, it cannot display the correct details for me.
  2. When i use the filter and search function to sort my items, it only display the first page correctly for me, after i click on the next button or click on other pages, it display all items to me again.

I would really appreaciate it if someone could solve my problems faced. Thank you so much!

supabase – How to prevent to not logged users to see vue app pages

I’m starting use supabase as an alternative to firebase. I’m implementing a siple authentication system for my vue webapp, I have a doubt about redirection.
I’ve used the magic link solution to let the user login https://supabase.com/docs/guides/auth/auth-magic-link but I’m not sure how to correctly setup the redirect after login in my localhost during the dev process and hov I can prevent users to see a view if they are not logged in.

I have pinia implemented and vue router, at the moment this is the code I have in my homepage to let users login

import { supabase } from '../supabase/supabase'

export default {
    name: 'HomeView',
    data() {
        return {
            userEmail: null
        }
    },
    created() {
        
    },
    mounted() {
        //this.initGoogleAuth()     
    },
    methods: {
        initMagicLinkAuth() {
            supabase.auth.signInWithOtp({
                email: this.userEmail,
                options: {
                    emailRedirectTo: '/about'
                }
            })
        }
    }
}

in the template I have a simple email input field

                <input type="email" class="form-control" placeholder="Email" v-model="userEmail">
                <div class="d-grid gap-2">
                    <button class="btn btn-primary" @click.prevent="initMagicLinkAuth()">Login</button>
                </div>

and in my router I have this code

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue')
    }
  ]
})

export default router

How I can correctly setup the vue router to prevent navigation if users are not logged in and how I can setup correctly supabase for redirect?

Downloaded wrong blob file in the webview

I have the web page, that renders an array of downloadable pdf files. Something like this:
enter image description here
In the browser I had a URL, that looked like this:

https://www.wmata.com/schedules/maps/upload/2019-System-Map.pdf

And I can easily download this URL.
In the webview I have the following URL after tapping:

blob:https://mydomain/7bc4fe9c-3405-4a86-bde2-944e1f15174d

I read lots of stuff where people recommend using js code to download blob files.
Like this one or here is solution for flutter

So, my js script looks like this:

var xhr = new XMLHttpRequest();
var blobUrl = "blobUrlPlaceholder";
console.log(blobUrl);
xhr.open('GET', blobUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
  if (this.status == 200) {
    var blob = this.response;
    var reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = function() {
      var base64data = reader.result;
      var base64ContentArray = base64data.split(",");
      var mimeType = base64ContentArray[0].match(/[^:s*]w+/[w-+d.]+(?=[;| ])/)[0];
      var decodedFile = base64ContentArray[1];
      console.log(mimeType);
      window.flutter_inappwebview.callHandler('blobToBase64Handler', decodedFile, mimeType);
    };
  };
};
xhr.send();

As a result, I get HTML page with this text:
text

So, my questions are the following:

  1. Can I reflect files on the webview as the web browser does? I mean files with the pdf extension, not as blob ones?
  2. I guess I missed something put into the request in the js code, but how to know what should I additionally add? Why does the browser know it and the webview – does not?

I’ve also tested Chrome custom tabs, which work perfectly, but I must use Webview.
I tried webview_flutter and flutter_inappwebview in the Flutter and native Android webview, but no success. Thanks in advance for any help.

After a deep cloneNode, given a node from the original tree, how can I find the corresponding cloned node?

I am building something of a templating engine. As a form of a caching mechanism, I would like to keep a DocumentFragment node containing the template tree, on which I will call .cloneNode(true), and then perform parameter substitution into the cloned tree. One of the things I need to do is locate substitution points when rendering parameters into a template.

But there is a problem. If I locate substitution points in the original tree, this will be of no use in the cloned tree, because the node identities will be different after cloning. On the other hand, walking the whole cloned tree seems to be wasteful.

I suppose I can compute a list of child element indices for each substitution point, and then use those indices to traverse the cloned tree, but this seems a bit burdensome. Ideally, I’d like to have a WeakMap mapping chosen nodes from the original tree to their cloned counterparts.

Is there a convenient way to locate a cloned counterpart of a node, or do I have to make do with lists of indices?

Update database for checked tuples checkboxes with value from variable

i’m trying to setup a webpage with php and javascript. On this site there is a table which shows the relevant data from postgres database. This table is inside form tags, so i have checkboxes for each row.

Each row has a status like ‘new’, ‘used’, ‘broken’.

The user should choose the rows which he wants to change and for these rows the new status (chosen by user) should be saved in the database.

This works if i set the status manually. Like in the following:

        <div id="refresh-section">
            <form id="chk-input" role="form" method="post">
                <?php
                $object= new Object();
                $object = $object->getObjectProjekt();
                ?>
            </form>
        </div>

Then I have a JS function, which gets the checked checkboxes

        <script>
            var form = document.getElementById('chk-input');

            document.getElementById('button').addEventListener('click', function(e) {
                var fskz = [];

                form.querySelectorAll('input').forEach(function(input) {
                    if (input.type === 'checkbox' && input.checked) {
                        fskz.push(input.value);
                    }
                })
                string_json = JSON.stringify(fskz);
                console.log(fskz);
                $.ajax({
                    method: "post",
                    data: {
                        fskz: JSON.stringify(fskz)
                    }
                })
            }
            )
            
        </script>

This works fine. I get the id for the selected rows as an array. So with the following code the database is updated:

        <?php

        $fskz = json_decode($_POST['fskz'], true);
        $status = "new"; // this status should be chosen by user 

        foreach ($fskz as $fkz) {
            $objectUp = new Object();
            $objectUp->updateObjectStatus($status, $fkz);
        }
        ?>

As I said this works BUT only if I set the status in $status = “new” for example.
I tried to use different buttons, but somehow only the first button works, not the other ones.
I also tried to use a dropdown menu for the status, but this also does not work. In this case you need a second button to save the chosen one from dropdown in the variable status. Then the function sets an empty status.

Do one of you have an idea how to solve this? Thanks a lot! 🙂

ERROR TypeError: Cannot convert undefined value to object

How can i fix this problem with my code I am trying to fetch some user data from an API and display name and profile image etc to the client side but its giving me this error ERROR TypeError: Cannot convert undefined value to object How can I fix this problem?

const User = () => {

    const [userData, setUserData] = useState({});

    useEffect(() => {
        fetchUser();
    }, []);

    const fetchUser = async () => {
        try {
            const userDataString = await AsyncStorage.getItem('user');
            const e = await JSON.parse(userDataString);
            const response = await fetch(`https://10.0.2.2:3000/getuser`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    email: e.user.email,
                }),
            });
            const data = await response.json();
            console.log(data)
            setUserData(data.User)
        } catch (error) {
            console.log(error);
        }
    };

    return (
        <View style={styles.container}>
            {
                userData[0] ? <Text>{userData.username}</Text> : <ActivityIndicator />
            }
        </View>

    )
}

export default User