How can I view Zustand state with time travel debugging for multiple combined stores?

I’m really new to Zustand state management library and I’m using it for a React project with ViteJS. I have two stores using the slice pattern with bounded store to combine them. Is there anyway to view the Zustand states with time travel debugging? I know that I can use Zustand middleware devtools, but that doesn’t support combined or multiple stores. I have used a third-party library called zukeeper which is suggested on the official Zustand documentation too.

Here is what I did,

const authStoreSlice = (set) => ({
 userName: null,
 userEmail: null,
 setUserName: (username) => set(() => ({ username })),
 setUserEmail: (userEmail) => set(() => ({ userEmail })),
});
const userStoreSlice = (set) => ({
 users: null,
 setUsers: (users) => set(() => ({ users})),
});

bounded store

import { create } from 'zustand';
import zukeeper from 'zukeeper';

useBoundStore = create(zukeeper((...a) => ({
  ...authStoreSlice (...a),
  ...userStoreSlice (...a),
})))

But in the Zukeeper extention, it shows all store values together as in a single store. is there anyway I could view them as in Redux devtools view separated into stores which we create?

How to check if there are images on the image?

My problem:

I receive news from the API, and there are pictures in them (i.e. a preview of the news), for some reason, I very often receive pictures like this from the API

https://ml.globenewswire.com/media/ZmI4MDcwZWMtZmNiZS00NWM0LThkMjktNDJmNWUwMzJjMWI2LTEwNjEzMjg=/tiny/Mustang-Bio-Inc-.png

That is, there is a picture, but there is no picture content; it is just a transparent background.

I tried checking the width and height of the image but it doesn’t work

<img className={styles["image"]}
     src={news?.Image}
     alt={'news-image'}
     onLoad={(e) => {
       const img = e.target;
       if (img.width === 0 || img.height === 0) {
          img.src = '/images/banners/stock_market_news_banner.svg';
       }
     }}
     onError={(e) => {
       e.currentTarget.src = '/images/banners/stock_market_news_banner.svg'
     }}/>

How to retrieve values of non selected row in HTML datatable using jquery

I trying to get the value of all rows that not clicked on their buttons. For example when I click to the button on first row, I want to retrieve the values of the rows without the clicked one.

 
var table = document.getElementById("all_department");
if (table != null) {
  for (var i = 0; i < table.rows.length; i++) {
  table.rows[i].onclick = function() {
  tableText(this);
      }
    }
  }    
    
function tableText(tableRow) {
var myJSON = JSON.stringify(tableRow);
console.log(myJSON);
}
    <table id="all_departments">
     <thead>
              <th><button>click</button></th>                                   
              <th>Departments</th>
              <th>Creation Date</th>
              <th>Name</th>
     </thead>
    <tbody class="bl">
           <tr>
                <td><button>click</button></td>
                <td>Management</td>
                <td>2-3-2016</td>
                <td>client x</td>
          </tr>
    
           <tr>
                <td><button>click</button></td>
                <td>Sales</td>
                <td>25-6-2019</td>
                <td>client y</td>
          </tr>
    </tbody>
    </table>

how to fix objects are not valid as a React child, in Nextjs13

How to fix this error in Nextjs13, objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead

I’m fetching data from Supabase via Prisma, and I’m getting the data in my terminal but also I’m getting the error in my next App.

pages/index.tsx

import Header from "@/components/Header";
import Navbar from "@/components/Navbar";
import RestaurantCard from "@/components/Restaurantcard";
import { PrismaClient } from "@prisma/client";
const prisma =new PrismaClient()

const fetchRestaurant = async () => {
  const restaurants = await prisma.restaurant.findMany();
  return restaurants;
};

export default async function Home() {
  const restaurants = await fetchRestaurant();
  console.log({restaurants})
  return (
    <main className="bg-gray-100 min-h-screen">
      <main className="max-w-screen-2xl m-auto bg-white">
        <Navbar />
        <main>
          <Header />
          <div className="py-3 px-36 mt-10 flex flex-wrap justify-center">
            {restaurants.map((res) => (
              <RestaurantCard />
            ))}
          </div>
        </main>
      </main>
    </main>
  );
}

Data which I'm getting in the terminal

{
  restaurants: [
    {
      id: 25,
      name: 'Vivaan - fine Indian',      
    },
    {
      id: 26,
      name: 'RamaKrishna Indian',
    }
  ]
}

How can I display a Chart.js plugin-generated antenna on top of a bar chart without it overlapping?

