Vue 3 – Laravel – Inertia Partial reloading not working properly

I have experience with the previous router-view but right now I’m confused. The Problem I’m facing is that all components are updated, the page is not reloading, but everything is being updated.

The structure that I have is next:

Layout :

<script setup>

</script>

<template>
  <h1>This is layout</h1>
  <nav>
    <Link :href="route('home')">Home</Link>
    <Link :href="route('info')">Info</Link>
    <Link :href="route('about')">About</Link>
  </nav>
  <div class="content">
    <Transition name="page" appear>
      <span />
    </Transition>
  </div>
</template>

<style scoped lang="scss">

</style>

MyComponent:

<script setup>
import Layout from "@/layouts/Layout.vue"
</script>

<template>
  <Layout>
    <h1>This is my component</h1>
    <ul>
      <li>
        <Link :href="route('my.route.1')">Menu 1</Link>
        <Link :href="route('my.route.2')">Menu 2</Link>
        <Link :href="route('my.route.3')">Menu 3</Link>
      </li>
    </ul>
    <div class="submenu-content">
      <slot />
    </div>
  </Layout>
</template>

<style scoped lang="scss">

</style>

SubmenuComponent:

<script setup>
import Layout from "@/layouts/MyComponent.vue"
</script>

<template>
  <MyComponent>
    <h1>I'm submenu component and my content is here</h1>
  </MyComponent>
</template>

<style scoped lang="scss">

</style>

MyController.php

public function viewSubComponent(Request $request) {
   $data = [1,2,3,4,5];
   return inertia('SubComponent', ['data' => $data]);
}

enter image description here

The issue that I’m facing is when I click on for example “Home”, a Transition will be added to My component and It will fade in with this sub-menu (1,2,3), but when I click on any of this sub-menu items (1,2,3) I was expecting to update only Submenu Component and not to get transition again for both My component and Submenu Component

Better way to open modal

I have 2 ways to open my Form Modal. I wonder which is a better way? And, with solution one, will value of newStaff be delay 1 stay before the modal shows up? thanks:

 const [newStaff, setNewStaff] = useState(null);
  const [showFormModal, setShowFormModal] = useState(false);
 const handleEditDropdownBtn = row => {
    setNewStaff(row.original);
    setShowFormModal(true);
  };

and this

 const [newStaff, setNewStaff] = useState(null);
  const [showFormModal, setShowFormModal] = useState(false);
 const handleEditDropdownBtn = row => setNewStaff(row.original);
 useEffect(() => {
    staffToDelete
      ? setShowDeleteWarningModal(true)
      : setShowDeleteWarningModal(false);
  }, [newStaff]);

I tried both, first solution sometimes and somehow has newStaff value delays 1 state that when open Modal, it doesn’t appear anything.

How we get polygon [closed]

Hi when I draw a polygon in map which coordinates I need mean latitude and longitude are one or multiple give me example with solutions

How we get polygon coordination in JavaScript in my side I can get this type of lat and long lat=333.55467 and longitude= 72.56544 but this can not give me perfect shape in fetch time I am also fetch these coordination my database to shoe user after save using JavaScript Language

Electron/Vite Cannot find modules after build

im facing a few problems after i built the project.
the error im facing: cannot find module newMessageHandler, axios, crypto
i tried using path.join(__dirname, ‘events/newMessage.js’); but then i get error newMessage/axios/crypto is not a function
full code: https://github.com/DaYroXy/cryptwohale-desktop
of course i did install the dependencies ‘npm i axios crypto etc…’

    const { app, BrowserWindow, ipcMain } = require('electron');
    const path = require('path');
    const newMessageHandler = require('./events/newMessage.js');
    const axios = require('axios')
    const crypto = require('crypto')
    const isDev = !app.isPackaged;

viteConfig

    export default defineConfig({
      plugins: [react()],
      build: {
        outDir: 'dist',
      },
      base: './', // Set base to './'
    });

not really sure how to include events/ to the build as well as the dependencies

How to translate my web site based location as whatsapp.com

I did so simple website and published it. İt is so simple with HTML, CSS, PHP and javascript. I need to change it’s language as whatsapp.com. When visitors come to my page. My website should change to the visitor’s language. Such as: I am now in Turkey. And My language is Turkish when I enter the website (as whatsapp.com ). Web site turns to the Turkish language. But At the same time: The visitors that Amerikan that’s time should be English. How can I do that just use PHP or Javascript? (Also, I am a newbie at this language.)

You can understand it more easily by looking at images:

When I clicked on google search and enter to whatsapp.com:

enter image description here

Or directly enter it: (the language is still turkish)

enter image description here

How to use sass variables with scss files imported through JS?

I’m working on my first “real” project with webpack and I have an issue using sass variables depending on where I use them.

This is part of my folders so you can understand:

