Proving that LocalStorage Persists after tab close

I’ve read from internet – that “LocalStorage” data for a tab (persists) and has no expirty date – even after the tab or window is closed.

Case_I: say I go to the website => https://www.hondacarindia.com/

I can see the data in localstorage (Application tab):

enter image description here

I can also run the command to console the data of localstorage:

console.log(localstorage);

enter image description here

yes I can see the same items (8 items here);

Query:

Now if I close the window or tab => I can no longer, have access to (application tab), (console tab); —> Now is there anyway to know that those 8 items are still there in memory, as tab is gone;

Also:

If I again open website https://www.hondacarindia.com/ (It might be that — website stores those 8 items again to the new tab) —> which is 2nd time. There is no way to know that —> the localStorage data (of 8 items persisted). So, I want to confirm —> that the 8 items persisted and (they are the old ones, not again in new tab —> as I browsed the site, added again to my (Application tab).

Can someone help me out, how to confirm that localStorage -> 8 items persisted (when I closed the tab), just proving it?

expo-router not sending props when pushing screen

i need some help with this issue.

I’m tring to read navigation props in pokemon screen when pushing from index but I’m only getting {“segment”: “pokemon”}.

This is from my index.js file.

return (
    <SafeAreaView>
      <Link href={"/pokemon"}>
        <Text>Go to pokemon 1</Text>
      </Link>
      {/* <PokemonList
        pokemons={pokemons}
        loadPokemons={loadPokemons}
        isNextUrl={nextUrl}
      /> */}
    </SafeAreaView>
  );

And this is how I’m reading props received by pokemon.js.

export default function pokemon(props) {
  console.log(props);

  return (
    <View>
      <Text>pokemon</Text>
    </View>
  );
}

It’s suposed that I need some props like this:
props from react navigation

I tried to use

navigation.navigate() from @react-navigation/native;

Also using

router.push() from expo-router 

and

<Link>
    <Text>Go to pokemon page</Text>
</Link>

component from expo-router but anyway I’m getting the same result.

Maybe I’m not reading the props in a propper way. Could you help me?

Trying to add records in RAG vector database Pinecone

Hello All I am trying creating a RAG chatbot, that does a POST request when user clicks add. The purpose of the add, is to add the record in the RAG vector database. I can’t seem to format the data properly to do, I was able to achieve something similar using python notebook.

Json Format:

{
  "restaurant": [
    {
      "restaurant": "Bella Italia",
      "cuisine": "Italian",
      "rating": 5,
      "review": "Amazing pasta and great ambiance! Highly recommended."
    },
    {
      "restaurant": "Sushi Sakura",
      "cuisine": "Japanese",
      "rating": 4,
      "review": "Fresh sushi and friendly staff. A bit pricey but worth it."
    }
  ]
}

My app/api/add/route.js code is below:

import { Pinecone } from '@pinecone-database/pinecone';
import { OpenAI } from 'openai';
import dotenv from 'dotenv';

dotenv.config();

// Initialize OpenAI and Pinecone clients with API keys
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const pc = new Pinecone({ apiKey: process.env.PINECONE_API_KEY });
const index = pc.index('rag'); // Use the correct index name

// Function to handle user input
async function handleUserInput(userInput) {
    let records = [];

    // Check if input is an array or an object
    if (Array.isArray(userInput.restaurant)) {
        records = userInput.restaurant;
    } else {
        console.error('Invalid input format:', userInput);
        return [];
    }

    const processedData = [];

    for (const record of records) {
        console.log('Processing record:', record);

        // Ensure fields are properly mapped
        const mappedRecord = {
            restaurant: record.restaurant,
            review: record.review,
            cuisine: record.cuisine,
            rating: record.rating,
        };

        if (!mappedRecord.restaurant || !mappedRecord.review || !mappedRecord.cuisine || typeof mappedRecord.rating !== 'number') {
            console.error('Invalid record data:', mappedRecord);
            continue;
        }

        try {
            const response = await openai.embeddings.create({
                input: mappedRecord.review,
                model: 'text-embedding-3-small', // Ensure this model is available
            });

            const embedding = response.data?.[0]?.embedding;

            if (!Array.isArray(embedding)) {
                throw new Error('Embedding is not an array');
            }

            processedData.push({
                id: mappedRecord.restaurant, // Use 'restaurant' field for id
                values: embedding, // Embedding should be an array
                metadata: {
                    review: mappedRecord.review,
                    cuisine: mappedRecord.cuisine,
                    rating: mappedRecord.rating,
                },
            });
        } catch (error) {
            console.error('Error creating embedding:', error.message);
        }
    }

    return processedData;
}