I have created a Chart.js plugin to draw a small antenna on top of each bar in the chart, however the antenna is overlapping with the bar. Is there any way to ensure that the antenna is displayed over the bar, so it won’t be obscured?

    const topAntenna = {
      id: 'topAntenna',
      order: 4,
      beforeDraw(chart, args, options) {
        const { ctx, config, scales: { x, y } } = chart;
        ctx.save();
        ctx.strokeStyle = 'red';
        var data = chart.data.datasets[0].data;
        if (data.length > 0) {
          debugger
          //ctx.strokeRect(x, y, width, height)
          ctx.fillRect(x.getPixelForValue(0), y.getPixelForValue(data[0][1]) - 20, 10, 60);
        }
        ctx.restore();
      }
    }

Current output:

enter image description here

Expected output :

enter image description here

I need to remove items from an array dynamically when the value is been changed in react

I need some help removing values from an array.
This is the array

[
    {
        "label": "One",
        "value": "one"
    },
    {
        "label": "Two",
        "value": "two"
    },
    {
        "label": "Three",
        "value": "three"
    },
    {
        "label": "Four",
        "value": "four"
    },
    {
        "label": "FIve",
        "value": "five"
    }
]

this is the code which I tried

useEffect(() => {
            let od = [...options?.stockModeList]
            let dc;


    

            if (!isNaN(state?.parentVariant)){
                dc = od.splice(options.length - 2, 2);
            } else {
                dc = od.splice(0, 3);
            }

 // and also I tried this as well
if (state?.parentVariant === null){
                dc = od.splice(options.length - 2, 2);
            } else {
                dc = od.splice(0, 3);
            }
            


            // console.log(dc)

    }, [ options?.stockModeList, state?.parentVariant])

state?.parentVariant variable is updating dynamically when the UI is changing it will mostly be a null value or integer value. So if its a null then I need to run the first statement and if it is an integer then I need to run the else statement.

But the issue is even after the value is been changed it always stays in the if statement.

Can someone help me to resolve this…

How to use webcam in a chrome extension?

I’m working on a Chrome extension and I want to add a webcam test for Chrome OS devices, and I’m having trouble my script to run properly. I have followed the documentation and examples, but the it doesn’t seem to execute correctly.

Here are the details of my setup:

I have a manifest.json file with the following relevant configuration:

  {
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "permissions": ["activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_URLs>"],
      "js": ["content_script.js"],
    }
  ]
}

I have a contentScript.js file located in the same directory as the manifest.json file. The file contains some basic code for testing:

// contentScript.js

// Inject an iframe into the current tab's page
const iframe = document.createElement("iframe");
iframe.src = chrome.runtime.getURL("iframe.html");
iframe.style.display = "none";
document.body.appendChild(iframe);

// Listen for messages from the iframe
window.addEventListener("message", (event) => {
  if (event.data.type === "mediaAccessSuccess") {
    // Notify the background script about the successful access
    chrome.runtime.sendMessage({ type: "requestMediaAccess" });
  } else if (event.data.type === "mediaAccessError") {
    // Notify the background script about the failed access
    chrome.runtime.sendMessage({ type: "requestMediaAccessError", error: event.data.error });
  }
});

Here is my iframe.html:

<!-- iframe.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <script>
      // Request media access in the iframe
      navigator.mediaDevices
        .getUserMedia({ video: true })
        .then(() => {
          // Notify the parent content script about the successful access
          window.parent.postMessage({ type: "mediaAccessSuccess" }, "*");
        })
        .catch((error) => {
          // Notify the parent content script about the failed access
          window.parent.postMessage({ type: "mediaAccessError", error: error.message }, "*");
        });
    </script>
  </body>
</html>

My background.js:

// background.js

// Listen for messages from content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "requestMediaAccess") {
    // Request media access from the background script
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const activeTab = tabs[0];
      chrome.scripting.executeScript({
        target: { tabId: activeTab.id },
        function: requestMediaAccessInTab,
      });
    });
  }
});

// Function to request media access in the tab
function requestMediaAccessInTab() {
  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then(() => {
      // Notify the content script about the successful access
      chrome.runtime.sendMessage({ type: "mediaAccessSuccess" });
    })
    .catch((error) => {
      // Notify the content script about the failed access
      chrome.runtime.sendMessage({ type: "mediaAccessError", error: error.message });
    });
}

And finally my popup.js:

// popup.js

// Send a message to the content script to toggle the webcam
function toggleWebcam() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    const activeTab = tabs[0];
    chrome.scripting.executeScript({
      target: { tabId: activeTab.id },
      function: toggleWebcamInTab,
    });
  });
}

// Function to toggle the webcam in the tab
function toggleWebcamInTab() {
  chrome.runtime.sendMessage({ type: "toggleWebcam" });
}