new_folder/
├─ assets/
│  ├─ styles/
│  │  ├─ _base.scss
│  │  ├─ _reset.scss
│  │  ├─ _variables.scss
│  │  ├─ styles.scss
├─ index.html
├─ index.js
├─ index.scss

I’m adding my sass variables in _variables.scss while _base.scss contains all the common css for my project (header, footer, components/ui elements)

Then I import everything in styles.scss, using @import because with @use I apparently have some troubles so I will replace it later).

@import 'reset';
@import 'variables';
@import 'fonts';
@import 'icons';
@import 'base';

Then I’m loading styles.scss on all the pages at the beginning, not in the scss file as an import but directly in JS, which is what I learnt on the course I previously followed :

import './assets/styles/styles.scss';
import './index.scss';
import { db } from './assets/javascripts/firebase';

import { doc, collection, getDocs, query, where } from 'firebase/firestore';

const placesArray = [];
const cardsContainerElem = document.querySelector('.cardsContainer');

But i get the error that the variables, when used in index.scss are undefined, while it works when I use them in _base.scss

I guess I could always import directly in the scss file of every page, but I learnt to import through JS, so I’m questioning if there is a reason to do this way

Removing empty values, casting strings to bools and trimming whitespace recursively in JSON with jq – how to optimize?

As part of data preprocessing I need to remove all empty values from an input JSON like empty arrays [], empty objects {}, empty strings ""/" "/"t", objects with empty keys {"":5} and I need to do that recursively. I also need to trim all the whitespaces of all strings (also if they are object keys). I built a solution using jq 1.6 and a custom walk() function. I was wondering if I could improve the performance of my query somehow since I am quite new to advanced jq stuff. Memory is not the problem I would like it to be less CPU intensive (so I do not consider jq stream). Currently I run it through executeScript on a 10 nodes 4 CPU cluster with 16GB RAM each and it is mostly hitting the CPU the hardest. Memory is only at around 60%.

jq 'walk(
  if type == "string" then
    (sub("^[[:space:]]+"; "") | sub("[[:space:]]+$"; "") | if . == "true" then . |= true else . end | if . == "false" then . |= false else . end)
  elif type == "object" then
    with_entries(select(.value | IN("",null, [], {}) | not) | .key |= sub("^[[:space:]]+"; "") | .key |= sub("[[:space:]]+$"; "") |select(.key | IN("") | not ))
  elif type == "array" then
      map(select(. | IN("",null, [], {}) | not))
  else . end)'

That is what I have now. I also cast "true" to boolean true and "false" to boolean false. Are there any obvious query improvements?

I tried doing the whole thing in plain JavaScript or Groovy but I did not feel like reinventing the wheel when recursing nested JSON object is already handled that gracefully by jq. I am open for JavaScript or Groovy implementation if the jq query cannot be improved substantially.

Display random number on Bootstrap popover

I have a bootstrap popover on a button that I would like to display a random number every time its clicked. However my current implementation only displays the first number generated and is not updated on subsequent clicks.

Here’s my code.

  <button type="button" class="btn btn-primary rounded" data-bs-toggle="popover" id="d100">
    Popover Button
  </button>  

<script>
$(document).ready(function() {
  $('#d100').click(function() {
    var popoverContent = generalDice(1,100,0);

    // Show the popover
    $(this).popover({
      content: popoverContent,
      placement: 'top',
      trigger: 'manual'
    }).popover('show');


    // Remove the popover when clicking outside
    $(document).on('click', function(event) {
      if (!$(event.target).closest('#d100').length) {
        $('#d100').popover('hide').popover('destroy');
      }
    });

    // Prevent click event propagation to avoid immediate removal
    return false;
  });
});
</script>

Vite with react – Browser error “Uncaught SyntaxError: ambiguous indirect export: jose”

I’m trying to render an image with JSX but there’s no image shown in the browser. I inspected the page and it returns this error on console “Uncaught SyntaxError: ambiguous indirect export: jose”

Here’s the code:

import { jose } from "../img/react-logo.png";
export function Headerr() {
    return(
        <>
            <div className="redes">
                <img src={jose} alt="" />
            </div>
            <h1>Pizza</h1>
        </>
    )  
}

how to update element of an array of objects, which is inside an object?

how to update element of array of object which is inside an object ? (Note: I tried to create this object when using state varibles usign usestate hook )

I want to how to do it, can anyone explain it?

const [hotelForm, setHotelForm] = useState({
    HotelLocation: "",
    CheckInOn: "",
    CheckOutOn: "",
    
     rooms: [
        {
            roomNo: 1,
            noOfPersons: 2,
            ageOfPerson1: 0,
            ageOfPerson2: 0,
            
        },
     ],
     rooms: props.rooms,
});