// Function to upsert data into Pinecone
async function upsertData(processedData) {
    try {
        // Ensure processedData is in the correct format
        const formattedData = processedData.map(record => ({
            id: record.id,
            values: record.values,
            metadata: record.metadata,
        }));

        // Perform upsert operation
        const upsertResponse = await index.upsert({
            vectors: formattedData,
            namespace: 'ns1', // Replace with your namespace if needed
        });

        console.log(`Upserted count: ${upsertResponse.upserted_count}`);
    } catch (error) {
        console.error('Error upserting data into Pinecone:', error.message);
        throw new Error('Failed to upsert data');
    }
}

// Function to print index statistics
async function printIndexStats() {
    try {
        const stats = await index.describeIndexStats();
        console.log('Index statistics:', stats);
    } catch (error) {
        console.error('Error describing index stats:', error.message);
    }
}

// POST request handler
export async function POST(req) {
    if (req.method !== 'POST') {
        return new Response(JSON.stringify({ error: 'Method not allowed' }), { status: 405 });
    }

    try {
        const body = await req.json();
        console.log('Received request body:', JSON.stringify(body, null, 2)); // Pretty print

        const processedData = await handleUserInput(body);

        if (processedData.length > 0) {
            await upsertData(processedData);
        } else {
            console.log('No valid data to upsert');
        }

        await printIndexStats();

        return new Response(JSON.stringify({ message: 'Successfully added to lunch box' }), { status: 200 });
    } catch (error) {
        console.error('Error adding restaurant:', error.message);
        return new Response(JSON.stringify({ error: error.message || 'Internal Server Error' }), { status: 500 });
    }
}

Similar Implementation done here:

from dotenv import load_dotenv
load_dotenv()
from pinecone import Pinecone, ServerlessSpec
from openai import OpenAI
import os
import json

# Initialize Pinecone
pinecone = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))

# Create a Pinecone index
pinecone.create_index(
    name="rag",
    dimension=1536,
    metric="cosine",
    spec=ServerlessSpec(cloud="aws", region="us-east-1"),
)

# Load the review data
with open("reviews.json") as file:
    data = json.load(file)

# Initialize OpenAI client
client = OpenAI()

processed_data = []

# Create embeddings for each review
for review in data["restaurant"]:
    response = client.embeddings.create(
        input=review['review'], model="text-embedding-3-small"
    )
    embedding = response.data[0].embedding
    processed_data.append(
        {
            "values": embedding,
            "id": review["restaurant"],
            "metadata": {
                "review": review["review"],
                "cuisine": review["cuisine"],
                "rating": review["rating"],
            }
        }
    )

# Insert the embeddings into the Pinecone index
index = pinecone.Index("rag")
upsert_response = index.upsert(
    vectors=processed_data,
    namespace="ns1"
)

print("Upsert response:", upsert_response)

# Print index statistics
index_stats = index.describe_index_stats()
print(index_stats)

Basically I am trying to achieve what I have done in python, through javascript.

My error are below:

○ Compiling /api/add ...
 ✓ Compiled /api/add in 1273ms (1168 modules)
