Persisting @tanstack/vue-query query client in Quasar SSR

Is there any way to persist data from server to client in SSR apart from using “store” in SSRContext? The docs mostly mention Vuex, even though Vuex is deprecated. I’m using @tanstack/vue-query, which saves a lot of headaches when managing async or server state. It manages deduping requests, retries, query caching and invalidation, gabarge collection, query refetching, infinite queries, and so much more. In the docs, the guidelines for integrating with Vite SSR are:

// main.js (entry point)
import App from './App.vue'
import viteSSR from 'vite-ssr/vue'
import {
  QueryClient,
  VueQueryPlugin,
  hydrate,
  dehydrate,
} from '@tanstack/vue-query'

export default viteSSR(App, { routes: [] }, ({ app, initialState }) => {
  // -- This is Vite SSR main hook, which is called once per request

  // Create a fresh VueQuery client
  const queryClient = new QueryClient()

  // Sync initialState with the client state
  if (import.meta.env.SSR) {
    // Indicate how to access and serialize VueQuery state during SSR
    initialState.vueQueryState = { toJSON: () => dehydrate(queryClient) }
  } else {
    // Reuse the existing state in the browser
    hydrate(queryClient, initialState.vueQueryState)
  }

  // Mount and provide the client to the app components
  app.use(VueQueryPlugin, { queryClient })
})

Then in the Vue component:

<!-- MyComponent.vue -->
<template>
  <div>
    <button @click="refetch">Refetch</button>
    <p>{{ data }}</p>
  </div>
</template>

<script setup>
  import { useQuery } from '@tanstack/vue-query'
  import { onServerPrefetch } from 'vue'

  // This will be prefetched and sent from the server
  const { refetch, data, suspense } = useQuery({
    queryKey: ['todos'],
    queryFn: getTodos,
  })

  onServerPrefetch(suspense)
</script>

I tried the same with boot files Quasar SSR, replacing initialState with ssrContext but it reads as undefined on the client.

Here is what I tried:

import { boot } from 'quasar/wrappers'
import { QueryClient, VueQueryPlugin, dehydrate, keepPreviousData } from '@tanstack/vue-query'
import { hydrate } from 'vue'

export default boot(({ app, ssrContext }) => {
  const globalQueryClient = new QueryClient({
    defaultOptions: {
      queries: {
        networkMode: 'always',
        placeholderData: keepPreviousData,
        retry: false,
        staleTime: 1000 * 60 * 5 // 5 minutes
      }
    }
  })
  if (process.env.SERVER) {
    // Indicate how to access and serialize VueQuery state during SSR
    ssrContext.vueQueryState = { toJSON: () => dehydrate(globalQueryClient) }
  } else {
    // Reuse the existing state in the browser
    hydrate(globalQueryClient, ssrContext.vueQueryState)
  }
  app.use(VueQueryPlugin, { queryClient: globalQueryClient })
})

vueQueryState was undefined on the client.

Getting Syntax “??==” Error in Rollup.js when i am running rollup -c for bundling the package

I am trying to creat a npm package and publishing into npm repository, after setup the rollup.config.js
when i am trying to bundle the package with “rollup -c” getting Compilation error in rollup.js (internal file)

Saying that “??==” Syntax error.

// rollup.config.js

import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import dts from "rollup-plugin-dts";
import terser from "@rollup/plugin-terser";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import { babel } from "@rollup/plugin-babel";

const packageJson = require("./package.json");