Here, I was trying to update the value of element of rooms array, when in form input field value changes, then onChange I wanted update it, and here in this rooms array, other same room objects (objects made using roomNo,noOfPersons,etc.) can be added.
So in that array how can I update the element of that array.
and this all is inside a state variable, so I want to know how to update it. Can anyone explain it please? and if possible I would also like to know how to do it if it was only in JavaScript not in ReactJS

Front and back-end base64 conversion problem

Java&Vue Project.When I take a picture of a face with the camera on the front end and send it to the back end, the back end converts the base64 to a file but cannot open it

frontend: canvas.toDataURL('image/png').split(',')[1].replace(/+/g, '%2B');
backend:imgStr.replace(" ", "").replace("data:image/png;base64,", "").replaceAll("%2b", "+");

Remix session values don’t persist across pages

I’m making a site using Remix where I’d like to persist session values across pages. I have implemented a session cookie in sessions.ts:

const { getSession, commitSession, destroySession } =
    createCookieSessionStorage<SessionData, SessionFlashData>(
        {
            //cookie options to create a cookie
            cookie: {
                name: "__session",
                maxAge: 1200,
                path: "/",
                sameSite: "none",
                secure: true,
                secrets: ["surprise"]

            },
        }
    );

On one page I set a value and log it out and receive the expected value

export const loader = async ({ request }: LoaderArgs) => {
    const session = await getSession(
        request.headers.get("Cookie")
    );
    session.set("token", "abc123")
    var data = { "count": 2 }
    console.log(session.get("token"))
    return json(data, {
        headers: {
            "Set-Cookie": await commitSession(session),
        },
    });
};

however when i try to access the value in a different page, the value is undefined

export const loader = async ({ request }: LoaderArgs) => {
  const session = await getSession(
    request.headers.get("Cookie")
  );
  var data = { "abc": 442 }
  console.log(session.get("token"))
  return json(data, {
    headers: {
      "Set-Cookie": await commitSession(session),
    },
  });

  return null


};

I’m very new to remix and react so appreciate any help!

Javascript arrays: Can you have both keys and values?

I used an ethers.providers.getLogs() function on an arbitrary transaction in javascript. I got the following result as one of the parameters.

There seems to be key-pair values in this array (denoted by the brackets []), which doesn’t make sense. This makes me think this as an object. But that can’t be the case as well because there are singular keys without pairs.

Can someone explain what’s going on here?

[
  '0xd2ab1089822171b728a5694b79acf292f6b59ff8c548d2a2e71f6c5ff7025f0f',
  '0xcd63cB2374e49f88083d79D5f7891be5734cdc68',
  '0x0000000000000000000000000000000000000000',
  BigNumber { _hex: '0x38', _isBigNumber: true },
  true,
  BigNumber { _hex: '0xc817c38c6ddc', _isBigNumber: true },
  BigNumber { _hex: '0x023c74', _isBigNumber: true },
  userOpHash: '0xd2ab1089822171b728a5694b79acf292f6b59ff8c548d2a2e71f6c5ff7025f0f',
  sender: '0xcd63cB2374e49f88083d79D5f7891be5734cdc68',
  paymaster: '0x0000000000000000000000000000000000000000',
  nonce: BigNumber { _hex: '0x38', _isBigNumber: true },
  success: true,
  actualGasCost: BigNumber { _hex: '0xc817c38c6ddc', _isBigNumber: true },
  actualGasUsed: BigNumber { _hex: '0x023c74', _isBigNumber: true }
]

Add tooltip to data points for each layer using open layer map library typescript

I have a map in my angular app, generated through open layers library. I also have two layers, which show different data points. I can toggle them on and off depending on which ones i want to show in my html.

The map is showing perfectly and so are the data points for each layer. However, I am trying to add tooltips to my data points, so if they are hovered over with the mouse (while that particular layer is toggled on), a tooltip will appear showing the data point name.

Can anyone help me out with how i can add tooltips to this, because what i have added so far doesn’t seem to be working?

Here is my code so far for my component.ts file:

import { Component, OnInit } from "@angular/core";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import OSM from "ol/source/OSM";
import { Feature } from "ol";
import { Point } from "ol/geom";
import { fromLonLat } from "ol/proj";
import VectorSource from "ol/source/Vector";
import { Style, Icon, Circle, Fill, Stroke } from "ol/style";
import Overlay from "ol/Overlay";

@Component({
  selector: "map",
  templateUrl: "./map.component.html",
  styleUrls: ["./map.component.scss"],
})
export class MapComponent implements OnInit {
  map: Map;
  loading: any;
  showLayer1: boolean = true;
  showLayer2: boolean = true;
  layer1: VectorLayer<VectorSource<Point>>;
  layer2: VectorLayer<VectorSource<Point>>;
  tooltipOverlay: Overlay;

  constructor() {}