Failed to find any user-provided fetch implementation. Using global fetch implementation.
Failed to find any user-provided fetch implementation. Using global fetch implementation.
Received request body: {
  "restaurant": {
    "name": "Popeyes Louisiana Kitchen",
    "rating": 4.6,
    "cuisine": "Fast-food",
    "review": "This is not the first time, last visit the food was clearly refried to be warmed up. This time, all the wraps are dripping with half a bottle of sause in each wrap. Inedible food. I would like my money back. My dog is served better food."
  }
}
Invalid input format: {
  restaurant: {
    name: 'Popeyes Louisiana Kitchen',
    rating: 4.6,
    cuisine: 'Fast-food',
    review: 'This is not the first time, last visit the food was clearly refried to be warmed up. This time, all the wraps are dripping with half a bottle of sause in each wrap. Inedible food. I would like my money back. My dog is served better food.'
  }
}
No valid data to upsert
Failed to find any user-provided fetch implementation. Using global fetch implementation.
Failed to find any user-provided fetch implementation. Using global fetch implementation.
Index statistics: {
  namespaces: { ns1: { recordCount: 20 } },
  dimension: 1536,
  indexFullness: 0,
  totalRecordCount: 20
}
 POST /api/add 200 in 2870ms

ReferenceError: can’t access lexical declaration ‘__WEBPACK_DEFAULT_EXPORT__’ before initialization

I am deveoping an web app which used ReactJS as FE and redux for state management.

I am facing an issue when I import slice into one of my folder it gives an error.

The error is:

ReferenceError: can't access lexical declaration '__WEBPACK_DEFAULT_EXPORT__' before initialization

The file where I am importing the error is:
layoutsdashboardindex.js

My project structure is (SRC folder structure below):

|   App.js
|   config.js
|   index.js
|   output.txt
|   reportWebVitals.js
|   socket.js
|   
+---assets
|   +---Illustration
|   |       NoChat.js
|   |       
|   ---Images
|     
|                    
+---components
|   |  
|   +---animate
|   |          
|   +---Contact
|   |          
|   +---Conversation
|   |         
|   +---dashobard
|   |           
|   +---hook-form
|   |      
|   +---Image
|   |
|   |       
|   +---Search
|   |
|   +---settings
|   |   |       
|   +---upload
|   |   |   index.js
|   |   |   UploadAvatar.js
|   |   |   
|   |   ---preview
|   |           AvatarPreview.js
|   |           
|   ---utils
|           index.js
|           
+---contexts
|       SettingsContext.js
|       
+---data
|       index.js
|       
+---hooks
|       useLocales.js
|       useLocalStorage.js
|       useResponsive.js
|       useSettings.js
|       
+---layouts
|   +---auth
|   |       index.js
|   |       
|   +---dashboard
|   |       index.js
|   |       SideBar.js
|   |       utils.js
|   |       
|   ---main
|           index.js
|           
+---pages
|   |   Page404.js
|   |   
|   +---auth
|   |
|   +---dashboard
|   |
|   |       
|   ---utils
|           index.js
|           
+---redux
|   |   rootReducer.js
|   |   store.js
|   |   
|   ---slices
|           app.js
|           auth.js
|           
+---routes
|       index.js
|       paths.js
|       
+---sections
|   +---auth
|   |       AuthSocial.js
|   |       LoginForm.js
|   |       NewPasswordForm.js
|   |       RegisterForm.js
|   |       ResetPasswordForm.js
|   |       VerifyForm.js
|   |       
|   ---main
+---theme
|   files related to theme
|           
---utils        

CLIENTsrclayoutsdashboardindex.js

code snippets are slice/app.js:

import { createSlice } from "@reduxjs/toolkit";
import { dispatch } from "../store";
import axios from "axios";

const initalState = {
  snackbar: {
    open: null,
    severity: null,
    message: null,
  }
};


const appSlice = createSlice({
  name: "app",
  initialState: initalState,
  reducers: {
    closeSnackBar(state, action) {
      state.snackbar.open = false;
      state.snackbar.message = null;
      state.snackbar.severity = null;
    },
    openSnackBar(state, action) {
      state.snackbar.open = true;
      state.snackbar.severity = action.payload.severity;
      state.snackbar.message = action.payload.message;
    }
  }
});