// Attach event listener to the button
document.getElementById("toggleWebcamButton").addEventListener("click", toggleWebcam);

I want to be able to press the button in my popup.html

<button id="toggleWebcamButton">Toggle Webcam</button>

There always seems to be a lot of issues with this. Sorry for a lot of code, but any guidance is appreciated.

How do you find out (print) a Path2D object?

How do I print out the name of a Path2D object?

var test = new Path2D() and then follows the code for the drawing.

Then I store the variable test in another variable with an if statement.

if (ctx.isPointInPath(test, event.offsetX, event.offsetY)) {

something = test ...

console.log(something) will give Path2D {}.

console.log(toString(something)) will give [object undefined].

console.log(JSON.stringify(something)) will give {}.

cannot read properties of undefined (reading ‘watchQuery’) at useQuery

I have a next.js application and when I perform a useQuery I get the error “cannot read properties of undefined (reading ‘watchQuery’) at useQuery”. I have had to change some dependencies to resolve an error rendering my hooks so I had changed my next version a few times as well as my apollo-client as well I have a feeling it is a dependency related issue here are all my relevant files:
my package.json

"dependencies": {
   "@apollo/client": "3.6.2",
   "@apollo/link-error": "^2.0.0-beta.3",
   "@apollo/react-ssr": "^4.0.0",
   "@keystone-6/document-renderer": "^1.1.2",
   "@sentry/nextjs": "^7.52.1",
   "@stripe/react-stripe-js": "^1.1.2",
   "@stripe/stripe-js": "^1.11.0",
   "apollo-upload-client": "^14.1.3",
   "babel-core": "^7.0.0-bridge.0",
   "babel-plugin-macros": "^3.1.0",
   "babel-plugin-styled-components": "^2.1.1",
   "date-fns": "^2.16.1",
   "downshift": "^6.0.12",
   "enzyme": "^3.11.0",
   "enzyme-adapter-react-16": "^1.15.5",
   "graphql": "15.8.0",
   "graphql-tag": "^2.11.0",
   "graphql-upload": "^11.0.0",
   "lodash.debounce": "^4.0.8",
   "next": "^12.2.2",
   "next-with-apollo": "^5.1.1",
   "nprogress": "^0.2.0",
   "prop-types": "^15.7.2",
   "react": "^17.0.2",
   "react-dom": "^17.0.2",
   "react-is": "^17.0.2",
   "react-transition-group": "^4.4.1",
   "styled-components": "^5.2.1",
   "vercel": "^29.3.4",
   "waait": "^1.0.5"
 },
 "devDependencies": {
   "@apollo/react-testing": "^4.0.0",
   "@babel/core": "^7.12.10",
   "@babel/preset-env": "^7.12.11",
   "@testing-library/jest-dom": "^5.11.8",
   "@testing-library/react": "^11.2.3",
   "@testing-library/user-event": "^12.6.0",
   "babel-eslint": "^10.1.0",
   "babel-jest": "^26.6.3",
   "babel-plugin-styled-components": "^2.1.1",
   "casual": "^1.6.2",
   "eslint": "^7.17.0",
   "eslint-config-airbnb": "^18.2.1",
   "eslint-config-prettier": "^7.1.0",
   "eslint-config-wesbos": "^1.0.1",
   "eslint-plugin-html": "^6.1.1",
   "eslint-plugin-import": "^2.22.1",
   "eslint-plugin-jsx-a11y": "^6.4.1",
   "eslint-plugin-prettier": "^3.3.1",
   "eslint-plugin-react": "^7.22.0",
   "eslint-plugin-react-hooks": "^4.2.0",
   "jest": "^26.6.3",
   "prettier": "^2.2.1",
   "react-test-renderer": "^17.0.1"
 },
 "engines": {
   "node": "16.x"
 },
 "//": "This is our babel config, I prefer this over a .babelrc file",
 "babel": {
   "env": {
     "development": {
       "presets": [
         "next/babel"
       ],
       "plugins": [
         [
           "babel-plugin-styled-components",
           "macros",
           {
             "ssr": true,
             "displayName": true
           }
         ]
       ]
     },
     "production": {
       "presets": [
         "next/babel"
       ],
       "plugins": [
         [
           "babel-plugin-styled-components",
           "macros",
           {
             "ssr": true,
             "displayName": true
           }
         ]
       ]
     },
     "test": {
       "presets": [
         [
           "next/babel",
           {
             "preset-env": {
               "modules": "commonjs"
             }
           }
         ]
       ],
       "plugins": [
         [
           "babel-plugin-styled-components",
           {
             "ssr": true,
             "displayName": true
           }
         ]
       ]
     }
   }
 }
}