export default [
  {
    input: "src/index.ts",
    output: [
      {
        file: packageJson.main,
        format: "cjs",
        sourcemap: true,
      },
      {
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    plugins: [
      peerDepsExternal(),
      resolve(),
      commonjs(),
      babel({ babelHelpers: "bundled" }),
      typescript({ tsconfig: "./tsconfig.json" }),
      postcss(),
      terser(),
    ],
    external: ["react", "react-dom", /.css$/],
  },
  {
    input: "src/index.ts",
    output: [{ file: "dist/types.d.ts", format: "es" }],
    plugins: [dts.default()],
  },
];

This is package.json configuration:

{
  "name": "lighter-lib",
  "version": "1.0.0",
  "description": "lighter component library",
  "main": "dist/cjs/index.js",
  "module": "dist/esm/index.js",
  "types": "dist/index.d.ts",
  "author": "Ashish",
  "license": "ISC",
  "config": {
    "commitizen": {
      "path": "./node_modules/cz-conventional-changelog"
    }
  },
  "scripts": {
    "commit": "git-cz",
    "build": "rollup -c" // tried with this flag also bundleConfigAsCjs
  },
  "peerDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.23.9",
    "@babel/preset-env": "^7.23.9",
    "@babel/preset-react": "^7.23.3",
    "@babel/preset-typescript": "^7.23.3",
    "@rollup/plugin-commonjs": "^25.0.7",
    "@rollup/plugin-node-resolve": "^15.2.3",
    "@rollup/plugin-terser": "^0.4.4",
    "@rollup/plugin-typescript": "^11.1.6",
    "babel-jest": "^29.7.0",
    "commitizen": "^4.3.0",
    "cz-conventional-changelog": "^3.3.0",
    "rollup": "^4.9.6",
    "rollup-plugin-dts": "^6.1.0",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "rollup-plugin-postcss": "^4.0.2",
    "semantic-release": "^23.0.2"
  }
}

I checked lot of places not getting the proper answer. might be error is related to cjs and es6 module definition.

Android Load WebView and Javascript

I am writing an app using WebView to load my html, css, js and get some problems when loading the html.

Here is the MainActivity

public class MainActivity extends AppCompatActivity
{
    HTMLDataBase myDB1;
    ContentTableDataBase myDB2;
    CloudTableDataBase myDB3;
    InterviewDataBase myDB4;
    Context context;
    boolean check;

    private WebView view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myDB1 = new HTMLDataBase(this);
        myDB2 = new ContentTableDataBase(this);
        myDB3 = new CloudTableDataBase(this); 
        myDB4 = new InterviewDataBase(this); 

        display_html();
        Javascript_Android_Communication();

    }

    public void display_html()
    {
        WebView view = (WebView) findViewById(R.id.WebView);
        view.getSettings().setJavaScriptEnabled(true);


        Cursor res = myDB1.getAllData();

        if (res.getCount() > 0) {
            StringBuffer buffer = new StringBuffer();
            while (res.moveToNext())
            {
                buffer.append(res.getString(0) + ",");
                buffer.append(res.getString(1) + ",");
                buffer.append(res.getString(2) + ",");
            }
            
            String[] result = buffer.toString().substring(0, buffer.toString().trim().length() - 1).split(",", -2);

            if (result[2].equals("block"))
            {
                view.loadUrl("file:///android_asset/index.html");
            }

            if (!result[2].equals("block"))
            {
                view.loadUrl("file:///android_asset/index2.html"); // Problem occurs when loading this html
            };
        }

    }

    public void Javascript_Android_Communication()
    {
        WebView view = (WebView) findViewById(R.id.WebView);
        view.setWebChromeClient(new WebChromeClient() {});
        WebSettings settings = view.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);

        view.addJavascriptInterface(new JavaScriptInterface(this), "Android");
        view.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app");
    }
}

Javascript requests information from DataBase and imports them to:

document.getElementById("").style.display = "";

The problem is data can be extracted but the html is never completely loaded and thus errors occurs when I change the html element. When I open the logcat, it said “Uncaught TypeError: Cannot read property ‘style’ of null”.

Whenever I use alert method to call

document.getElementById("").style.display

It simply returns me empty.

I try to use

document.addEventListener("load",function(){alert(document.getElementById().style.display);});

but the page is never completely loaded so it just wastes my time. What shall I do so that I can change the html with data I have extracted.

Why MathQuill does not support nmid LaTeX?

When I try to show that 3 does not divide 4 in LaTeX like this, 3 nmid 4, it does not display what I need. However, mid works correctly.

mid working correctly

nmid not working

I do a google search on is there a configuration to enable or disable this but didn’t find anything.