export const showSnackbar =
  ({ severity, message }) =>
  async (dispatch, getState) => {
    dispatch(
      appSlice.actions.openSnackBar({
        message,
        severity,
      })
    );

export default appSlice.reducer;

rootReducer.js

import { combineReducers } from "redux";
import storage from "redux-persist/lib/storage";
import appReducer from "./slices/app";
import authReducer from "./slices/auth";

// Slice reducers 

const rootPeristConfig = {
  key: "root",
  storage,
  keyPrefix: "redux-"
}

const rootReducer = combineReducers({
  auth: authReducer,
  app: appReducer,
});


export {
  rootReducer,
  rootPeristConfig,
}

I am trying to import showSnackBar in layoutsdashboardindex.js file:
whose code snippet is:

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Box, Stack } from "@mui/material";
import { Navigate, Outlet } from "react-router-dom";
import { useTheme } from "@mui/material/styles";

import SideBar from "./SideBar";
import { connectSocket, socket } from "../../socket";
import { showSnackbar } from "../../redux/slices/app";  // (Throws error)

I am looking for possible solutions and debug methods how can I solve my errors.

How can the count of product add/remove can be independent for each product?

When the add/remove button is clicked it increases/decreases count of the product but that count value stays for other products too.

how to make the count independent for each product? so that when the product is added it shows its count only and other products to have their individual count

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="header margin-bottom">
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="#">Full Web Projects</a></li>
        <li class="dropdown">
          <a href="javascript:void(0)" class="dropbtn">Small Projects</a>
          <div class="dropdown-content">
            <a href="cart.html">cart</a>
            <a href="counter.html">Counter</a>
            <a href="products.html">Products</a>
            <a href="#">Link 3</a>
          </div>
        </li>
      </ul>
    </div>
    <div class="page">
      <h2>Product Page</h2>
      <p id="message"></p>
      <div class="products container">
        <div class="product">
          <figure id="caption">
            <img src="images/flower.png" alt="Flowers" />
            <figcaption id="flower-caption">Beautiful Flower</figcaption>
          </figure>
          <div class="productButtons">
            <button type="button" class="addProduct">Add To Cart</button>
            <button type="button" class="removeProduct">
              Remove From Cart
            </button>
          </div>
        </div>

        <div class="product">
          <figure id="caption">
            <img src="images/parrot.png" alt="Flowers" />
            <figcaption id="parrot-caption">Parrot</figcaption>
          </figure>
          <div class="productButtons">
            <button type="button" class="addProduct">Add To Cart</button>
            <button type="button" class="removeProduct">
              Remove From Cart
            </button>
          </div>
        </div>

        <div class="product">
          <figure id="caption">
            <img src="images/penguin.png" alt="penguin" />
            <figcaption id="penguin-caption">Penguin</figcaption>
          </figure>
          <div class="productButtons">
            <button type="button" class="addProduct">Add To Cart</button>
            <button type="button" class="removeProduct">
              Remove From Cart
            </button>
          </div>
        </div>

        <div class="product">
          <figure id="caption">
            <img src="images/be-nice.png" alt="be-nice" />
            <figcaption id="be-nice-caption">Be Nice</figcaption>
          </figure>
          <div class="productButtons">
            <button type="button" class="addProduct">Add To Cart</button>
            <button type="button" class="removeProduct">
              Remove From Cart
            </button>
          </div>
        </div>

        <div class="product">
          <figure id="caption">
            <img src="images/painting-1.png" alt="Painting-1" />
            <figcaption id="painting-1-caption">Painting-1</figcaption>
          </figure>
          <div class="productButtons">
            <button type="button" class="addProduct">Add To Cart</button>
            <button type="button" class="removeProduct">
              Remove From Cart
            </button>
          </div>
        </div>

        <div class="product">
          <figure id="caption">
            <img src="images/painting-2.png" alt="Painting-2" />
            <figcaption id="painting-2-caption">Painting-2</figcaption>
          </figure>
          <div class="productButtons">
            <button type="button" class="addProduct">Add To Cart</button>
            <button type="button" class="removeProduct">
              Remove From Cart
            </button>
          </div>
        </div>

        <div class="product">
          <figure id="caption">
            <img src="images/painting-3.png" alt="Painting-3" />
            <figcaption id="painting-3-caption">Painting-3</figcaption>
          </figure>
          <div class="productButtons">
            <button type="button" class="addProduct">Add To Cart</button>
            <button type="button" class="removeProduct">
              Remove From Cart
            </button>
          </div>
        </div>

        <div class="product">
          <figure id="caption">
            <img src="images/painting-4.png" alt="Painting-4" />
            <figcaption id="painting-4-caption">Painting-4</figcaption>
          </figure>
          <div class="productButtons">
            <button type="button" class="addProduct">Add To Cart</button>
            <button type="button" class="removeProduct">
              Remove From Cart
            </button>
          </div>
        </div>
      </div>
    </div>

    <script src="product.js"></script>
  </body>