my createClient

import { ApolloClient, ApolloLink, InMemoryCache } from "@apollo/client";
import { onError } from "@apollo/link-error";
import { createUploadLink } from "apollo-upload-client";
import withApollo from "next-with-apollo";
import { prodEndpoint, cors } from "../config";

function createClient({ headers, initialState }) {
return new ApolloClient({
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors)
        graphQLErrors.forEach(({ message, locations, path }) =>
          console.log(
            `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
          )
        );
      if (networkError)
        console.log(
          `[Network error]: ${networkError}. Backend is unreachable. Is it running?`
        );
    }),
    createUploadLink({
      uri: prodEndpoint,
      cors,
      fetchOptions: {
        credentials: "include",
      },
      headers,
    }),
  ]),
  cache: new InMemoryCache().restore(initialState || {}),
});
}

export default withApollo(createClient);

and my _app.js

import { ApolloProvider } from "@apollo/client";
import NProgress from "nprogress";
import Router from "next/router";
import Page from "../components/Page";
import "../components/styles/nprogress.css";
import apolloClient from "../lib/withData";

Router.events.on("routeChangeStart", () => NProgress.start());
Router.events.on("routeChangeComplete", () => NProgress.done());
Router.events.on("routeChangeError", () => NProgress.done());

function MyApp({ Component, pageProps }) {
  // const router = useRouter();
  return (
    <ApolloProvider client={apolloClient}>
      <Page>
        <Component {...pageProps} />
      </Page>
    </ApolloProvider>
  );
}

MyApp.getInitialProps = async function ({ Component, ctx }) {
  let pageProps = {};
  console.log(pageProps);
  if (Component.getInitialProps) {
    console.log(`Paging all props ${pageProps}`);
    pageProps = await Component.getInitialProps(ctx);
  }
  pageProps.query = ctx.query;
  return { pageProps };
};

export default MyApp;

Vite/vue3 HMR not updating imported store refs/computeds when files changed

tl;dr HRM working everywhere except for imported pinia store refs.

I have a fairly basic Vue3 + vite + pinia site, and I’m trying to get hot module replacement (HRM) working for store values. Whenever I modify a ref on a component *.vue file directly and use it in it’s template, it’s updating the page. However, if it’s a ref from a pinia store, I have to manually refresh the page for the change to be reflected.

Some things I’ve tried:

UPDATE:
So from the last bullet, pinia issue 843 apparently that’s expected behavior, but I can’t get it to work even with the comment -> change -> uncomment that they mentioned. I didn’t really understand their explanation, if anyone can expand on it would really appreciate it!

Note: The functionality of the page isn’t the issue, if the store is updated through user input, the page does update as you’d expect, this is just about getting HMR to work through the store. Also, it doesn’t generalize to any *.js file imported; with composables, for instance, HRM works fine. Likewise with other variables, etc imported from *.js files.


Details:

    "pinia": "^2.0.36",
    "vue": "^3.2.25",
    "vite": "^2.9.9",

Difference between const a = value; vs const a = () => (value);

I’d like to know if there’s any difference (performance, memory usage) between the two following JS statements, whether it is recommended to use one over the other, and the reasoning behind it.

Statement 1 (assigning value)

const fooOne = { a: 1, b: 2 };
const barOne = fooOne;

Statement 2 (using function expression)

const fooTwo = () => ({ a: 1, b: 2 });
const barTwo = fooTwo();

Both statements yield the same thing:

console.log(barOne); // outputs {a: 1, b: 2}
console.log(barTwo); // also outputs {a: 1, b: 2}

Why do inline css and internal css have different behaviour?

In the example, I have to click twice to see Foo content, but only once to see Bar content. The only difference is that Foo content has a internal style and Bar has inline style.

<html>

<head>
  <style>
    .content {
      display: none;
    }
  </style>

  <script>
    function showHide(element) {
      sibling = element.nextElementSibling;
      if (sibling.style.display == "none")
        sibling.style.display = "block"
      else sibling.style.display = "none";
    }
  </script>
</head>

<body>
  <h1 onclick="showHide(this)">Foo</h1>
  <div class="content">
    Foo Content
  </div>

  <h1 onclick="showHide(this)">Bar</h1>
  <div style="display: none;">
    Bar Content
  </div>
</body>

</html>

You can see this code in jsfiddle here

I’d like to use internal css or external css but having the same behaviour as I get in inline css, is this possible?
I guess this is a basic topic, but I don’t know what concepts to use to going deeper.