My configurations:

    var mathField = MQ.MathField(mathFieldSpan, {
        spaceBehavesLikeTab: true, // configurable
        // autoCommands: 'pi theta sqrt sum',
        autoOperatorNames: 'sin cos',
        substituteTextarea: function() {
            return document.createElement('textarea');
        },
        handlers: {
            edit: function () { // useful event handlers
                latexSpan.textContent = mathField.latex(); // simple API
            },
            enter: function () {
                // addMathField();
            },
        }
    });

Whatever code I add into this may appear as a backlink? [closed]

I have a page like domain.com/code.js

Whatever code I add into this may appear as a backlink?

To get backlinks to my other sites by just adding

var a = document.createElement('a');
var linkText = document.createTextNode("mydomain");
a.appendChild(linkText);
a.title = "mydomain";
a.href = "https://mydomain/";
document.body.appendChild(a);

this didn’t work

HTML Table bounces onScroll in React 18, whereas React 17 renders the table correct

I am working on a virtualised data grid for my application.
I use transform: translateY for the table offset on scroll to make table virtualised.
I developed all the functionality in React 17 project, but when migrated to React 18 I found that the data grid behaviour changed for the worse – the data grid started to bounce on scroll.
I prepared the minimal representing code extract, which shows my problem.
To assure that the code is the same for React 17 and React 18, I change only the import of ReactDOM from ‘react-dom/client’ to ‘react-dom’ (which is of course incorrect, since the latter is deprecated) in my index.tsx file.

This is the code:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Virtuailsed table</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

index.js

// import ReactDOM from "react-dom";
import ReactDOM from "react-dom/client";
import { useState } from "react";
import "./styles.css";

let vendors = [];

for (let i = 0; i < 1000; i++ ){
  vendors.push({
    id: i,
    edrpou: i,
    fullName: i,
    address: i
  })
}

const scrollDefaults = {
  scrollTop: 0,
  firstNode: 0,
  lastNode: 70,
};