</html>

let count = 0;
document.querySelectorAll(".addProduct").forEach((btn) => {
  btn.addEventListener("click", () => {
    const productElement = btn.closest(".product");
    const proName = productElement.querySelector("figcaption").textContent;
    count++;
    if (count <= 10) {
      document.getElementById(
        "message"
      ).textContent = ` ${count} ${proName} Added.`;
    } else {
      count = 10;
      document.getElementById("message").textContent = ` Maximum limit reached`;
    }
  });
});

document.querySelectorAll(".removeProduct").forEach((btn) => {
  btn.addEventListener("click", () => {
    const productElement = btn.closest(".product");
    const proName = productElement.querySelector("figcaption").textContent;
    count--;
    if (count >= 0) {
      document.getElementById(
        "message"
      ).textContent = ` ${count}  ${proName} Remaining.`;
    } else {
      count = 0;
      document.getElementById("message").textContent = ` Minimum limit reached`;
    }
  });
});

I Tried to create a count variable that stores the value of the product count added and removed.

Jquery stick element image replacement

enter image description here

Trying to create these kind of screen transitions – a sticky image, that then gets replaced with a similar version but on a different theme colour.

What scroll formula/value is being used to control the height of the white-holder element so that it replaces the dark mode with the light.

I’ve tried to increase the height of the container to test this component.

  $( document ).ready(function() {

    console.log("ready")
var myElement = $(".white-mode-holder");

function setHeight(yPos, el) {
  el.style.height = `${yPos}vh`;
}

$(document).scroll(function(e){
  
  console.log("e", e)
  
  let h = $("body").offset().top;
  console.log("h", h)
  
  setHeight(h*2, myElement[0])
  
});


  });
html {
    -ms-text-size-adjust: 100%;
    -webkit-text-size-adjust: 100%;
    font-family: sans-serif;
}
body {
    color: #fff;
    background-color: #000;
    font-family: Manrope, sans-serif;
    font-size: 14px;
    line-height: 1.2;
}

.container {
    max-width: 1170px;
    margin-left: auto;
    margin-right: auto;
    padding: 2em;
    height: 2000px;
}

img {
    overflow-clip-margin: content-box;
    overflow: clip;
}

* {
    box-sizing: border-box;
}

img {
    border: 0;
}


img {
    max-width: 100%;
    vertical-align: middle;
    display: inline-block;
}



.dark-and-light-mode-container {
    width: 100%;
    height: 100vh;
    position: -webkit-sticky;
    position: sticky;
    top: 0;
}

.dark-and-light-mode-sticky {
    width: 100%;
    height: 100vh;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    display: flex;
    position: relative;
}

.dark-mode-holder {
    z-index: 1;
    width: 100%;
    height: 100vh;
    background-color: #000;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    display: flex;
    position: relative;
    overflow: hidden;
}

.white-mode-holder {
    z-index: 1;
    width: 100%;
    height: 50vh;
    background-color: #fff;
    flex-direction: column;
    justify-content: flex-end;
    align-items: center;
    display: flex;
    position: absolute;
    top: auto;
    bottom: 0%;
    left: 0%;
    right: 0%;
    overflow: hidden;
}