  ngOnInit() {
    this.loading = true;

    setTimeout(() => {
      // Create the map and add the OSM layer
      this.map = new Map({
        layers: [
          new TileLayer({
            source: new OSM(),
          }),
        ],
        target: "map",
      });
      const view = new View({
        center: fromLonLat([-1.1432, 52.9548]), // Set the center coordinates
        zoom: 7, // Adjust the zoom level as needed
      });
      this.map.setView(view);

      // Create the tooltip overlay and add it to the map
      this.tooltipOverlay = new Overlay({
        element: document.getElementById("tooltip"),
        autoPan: true,
      });
      this.map.addOverlay(this.tooltipOverlay);

      // Create the vector source for layer 1
      var layer1Source = new VectorSource<Point>({
        features: [],
      });

      // Create the vector layer for layer 1 with the vector source
      this.layer1 = new VectorLayer<VectorSource<Point>>({
        source: layer1Source,
        style: new Style({
          image: new Icon({
            src: "../../../assets/images/icons/ie.png",
            imgSize: [24, 24],
            crossOrigin: "anonymous",
          }),
        }),
      });

      // Create the vector source for layer 2
      var layer2Source = new VectorSource<Point>({
        features: [],
      });

      // Create the vector layer for layer 2 with the vector source
      this.layer2 = new VectorLayer<VectorSource<Point>>({
        source: layer2Source,
        style: new Style({
          image: new Circle({
            radius: 8,
            fill: new Fill({ color: "blue" }),
            stroke: new Stroke({
              color: "white",
              width: 2,
            }),
          }),
        }),
      });

      // Add the vector layers to the map initially
      this.map.addLayer(this.layer1);
      this.map.addLayer(this.layer2);

      // Add markers for each school to layer 1
      var shops1 = [
        {
          name: "shop1",
          longitude: -3.892366,
          latitude: 53.409634,
        },
        {
          name: "shop2",
          longitude: -0.147421,
          latitude: 51.495373,
        },
      ];
      shops1.forEach((shop) => {
        var marker = new Feature({
          geometry: new Point(fromLonLat([shop.longitude, shop.latitude])),
          name: shop.name,
        });
        layer1Source.addFeature(marker);
      });

      // Add markers for each shop to layer 2
      var shops2 = [
        {
          name: "shop2",
          longitude: -2.954443,
          latitude: 53.402111,
        },
        {
          name: "shop2",
          longitude: -0.747971,
          latitude: 51.314344,
        },
        // Add more shops for layer 2 as needed
      ];
      shops2.forEach((shop) => {
        var marker = new Feature({
          geometry: new Point(fromLonLat([shop.longitude, shop.latitude])),
          name: shop.name,
        });
        layer2Source.addFeature(marker);
      });

      this.loading = false;
    }, 1000);
  }

  toggleLayer1() {
    if (this.showLayer1) {
      this.map.addLayer(this.layer1);
    } else {
      this.map.removeLayer(this.layer1);
    }
  }

  toggleLayer2() {
    if (this.showLayer2) {
      this.map.addLayer(this.layer2);
    } else {
      this.map.removeLayer(this.layer2);
    }
  }

  showTooltip(event) {
    const feature = this.map.forEachFeatureAtPixel(
      event.pixel,
      (feature) => feature
    );
    if (feature) {
      const geometry = feature.getGeometry();
      if (geometry instanceof Point) {
        const coordinates = geometry.getCoordinates();
        this.tooltipOverlay.setPosition(coordinates);
        const tooltipElement = this.tooltipOverlay.getElement();
        tooltipElement.innerHTML = feature.get("name"); // Use any property of the feature to display in the tooltip
        tooltipElement.style.display = "block";
      }
    } else {
      this.hideTooltip();
    }
  }

  hideTooltip() {
    const tooltipElement = this.tooltipOverlay.getElement();
    tooltipElement.style.display = "none";
  }
}

Here is my html code:

<div class="app-content content">
  <div class="content-wrapper">
    <div class="row p-1 mt-5">
      <div class="content-header"></div>
    </div>
    <div class="content-body" style="padding-top: 0px !important;">
      <div class="row">
        <div class="col">
          <div>
            <input
              type="checkbox"
              [(ngModel)]="showLayer1"
              (change)="toggleLayer1()"
            />
            Layer 1
          </div>
        </div>
        <div class="col">
          <div class="map-container">
            <div id="map" class="map"></div>
            <div id="tooltip" class="tooltip"></div>
          </div>
        </div>
        <div class="col">
          <div>
            <input
              type="checkbox"
              [(ngModel)]="showLayer2"
              (change)="toggleLayer2()"
            />
            Layer 2
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Here is my scss code:

.map-container {
  width: 500px;
  height: 500px;
}

.map {
  width: 100%;
  height: 100%;
}

.tooltip {
  position: absolute;
  display: none;
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 5px;
  font-size: 12px;
  pointer-events: none;
  z-index: 9999;
}