function App() {
  const [scroll, setScroll] = useState(scrollDefaults);
  const rowHeight = 20;
  const tableHeight = rowHeight * vendors.length + 40;
  const handleScroll = (event) => {
    const scrollTop = event.currentTarget.scrollTop;
    const firstNode = Math.floor(scrollTop / rowHeight);
    setScroll({
      scrollTop: scrollTop,
      firstNode: firstNode,
      lastNode: firstNode + 70,
    });
  };
  const vendorKeys = Object.keys(vendors[0]);
  return (
    <div
      style={{ height: "1500px",  overflow: "auto" }}
      onScroll={handleScroll}
    >
      <div className="table-fixed-head" style={{ height: `${tableHeight}px` }}>
        <table style={{transform: `translateY(${scroll.scrollTop}px)`}}>
          <thead style={{ position: "relative" }}>
            <tr>
              {vendorKeys.map((key) => <td>{key}</td>)}
            </tr>
          </thead>
          <tbody >
            {vendors.slice(scroll.firstNode, scroll.lastNode).map((item) => (
              <tr style={{ height: rowHeight }} key={item.id}>
                <td><div className="data">{item.id}</div></td>
                <td><div className="data">{item.edrpou}</div></td>
                <td><div className="data">{item.fullName}</div></td>
                <td><div className="data">{item.address}</div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// const rootElement = document.getElementById("root");
// ReactDOM.render(<App />, rootElement);

const root = ReactDOM.createRoot(
  document.getElementById('root')
);

root.render(
  <App />
);

styles.css

* {
  padding: 0; 
  margin: 0
}
.table-fixed-head thead th{
  background-color: white;
}
.row {
  line-height: 20px;
  background: #dafff5;
  max-width: 200px;
  margin: 0 auto;
  box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.5);
}
.data{
  width: 150px;
  white-space: nowrap;
  overflow: hidden;
  margin-right: 20px;
}

I have spent 1.5 day trying to find the reason why the table bounces on scroll in React 18 without result.
BTW, overscroll-behaviour: none doesn`t work.

having problems with my js external file with html

Hi i have a slider on my home page and a hamburger nav and font size change in one file, however. they do not all work unless i split them into different files. Why is this? can someone explain please?

I have added the external file link to each of my pages, if i were to take the script out and out it straight into the html it will work. So as i am new to this it is probably so simple and i apologise if this is a stupid question.

see the js file below;

///NAV

document.querySelector(".toggle-button").addEventListener("click", () => 
{
  document.querySelector("#nav").classList.toggle("hide")
})


//FONT SIZE

document.getElementById("smallA").onclick = function(){changeSize("small")};

document.getElementById("mediumA").onclick = function(){changeSize("medium")};

document.getElementById("largeA").onclick = function(){changeSize("large")};

function changeSize(c)
{
    document.getElementsByTagName("body")[0].className= c;
}






//SLIDER

let slideIndex = 0;
      showSlides();

      function showSlides() {
        let i;
        let slides = document.getElementsByClassName("mySlides");
        for (i = 0; i < slides.length; i++) {
          slides[i].style.display = "none";
        }
        slideIndex++;
        if (slideIndex > slides.length) {
          slideIndex = 1;
        }

        slides[slideIndex - 1].style.display = "block";
        setTimeout(showSlides, 2000); // Change image every 2 seconds
      }

create reusable package from component in next.js

I have a Next.js website where I’ve created a component named TestMe.tsx. This component uses Next.js Link and Image components, and my project is using Next.js version 14.1.0 . I want to generate a build of this component so that I can reuse it in other Next.js projects as an Npm package.

I prefer to configure the next.config.mjs file to achieve this. How can I set up my next.config.mjs file to build TestMe.tsx as a standalone package that can be published on npm and easily reused in other Next.js projects?

I tried the following configuration but it didn’t work:

const nextConfig = {
  webpack(config, { isServer }) {
    if (!isServer) {
      config.externals.push("/src/components/TestMe/index.tsx");
      config.output.library = "TestMe";
      config.output.libraryTarget = "umd";
      config.output.publicPath = "auto";
    }

    return config;
  },
  experimental: {
    externalDir: true,
  },
};

export default nextConfig;

please help me! thanks.

Put desired color to fill transparent areas of an image in CSS

I’m currently working on implementing a loader animation on my website, and I’ve noticed that there’s a transparent background on my image. Is there a way to override this transparent background using CSS? It seems that setting a background color is not having any effect in covering up the transparency.

For instance, consider the image of a Pokeball below, which has a transparent background.

enter image description here

Below is my sample code on how I animate my loader.

body {
  min-height: 100vh;
  display: grid;
  place-items: center;
  .loader {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vh;
    height: 100vh;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f7f9fb;
    transform: opacity 0.75s, visiblity 0.75s;

    img {
      width: 300px;
      height: 300px;
      animation: loading 2s ease infinite;
    }

    @keyframes loading {
      from {
        transform: rotate(0turn);
      }
      to {
        transform: rotate(1turn);
      }
    }
  }

  .loader-hidden {
    opacity: 0;
    visibility: hidden;
  }
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="dist/style.css" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <title>Loader</title>
  </head>
  <body>
 
    <div class="loader">
      <img src="https://i.postimg.cc/NFzNjN86/pokemon-ball.png" alt="pokeball" />
    </div>
    <script src="/app/js/app.js"></script>
  </body>
</html>

Github Pages not updating fonts after deployment(React + Vite app)

I made a web application using react, vite and js. I tried to add some custom fonts(ttf format) which works completely fine on the local server. But when the site is deployed using github sites, the fonts do not load.

my app.css

@font-face {
  font-family: mija;
  src: url(./Fonts/mija.ttf);
}
@font-face {
  font-family: sanandreas;
  src: url(./Fonts/SAN ANDREAS.otf);
}

the fonts where placed in a separate folder Fonts outside the public folder

I also tried to add the font face code in the index.css but the same issue persisted. I am a beginner learning things by myself and need help with this sorry if this is some weird/ silly question as I have been getting many downvotes to my questions

GTM custom java script “Error at line 13, character 5: Parse error. ‘)’ expected”

I’m made script that extracts offer id’s in teh basket. In console it returns values as intended but when trying to run a preview in GTM it returns mentioned error.
Do you know how can I fix this script?

(function () {
    
  var cartItems = Array.from(document.querySelectorAll('tr.cart-item')).map(function(item) { return item.querySelector('a'); });

  function mapId(a) {
      return a.href.split('products/')[1].split('?')[0]; 
  }

  var result = cartItems.map(mapId);
  
  return result;

})();

I tried adjusting the code but it didn’t help

Using “this” in an addEventListener to replace “document.querySelector()”

Beginner in JavaScript here. I’m building a simple calculator using HTML, CSS and JavaScript.
I`ve realized that if I use this instead of document.querySelector(“.add”) when adding a style to a button inside of an addEventListener, my code still works. Question: would that be correct or should I always stick to the original document.querySelector(“.add”)?

document.querySelector(".add").addEventListener("click", function () {
  let a = Number(document.querySelector(".num1").value);
  let b = Number(document.querySelector(".num2").value);

  this.classList.add("botaoClicado");
  //the above "this" replaces this excerpt: document.querySelector(".add")

  let soma = a + b;
  console.log(soma);

  document.querySelector(".result").textContent = `RESULTADO: ${soma}`;
});

I am stuck at this program and i dont know what’s wrong wiht the code of program [closed]

npm ERR! code ENOENT
npm ERR! syscall lstat
npm ERR! path C:UsersHPAppDataRoamingnpm
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, lstat 'C:UsersHPAppDataRoamingnpm'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in: C:UsersHPAppDataLocalnpm-cache_logs2024-02-24T12_33_13_182Z-debug-0.log

I am stuck at this program and i dont know what’s wrong wiht the code of program please can anyone help answer my question ?

Copilot – strange injection in javascript

I was using Visual Studio for an ASP.netcore project at work with Github Copilot. I was writing javascript in one of the Views. A strange thing happened where lowercase d’s were injected into the code at random times and random places. It was a POTA to clean up and I had to turn off Copilot. There were a couple curly braces that were injected, also.

Are any of you familiar with this behavior? I did not train it to do these things.

fastapi javascript athentication

I have two endpoints, /login and /index. The /login is for authentication and getting an access_token. The /index is protected and user should login first.

After authentication, the /login sends the access token to the client. The client should be redirect to the /index page after receiving an access token.

It is the code:

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")

@app.get("/index")
async def root(
       request: Request,
       current_user: Annotated[User, Depends(oauth2_scheme)]
):
   return templates.TemplateResponse("index.html", {"request": request})

@app.post("/login")
async def login(
   request: Request,
   data: Annotated[OAuth2PasswordRequestForm, Depends()],
):
   user = authenticate_user(data.username, data.password)
   if not user:
       raise HTTPException(...)
   access_token = create_access_token(...)
   return Token(access_token=access_token, token_type="bearer")

It is the client form:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Login</title>
</head>
<body>
<h1>Login</h1>
<form id="loginForm" >
   <table>
       <tr>
           <td>
               <label for="username">Email:</label>
           </td>
           <td>
               <input type="text" id="username" name="username" required>
           </td>
       </tr>
       <tr>
           <td>
               <label for="password">Pass Code:</label>
           </td>
           <td>
               <input type="text" id="password" name="password" required>
           </td>
       </tr>
       <tr>
           <td></td>
           <td>
               <button type="submit" style="margin-top: 15px">Submit</button>
           </td>
       </tr>
   </table>
</form>
<script>
   document.getElementById("loginForm").addEventListener("submit", function (event) {
       event.preventDefault();
       fetch("/login", {
           method: "POST",
           body: new FormData(event.target)
       })
           .then(response => {
               if (response.ok) {
                   return response.json();
               } else {
                   throw new Error('Failed to authenticate');
               }
           })
           .then(data => {
               window.location.href = '/index';
           })
           .catch(error => console.error("Error:", error));
   });
</script>
</body>
</html>

This code does not work because of lacking of the authentication header. I get this error:
{“detail”:”Not authenticated”}

The test in /docs works because it sends the access token in the Authorization header. This command works:

curl -X 'GET' 
  'http://127.0.0.1:8000/index' 
  -H 'accept: application/json' 
  -H 'Authorization: Bearer A_VALID_TOKEN '

I do not know how I should handle the client side. I am not sure if I should send another fetch for the /index and get the html content and assign it to the body section. I do not know what is the best practice. Maybe I can use RedirectResponse from fastapi.response. I am not sure if it is a good practice or not. /login should send back an access token and not a html code I think.