.white-mode-holder{
    will-change: width, height;
    height: 0vh;
}


.center-iphone {
    width: 100vw;
    height: 100vh;
    min-height: 100vh;
    min-width: 100vw;
    text-align: center;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    display: flex;
    position: relative;
}



.dark-mode-hand-holder {
    z-index: 1;
    width: 400px;
    max-width: 400px;
    min-width: 400px;
    justify-content: center;
    align-items: center;
    margin: 80px 0 0;
    display: flex;
    position: relative;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}



.dark-mode-hand {
    z-index: 1;
    width: 400px;
    position: relative;
}


.dark-mode-app {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 20px;
}



.dark-mode-app-holder {
    padding: 2.6% 26% 26.2% 16%;
    position: absolute;
    top: 0%;
    bottom: 0%;
    left: 0%;
    right: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>


<div class="container">

  <div class="dark-and-light-mode-container">
    <div class="dark-and-light-mode-sticky">
      <div class="dark-mode-holder">
        <div class="center-iphone">
          <div class="dark-mode-hand-holder"><img src="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b5761b8fb633b42f3ad6c4_Iphone%20In%20Hand.webp" loading="eager" sizes="(max-width: 479px) 300px, 400px" srcset="https://assets.website-files.com/63aee5793ca698452efe7f60/63b5761b8fb633b42f3ad6c4_Iphone%20In%20Hand-p-500.webp 500w, https://assets.website-files.com/63aee5793ca698452efe7f60/63b5761b8fb633b42f3ad6c4_Iphone%20In%20Hand-p-800.webp 800w, https://assets.website-files.com/63aee5793ca698452efe7f60/63b5761b8fb633b42f3ad6c4_Iphone%20In%20Hand.webp 848w" alt="" class="dark-mode-hand">
            <div class="dark-mode-app-holder"><img src="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b576894fd22717696b9ead_Dark%20Mode.webp" loading="eager" alt="" sizes="232px" srcset="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b576894fd22717696b9ead_Dark%20Mode-p-500.webp 500w, https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b576894fd22717696b9ead_Dark%20Mode-p-800.webp 800w, https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b576894fd22717696b9ead_Dark%20Mode.webp 1035w" class="dark-mode-app"></div>
          </div>
        </div>
      </div>
      <div class="white-mode-holder" style="will-change: width, height; height: 0vh;">
        <div class="center-iphone">
          <div class="dark-mode-hand-holder"><img src="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b5761b8fb633b42f3ad6c4_Iphone%20In%20Hand.webp" loading="eager" sizes="(max-width: 479px) 300px, 400px" srcset="https://assets.website-files.com/63aee5793ca698452efe7f60/63b5761b8fb633b42f3ad6c4_Iphone%20In%20Hand-p-500.webp 500w, https://assets.website-files.com/63aee5793ca698452efe7f60/63b5761b8fb633b42f3ad6c4_Iphone%20In%20Hand-p-800.webp 800w, https://assets.website-files.com/63aee5793ca698452efe7f60/63b5761b8fb633b42f3ad6c4_Iphone%20In%20Hand.webp 848w" alt="" class="dark-mode-hand">
            <div class="dark-mode-app-holder"><img src="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b57689b7dd5c5baa9e0780_Light%20Mode.webp" loading="eager" alt="" sizes="232px" srcset="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b57689b7dd5c5baa9e0780_Light%20Mode-p-500.webp 500w, https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b57689b7dd5c5baa9e0780_Light%20Mode-p-800.webp 800w, https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63b57689b7dd5c5baa9e0780_Light%20Mode.webp 1036w" class="dark-mode-app"></div>
          </div>
        </div>
      </div>
    </div>
  </div>


</div>

Zebra ZQ620 can not find service from Chrome bluetooth

I want to connection ZQ620(this is verification machine) and print, use bluetooth from Android Chrome browser JavaScript (pure or jQuery) only.

Find device is ok but service is not find error occurred.

My source is this.

const DEVICE_UUID = '0000fe79-0000-1000-8000-00805f9b34fb';
const SERVICE_UUID = '38eb4a84-c570-11e3-9507-0002a5d5c51b';
var printer = null;
var printRes = null;
function sendText(s) {
    let encoder = new TextEncoder("utf-8");
    let txt     = encoder.encode(s+ 'u000Au000Du000Au000Du000Au000Du000Au000Du000Au000D');
    return printer.writeValue(txt);
}
function fnc(eve){
    navigator.bluetooth.requestDevice({
        filters: [{
            namePrefix: 'X',
        }],
        optionalServices: [SERVICE_UUID]
    })
    .then(device => {
        console.log('connect device start');
        return device.gatt.connect();
    })
    .then(server => {
        console.log('start primary servicies');
        //return server.getPrimaryService(SERVICE_UUID);
        return server.getPrimaryServices();  //throw error
    })
    .then(services => {
        console.log(services);
    })/*
    .then(service => {
        console.log('start characteristic');
        return service.getCharacteristic(SERVICE_UUID);
    })
    .then(characteristic => {
        printer = characteristic;
        printRes = sendText($("#_textarea").val());
    })*/
    .catch(error => {
        console.err('error occurred', error);
    })
}

But, error occurrd. Throws error is ‘NotFoundError: No Services found in device.’ from ‘return server.getPrimaryServices();’
nRF Connect app said service is exist, but can not access(screeenshot).

enter image description here

So, how connect and print? This printer not supported? Can I use it on other devices?
I’m sorry if my English is strange.

Form elements not working on a div overlapping a bootstrap modal

I am trying to overlap div on a bootstrap modal using only css and javascript but the form elements are not even clickable so I cannot change their values except for the select.

bootstrap modal

<button type="button" data-bs-toggle="modal" data-bs-target="#sampleModal" id="sampleModalBtn">show modal</button>
<div class="modal fade" id="sampleModal" tabindex="-1" role="dialog" aria-labelledby="sampleModalLabel" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold"><span class="pe-2">Sample Modal</span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <button type="button" onclick="document.getElementById('overlapDivCon1').style.visibility = 'visible'">overlap div1</button>
                <button type="button">overlap div2</button>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-md" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

overlapping div

<div class="d-flex justify-content-center overlapDivContainer" id="overlapDivCon1">
    <div class="border border-secondary bg-white rounded-3 shadow overlapDiv">
        <div class="p-2 border-bottom">
            <form>
                <a href="https://www.google.com" target="blank">check google</a>
                <input type="text" class="form-control form-control-sm mb-2" placeholder="type text here">
                <input type="number" class="form-control form-control-sm mb-2" placeholder="type number here">
                <input type="date" class="form-control form-control-sm mb-2">
                <select class="form-select form-select-sm mb-2">
                    <option value="1">1</option>
                    <option value="2">2</option>
                </select>
                <textarea></textarea>
            </form>
        </div>
    </div>
</div>

css

.overlapDivContainer {
  background-color: rgba(0,0,0,.6);
  width: 100%;
  height: 100%;
  position: fixed;
  z-index: 1056;
  visibility: hidden;
}
.overlapDiv {
  width: 60%;
  margin-top: 2%;
}

CORS error in Mongo DB Atlas Data API call via Client side JS

I am trying to make an API call via Client side JS to Mongo DB Atlas API. Code snippet is as below.

            try {
            const exportData = await exportBackupData();
            const url = `https://${region}.data.mongodb-api.com/app/${appId}/endpoint/data/v1/action/insertOne`;
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    dataSource: 'mongodb-atlas',
                    database: dbName,
                    collection: collectionName,
                    document: exportData,
                }),
            });

I am getting the below error

{type: 'cors', url: 'https://ap-southeast-2.aws.data.mongodb-api.com/ap…ation-0-mbgslar/endpoint/data/v1/action/insertOne', redirected: false, status: 400, ok: false, …}

Gone through different links but all I get is CORS is now supported via Bearer Authentication and I am doing that.

I have added the hostname to the App settings -> Allowed Request Origins as well in mongodb.

Any idea what I am missing?

Is There an ESLint Rule to Require Parenthesis Around Conditions?

I want to be able to enforce parens around conditions in my JavaScript project with ESLint.

if ((condition1 === "yes") && (condition2 === "no")) {
    // Do something
}

The following should produce an error and ESLint should be able to automatically “fix” it with --fix.

if (condition1 === "yes" && condition2 === "no") {
    // Do something
}

I have been unable to find a rule that works for this. Is there currently any ESLint rule that can achieve this?

Get libp2p Secp256k1PeerId from ethereum public key

I have a eth public key 0x123..., and I’d like to get its corresponding Secp256k1 peer id (e.g. 16Uiu...)

The @libp2p package has createSecp256k1PeerId() but it doesn’t take any parameters. It also has createFromPubKey(publicKey) which returns Ed25519PeerId | Secp256k1PeerId | RSAPeerId, but I’m not sure the format publicKey should be in to get a Secp256k1PeerId out.

How can I perform this eth public key hex string -> Secp256k1PeerId conversion?

Fetch request does not work with expressJS server (but both are working fine)?

I have a fetch request in a server component in a NextJS app. It looks like that (I tried to reduce all code to minimum working example) :

export async function bookRoom(params: BookingRequest) {
    const {rooms, startTime, endTime} = params;
    console.log(rooms, startTime, endTime);
    const booking = await fetch(API.bookings, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer lol`,
        },
        body: JSON.stringify(params),
    });
    console.log('trying to book...', JSON.stringify(params));
    return booking.json();
}

It works fine if API.bookings is :
https://rbaskets.in/web/kkk-ttt

request as received by rbaskets.in

However when targeting http://localhost:3000/booking I receive absolutely no body (just {}).

booking.js

'use strict';

const express = require('express');
const router = express.Router();

// Register a new booking
router.post('/', async (req, res) => {
    // Check all parameters of the booking are valid
    const params = req.body;
    console.log(params);
    return res.status(201).json({'status': 'ok', 'booking': null});
});

server.js

'use strict';

const express = require('express');
const path = require('path');
const https = require("https");
const fs = require("fs");

// Routes
const booking = require("./routes/booking");

const app = express();
const port = 3000;

app.use(express.json());

// bookings route
app.use('/booking', booking);


// Get the server to actually listen to a port
app.listen(port, () => {
    console.log(`API server listening on port ${port} (http://localhost:${port}/)`);
});

Which is very strange to me because from Bruno (a PostMan alternative) … everything works fine (I get {"startTime": "2024-09-02T03:23:00.000Z","endTime": "2024-09-04T03:24:00.000Z","rooms": [1]} in the console on that endpoint with the very same payload !

request handled correctly from Bruno

If any of you has a single clue !??

Note : it’s important to first fire expressJS : it’ll bind to port 3000 then next will fallback to 3001 if available [gonna be fixed soon : express will run on another port …].

  • Tested my express endpoint with bruno … and all was well
  • I started by trying to understand why my fetch was not posting the body … with no success then to be sure :
  • I ran those requests against rbasket instead … and my body was there !! So with both working independantly I’m having trouble to understand what’s really going on … Oh and since
  • I’m getting that {} in the expressJS console … so I do receive the request from fetch [so I guess not really a network problem !] ! (just not the body, as it seems !!) ]

I could also mention that I have another GET endpoint on the Express server that I can fetch just fine from the NextJS (no body though, only query string)

How to Require a Single-Line Conditional Body to be on its Own Line with ESlint

I have a large project with a lot of code. We are trying to standardize that code with linting rules.

We have several conditionals that are written like this:

if (thing) { doSomething(); }
else { doSomethingElse(); }

What I want is to make it like this:

if (thing) {
    doSomething();
}
else {
    doSomethingElse();
}

I have been unable to find any rule for eslint that meets this need. How to do?