Save pdf in Safari browser

I’m using a Mapbox map on my website, and I’m trying to take a screenshot of this map using HTML2Canvas and JSPDF, then insert it into a PDF. It works in Chrome but not in Safari. I am getting below errors. Any ideas on how to fix this? Thanks in advance.

...
    doc.save("" + REPORT + "_" + formattedDateTime + ".pdf");

    function convertToBase64(width, height) {
        html2canvas(document.getElementById("map"), {
          width: width,
          height: height,
          useCORS: true,
          allowTaint: true,
        })
          .then((canvas) => { var maxWidth = 525;
            var maxHeight = 320;
              var imgWidth = width;
              var imgHeight = height;
    
              if (imgWidth > maxWidth) {
                imgHeight *= maxWidth / imgWidth;
                imgWidth = maxWidth;
              }
              if (imgHeight > maxHeight) {
                imgWidth *= maxHeight / imgHeight;
                imgHeight = maxHeight;
              }
            imageBase64 = canvas.toDataURL("image/jpeg");console.log(width, height, "width height");
            getBase64FromUrl(imageBase64).then(
              
              doc.addImage(imageBase64, "JPEG", 40, 150, imgWidth, imgHeight)
            );
          })
          .catch((error) => {
            console.error("Hata:", error);
            return error;
          });
      }
    
      
      html2canvas(document.querySelector("#map"),{allowTaint:true,useCORS:true}).then(function (canvas) {
        convertToBase64(window.screen.width, window.screen.height);
      });

TypeError: null is not an object (evaluating'(document.body||document.getElementsByTagName(“head”)[0]).lastChild.src’)
SecurityError: The operation is insecure.

Quasar maximized q-dialog not printing whole screen

Vue 3

@quasar/app-vite 1.4.6 (@quasar/cli 2.2.3)

Sorry for messy format

I setup a test dialog:

<q-dialog maximized v-model="test">
  <q-card>
    <h1 v-for="i in 21" :key="i">hello world</h1>
  </q-card>
</q-dialog>

Which looks like this:
page has more hello worlds hence the scrollbar

And this is what the print preview looks like:
print preview

It does not create the other pages to show all the text. I’ve tried this with other pages and it works fine, it seems to not only work with <q-dialog maximized>...</q-dialog>.

I’ve tried adding these sort of css properties in search for a answer, but does not affect the print preview still:

height: 100% !important;
width: 100% !important;
display: inline-block;

visibility: visible;
print-color-adjust: exact;
-webkit-print-color-adjust: exact;

Webpack Error when hosting an application on local machine

I have got an application code from git repository : https://github.com/drminnaar/noteworx-react-mongodb
so as mentioned in the steps to locally host this application on my machine. I tried npm run build command. This is mentioned in READ.md file in the repo

But when giving the command npm run build I am facing the error below

PS C:Usersakashnoteworx-react-mongodb> npm run build
> [email protected] build 
> webpack -d
[webpack-cli] Error: Option '-d, --devtool <value>' argument missing 
[webpack-cli] Run 'webpack --help' to see available commands and options 
PS C:Usersakashnoteworx-react-mongodb> 

I am not sure how to proceed further. could any one of you please help on this issue.

Why is my PrimeReact dropdown component not detecting custom class styles?

I’m using multiple Prime React dropdown components in my Project and want to style one of them in a different way. I’ve global styles for all of them in CSS to override the default one’s. So for this specific dropdown, I tried applying new CSS styles using a custom class “custom-dropdown”. But it’s not even detecting the CSS styles inside nested in class “custom-dropdown”. But, when applying without nested class, its working. (Sorry, Not able to provide entire code, so elaborated here. Thank you)

I tried this way in CSS, but I couldn’t even see the styles while inspecting. Thank you

<Dropdown
      className="custom-dropdown"
      options={Days}
      value={selectedDay}
      onChange={(e) => {
      setSelectedDay(e.target.value);
     }}
/>
.custom-dropdown{ 
.p-dropdown-items {
  display: flex !important;
  flex-wrap: wrap !important;
}

.p-dropdown-items-wrapper {
  overflow: hidden !important;
}

.p-dropdown-panel {
  max-width: 200px !important;
  min-width: 200px !important;
}
}

Authentication of two different types of users within the same node API and react js using jwt

I’m working on a nodejs api for the backend and reactjs for the front. The principle is to allow two types of users (user and market) to be able to connect knowing that each type of user is linked to a specific mongoDB document because they do not have the same model. It follows that I first established the users system and it worked until creating the token and verification also worked.But when I did for users of type market certe the token is created but verification did not work.

here are the codes of the various node files:

server.js:

const express = require('express');
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require('cors');
const app = express();
const {checkUser, requireAuth, checkMarket, requireAuthMarket} = require('./middleware/auth.middleware');
require('dotenv').config({path: './config/.env'});
require('./config/db');
const marketRoutes = require("./routes/market.routes");
const marketpostRoutes = require("./routes/marketpost.routes");
const postRoutes = require('./routes/post.routes');
const userRoutes = require('./routes/user.routes');
const axios = require("axios");




const corsOptions = {
  origin: process.env.CLIENT_URL,
  credentials: true,
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}



app.use(cors(corsOptions));


app.use(express.urlencoded({ extended: true }));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());


//jet
app.get('*', checkMarket);
app.get('/jwt2id', requireAuthMarket, (req, res) => {
    res.status(200).send(res.locals.market._id)
  });

app.get('*', checkUser);
app.get('/jwtid', requireAuth, (req, res) => {
    res.status(200).send(res.locals.user._id)
  });




//routes
app.use('/api/user', userRoutes);
app.use('/api/post', postRoutes);
app.use('/api/marketpost', marketpostRoutes);
app.use('/api/market', marketRoutes);



//server
app.listen(process.env.PORT, () => {
    console.log("le server a démarré au port: " + process.env.PORT);
})

authuser.js

const UserModel = require('../models/user.model.js');
const jwt = require('jsonwebtoken');
const { signUpErrors, signInErrors } = require('../utils/errors.utils');
const maxAge = 3 * 24 * 60 * 60 * 1000;

const createToken = (id) => {
    return jwt.sign({id}, process.env.TOKEN_SECRET, {
      expiresIn: maxAge
    })
  };

  module.exports.signUp = async (req, res) => {
    const { nom, pseudo, email, password, phoneNumber } = req.body;
  
    try {
      const user = await UserModel.create({ nom, pseudo, email, password, phoneNumber });
      res.status(201).json({ user: user._id });
    } catch (err) {
      const errors = signUpErrors(err);
      res.status(200).json({ errors });
    }
  

  };

module.exports.signIn = async (req, res) => {
    const { email, password } = req.body
  
    try {
      const user = await UserModel.login(email, password);
      const token = createToken(user._id);
      res.cookie('jwt', token, { httpOnly: true, maxAge });
      res.status(200).json({ user: user._id})
    } catch (err){
      const errors = signInErrors(err);
      res.status(200).json({ errors });
    }
  }

module.exports.logout = (req, res) => {
    res.cookie('jwt', '', { maxAge: 1 });
    res.redirect('/');
  }

authMarket.js

const MarketModel = require('../models/market.model.js');
const jwtmarket = require('jsonwebtoken');
const { signUpErrors, signInErrors } = require('../utils/errors.utils');
const maxAge = 2 * 24 * 60 * 60 * 1000;

const createToken = (id) => {
    return jwtmarket.sign({id}, process.env.TOKEN_SECRET_MARKET, {
      expiresIn: maxAge
    })
  };

  module.exports.signUp = async (req, res) => {
    const { nom, email, password, phoneNumber} = req.body;
  
    try {
      const market = await MarketModel.create({ nom, email, password, phoneNumber});
      res.status(201).json({ market: market._id });
    } catch (err) {
      const errors = signUpErrors(err);
      res.status(200).json({ errors });
    }

  };

module.exports.signIn = async (req, res) => {
    const { email, password } = req.body;
  
    try {
      const market = await MarketModel.login(email, password);
      const tokenk = createToken(market._id);
      res.cookie('jwt2', tokenk, { httpOnly: true, maxAge });
      res.status(200).json({ market: market._id})
      console.log(tokenk);
    } catch (err){
      const errors = signInErrors(err);
      res.status(200).json({ errors });
    }
  }

module.exports.logout = (req, res) => {
    res.cookie('jwt2', '', { maxAge: 1 });
    res.redirect('/');
  }

authmiddleware.js

const UserModel = require("../models/user.model");
const MarketModel = require("../models/market.model");
const jwt = require("jsonwebtoken");
const jwtmarket = require("jsonwebtoken");

module.exports.checkUser = (req, res, next) => {
  const token = req.cookies.jwt;
  if (token) {
    jwt.verify(token, process.env.TOKEN_SECRET, async (err, decodedToken) => {
      if (err) {
        res.locals.user = null;
        next();
      } else {
        let user = await UserModel.findById(decodedToken.id);
        res.locals.user = user;
        next();
      }
    });
  } else {
    res.locals.user = null;
    next();
  }
};

module.exports.checkMarket = (req, res, next) => {
  const tokenk = req.cookies.jwtmarket;
  if (tokenk) {
    jwtmarket.verify(tokenk, process.env.TOKEN_SECRET_MARKET, async (err, decodedToken) => {
      if (err) {
        res.locals.market = null;
        next();
      } else {
        let market = await MarketModel.findById(decodedToken.id);
        res.locals.market = market;
        next();
      }
    });
  } else {
    res.locals.market = null;
    next();
  }
};

module.exports.requireAuth = (req, res, next) => {
  const token = req.cookies.jwt;
  if (token) {
    jwt.verify(token, process.env.TOKEN_SECRET, async (err, decodedToken) => {
      if (err) {
        console.log(err);
        res.status(401).json({ message: "Unauthorized" });
      } else {
        console.log(decodedToken.id);
        next();
      }
    });
  } else {
    console.log("No token");
    res.status(401).json({ message: "Unauthorized" });
  }
};

module.exports.requireAuthMarket = (req, res, next) => {
  const tokenk = req.cookies.jwtmarket;
  if (tokenk) {
    jwtmarket.verify(tokenk, process.env.TOKEN_SECRET_MARKET, async (err, decodedToken) => {
      if (err) {
        console.log(err);
        res.status(401).json({ message: "Unauthorized" });
      } else {
        console.log(decodedToken.id);
        next();
      }
    });
  } else {
    console.log("No token jwt2");
    res.status(401).json({ message: "Unauthorized" });
  }
};

App.js

import React, { useEffect, useState } from 'react';
import Routes from "./components/Routes/index";
import { UidContext } from './components/AppContext';
import { MidContext } from './components/AppContext';
import axios from 'axios';
import { useDispatch } from 'react-redux';
import { getUser } from './actions/user.actions';
import { getMarket } from './actions/market.actions';
import MyRoutes from './components/Routes/MyRoutes';



const App = () => {
  const [uid,setUid] = useState(null);
 
const dispatch = useDispatch();

const [mid,setMid] = useState(null);

useEffect(() => {
  const fetchToken = async () => {
    await axios({
      method: "get",
      url: `${process.env.REACT_APP_API_URL}jwtid`,
      withCredentials: true,
    })
      .then((res) => {
        setUid(res.data);
      })
      .catch((err) => console.log("No token/jeton"));
  };
  fetchToken();

  if (uid) dispatch(getUser(uid));
}, [uid,dispatch]);


useEffect(() => {
  const fetchToken = async () => {
    await axios({
      method: "get",
      url: `${process.env.REACT_APP_API_URL}jwt2id`,
      withCredentials: true,
    })
      .then((res) => {
        setMid(res.data);
      })
      .catch((err) => console.log("No token/jeton"));
  };
  fetchToken();
  if (mid) dispatch(getMarket(mid));
}, [mid, dispatch]);
console.log(mid+"trueeeeeee");

  return (
    <>
   <UidContext.Provider value={uid}>
  <MidContext.Provider value={mid}>
    <Routes />
  </MidContext.Provider>
</UidContext.Provider>
<MidContext.Provider value={mid}>
    <MyRoutes />
  </MidContext.Provider>
    </>
   
  );
};

export default App;

whenever I make a connection as a market I receive on the No token jwt2 console yet the token is created which translates that the checkAuthMarket check failed, but as a user it works well

RROR TypeError: Cannot read properties of undefined (reading ‘x’) – polygon fabric

I was trying to convert this code which is from the github gist into an angular app and updated the code which as you can see below , the github code gist works fine but when I tried to convert to angular typescript the editpolygon does not seem to work.

The editing of polygon is the main issue with the polygonPositionHandler and anchorWrapper.

Anyone has an idea how and why ? would be much appreciated.

–>> this is the link of the original code which works fine.
https://gist.github.com/restureese/25c75890d20db0b603a692d931e348b4

#ts code

import { AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
const fabric = require("fabric").fabric;
// import { fabric } from "fabric";

class CustomPolygonControl extends fabric.Control {
  pointIndex: number;

  constructor(options: any, pointIndex: number) {
    super(options);
    this.pointIndex = pointIndex;
  }
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements  OnInit, AfterViewInit {
  
  activeLine: any;
  activeShape: any;
  canvas: any;
  lineArray: any[] = [];
  pointArray: any[] = [];
  drawMode = false;
  pointIndex: any;

  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    this.initCanvas();
  }

  initCanvas() {
    this.canvas = new fabric.Canvas('c');
    this.canvas.setHeight(720);
    this.canvas.setWidth(1280);
    const imageUrl = "https://wpmedia.roomsketcher.com/content/uploads/2021/12/14164614/RoomSketcher-House-Floor-Plans-2452430-800.jpg";

    this.canvas.setBackgroundImage(imageUrl, this.canvas.renderAll.bind(this.canvas), {
      backgroundImageOpacity: 0.5,
      backgroundImageStretch: true
    });

    this.canvas.on('mouse:down', (options: any) => this.onMouseDown(options));
    this.canvas.on('mouse:up', () => this.onMouseUp());
    this.canvas.on('mouse:move', (options: any) => this.onMouseMove(options));
    this.canvas.on('object:moving', (option: any) => this.onObjectMove(option));
  }

  onMouseDown(options: any) {
    if (this.drawMode) {
      if (options.target && options.target.id === this.pointArray[0].id) {
        this.generatePolygon(this.pointArray);
      } else {
        this.addPoint(options);
      }
    }

    const evt = options.e;
    if (evt.altKey === true) {
      this.canvas.isDragging = true;
      this.canvas.selection = false;
      this.canvas.lastPosX = evt.clientX;
      this.canvas.lastPosY = evt.clientY;
    }
  }

  onMouseUp() {
    this.canvas.isDragging = false;
    this.canvas.selection = true;
  }

  onMouseMove(options: any) {
    if (this.canvas.isDragging) {
      const e = options.e;
      this.canvas.viewportTransform[4] += e.clientX - this.canvas.lastPosX;
      this.canvas.viewportTransform[5] += e.clientY - this.canvas.lastPosY;
      this.canvas.requestRenderAll();
      this.canvas.lastPosX = e.clientX;
      this.canvas.lastPosY = e.clientY;
    }
    if (this.drawMode) {
      if (this.activeLine && this.activeLine.class === 'line') {
        const pointer = this.canvas.getPointer(options.e);
        this.activeLine.set({
          x2: pointer.x,
          y2: pointer.y
        });
        const points = this.activeShape.get('points');
        points[this.pointArray.length] = {
          x: pointer.x,
          y: pointer.y,
        };
        this.activeShape.set({
          points
        });
      }
      this.canvas.renderAll();
    }
  }

  onObjectMove(option: any) {
    const object = option.target;
    object._calcDimensions();
    object.setCoords();
    this.canvas.renderAll();
  }

  toggleDrawPolygon() {
    if (this.drawMode) {
      this.activeLine = null;
      this.activeShape = null;
      this.lineArray = [];
      this.pointArray = [];
      this.canvas.selection = true;
      this.drawMode = false;
    } else {
      this.canvas.selection = false;
      this.drawMode = true;
    }
  }

  addPoint(options: any) {
    const pointOption = {
      id: new Date().getTime(),
      radius: 5,
      fill: '#ffffff',
      stroke: '#333333',
      strokeWidth: 0.5,
      left: options.e.layerX / this.canvas.getZoom(),
      top: options.e.layerY / this.canvas.getZoom(),
      selectable: false,
      hasBorders: false,
      hasControls: false,
      originX: 'center',
      originY: 'center',
      objectCaching: false,
    };
    const point = new fabric.Circle(pointOption);

    if (this.pointArray.length === 0) {
      point.set({
        fill: 'red'
      });
    }

    const linePoints = [
      options.e.layerX / this.canvas.getZoom(),
      options.e.layerY / this.canvas.getZoom(),
      options.e.layerX / this.canvas.getZoom(),
      options.e.layerY / this.canvas.getZoom(),
    ];
    const lineOption = {
      strokeWidth: 2,
      fill: '#999999',
      stroke: '#999999',
      originX: 'center',
      originY: 'center',
      selectable: false,
      hasBorders: false,
      hasControls: false,
      evented: false,
      objectCaching: false,
    };
    const line = new fabric.Line(linePoints, lineOption);

// Set a custom property 'customClass' on the line object
      (line as any).customClass = 'line';


    if (this.activeShape) {
      const pos = this.canvas.getPointer(options.e);
      const points = this.activeShape.get('points');
      points.push({
        x: pos.x,
        y: pos.y
      });
      const polygon = new fabric.Polygon(points, {
        stroke: '#333333',
        strokeWidth: 1,
        fill: '#cccccc',
        opacity: 0.3,
        selectable: false,
        hasBorders: false,
        hasControls: false,
        evented: false,
        objectCaching: false,
      });
      this.canvas.remove(this.activeShape);
      this.canvas.add(polygon);
      this.activeShape = polygon;
      this.canvas.renderAll();
    } else {
      const polyPoint = [{
        x: options.e.layerX / this.canvas.getZoom(),
        y: options.e.layerY / this.canvas.getZoom(),
      }];
      const polygon = new fabric.Polygon(polyPoint, {
        stroke: '#333333',
        strokeWidth: 1,
        fill: '#cccccc',
        opacity: 0.3,
        selectable: false,
        hasBorders: false,
        hasControls: false,
        evented: false,
        objectCaching: false,
      });
      this.activeShape = polygon;
      this.canvas.add(polygon);
    }

    this.activeLine = line;
    this.pointArray.push(point);
    this.lineArray.push(line);

    this.canvas.add(line);
    this.canvas.add(point);
  }

  generatePolygon(pointArray: any) {
    const points = [];
    for (const point of pointArray) {
      points.push({
        x: point.left,
        y: point.top,
      });
      this.canvas.remove(point);
    }
  
    for (const line of this.lineArray) {
      this.canvas.remove(line);
    }
  
    this.canvas.remove(this.activeShape).remove(this.activeLine);
  
    const polygon = new fabric.Polygon(points, {
      stroke: '#0084ff',
      fill: 'black',
    });
    this.canvas.add(polygon);
  
    this.toggleDrawPolygon();
    this.editPolygon();
  }


  polygonPositionHandler(dim : any, finalMatrix : any, fabricObject : any) {
    var x = (fabricObject.points[this.pointIndex].x - fabricObject.pathOffset.x),
          y = (fabricObject.points[this.pointIndex].y - fabricObject.pathOffset.y);
      return fabric.util.transformPoint(
          { x: x, y: y },
    fabric.util.multiplyTransformMatrices(
      fabricObject.canvas.viewportTransform,
      fabricObject.calcTransformMatrix()
    )
      );
  }

  actionHandler(eventData: any, transform: any, x: any, y: any) {
    const polygon = transform.target;
    const currentControl = polygon.controls[polygon.__corner];
    const mouseLocalPosition = polygon.toLocalPoint(new fabric.Point(x, y), 'center', 'center');
    const polygonBaseSize = polygon._getNonTransformedDimensions();
    const size = polygon._getTransformedDimensions(0, 0);
    const finalPointPosition = {
      x: mouseLocalPosition.x * polygonBaseSize.x / size.x + polygon.pathOffset.x,
      y: mouseLocalPosition.y * polygonBaseSize.y / size.y + polygon.pathOffset.y
    };
    polygon.points[currentControl.pointIndex] = finalPointPosition;
    return true;
  }

  anchorWrapper(anchorIndex: any, fn: any) {
    return (eventData: any, transform: any, x: any, y: any) => {
      const fabricObject = transform.target;
      const point = new fabric.Point(
        fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x,
        fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y
      );
      const absolutePoint = fabric.util.transformPoint(point, fabricObject.calcTransformMatrix());
      const actionPerformed = fn(eventData, transform, x, y);
      const newDim = fabricObject._setPositionDimensions({});
      const polygonBaseSize = fabricObject._getNonTransformedDimensions();
      const newX = (fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x) / polygonBaseSize.x;
      const newY = (fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y) / polygonBaseSize.y;
      fabricObject.setPositionByOrigin(absolutePoint, newX + 0.5, newY + 0.5);
      return actionPerformed;
    };
  }

 

  editPolygon() {
    let activeObject =  this.canvas.getActiveObject();
    if (!activeObject) {
        activeObject =  this.canvas.getObjects()[0];
        this.canvas.setActiveObject(activeObject);
    }

    activeObject.edit = true;
    activeObject.objectCaching = false;

    const lastControl = activeObject.points.length - 1;
    activeObject.cornerStyle = 'circle';
    activeObject.controls = activeObject.points.reduce((acc:any,index:any) => {
        acc['p' + index] = new fabric.Control({
            positionHandler: this.polygonPositionHandler,
            actionHandler: this.anchorWrapper(index > 0 ? index - 1 : lastControl, this.actionHandler),
            actionName: 'modifyPolygon',
            pointIndex: index,
        });
        return acc;
    }, {});

    activeObject.hasBorders = false;
    this.canvas.requestRenderAll();
}

  resizePolygon() {
    let activeObject = this.canvas.getActiveObject();
    if (!activeObject) {
      activeObject = this.canvas.getObjects()[0];
      this.canvas.setActiveObject(activeObject);
    }

    activeObject.edit = false;
    activeObject.objectCaching = false;
    activeObject.controls = fabric.Object.prototype.controls;
    activeObject.cornerStyle = 'rect';
    activeObject.hasBorders = true;

    this.canvas.requestRenderAll();
  }

  clearPolygon() {
    this.canvas.remove(...this.canvas.getObjects());
  }
}

#html code

<div>
  <button type="button" (click)="toggleDrawPolygon()">Draw Polygon</button>
  <button type="button" (click)="editPolygon()">Edit Polygon</button>
  <button type="button" (click)="resizePolygon()">Resize/Move Polygon</button>
  <button type="button" (click)="clearPolygon()">Clear</button>
</div>

<canvas id="c"></canvas>

How should you fix “Do not nest ternary expressions” for rendering components conditionaly

The code below, eslint raises some error

{authModal.mode === 'login' ? <Login /> : authModal.mode === 'register' ? <SignUp /> : <ForgotPassword />}

Error: Do not nest ternary expressions. eslint(no-nested-ternary)

I have come up with 3 ways not to get the error:

  1. check for each case
{authModal.mode === 'login' && <Login />}
{authModal.mode === 'register' && <SignUp />}
{authModal.mode === 'forgotPassword' && <ForgotPassword />}
  1. if/else inside function
{(() => {
  if (authModal.mode === 'login') {
    return <Login />;
  }
  if (authModal.mode === 'register') {
    return <SignUp />;
  }
  return <ForgotPassword />;
})()}
  1. switch case inside function
{(() => {
  switch (authModal.mode) {
    case 'login':
      return <Login />;
    case 'register':
      return <SignUp />;
    case 'forgotPassword':
      return <ForgotPassword />;
    default:
      throw new Error('Invalid auth mode');
  }
})()}

I’m new to JS and want to know how people would deal with this. If some of my solutions should be avoided please let me know. Other solutions are also appreciated!

In Express, how to send CSV data to a React Js Client from a large table of a Postgresql database? [closed]

I am currently working on a project that contains 160 million rows in a table. Directly fetching the data and converting it to CSV using sequilize Table.findAll() results in heap out of memory errors.

How should I efficiently provide CSV export to the client.

I am currently trying to implement stream to get data in chunks and create a csv in it, but not able to do it.

Note:
The CSV generated through dbeaver is of 50MB size.
Frontend: React
Backend: ExpressJs with Sequelize
Database: Postgresql

How do I make useEffect run every time a variable stored with useRef is changed?

I am trying to have useEffect run every time it changes a variable, but changes to the variable are lost on every re-render.

If I try to store the variable between renders using useRef, useEffect doesn’t run because it cannot detect changes to a ref. I found an article that shows how to effectively pass a ref to useEffect but I am not sure how to use this in the context of my problem.

here is my code where a ref is passed to useEffect:

import { useRef, useEffect, useLayoutEffect } from "react";
import "./styles.css";

export default function App() {
  const divOffset = useRef(0);
  let scrollPosition = 0;

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  });

  useLayoutEffect(() => {
    divOffset.current = linearInterpolation(
      divOffset.current,
      scrollPosition,
      0.07
    );
    divOffset.current = Math.floor(divOffset.current * 100) / 100;
    document.querySelector(
      "#main"
    ).style.transform = `translateX(-${divOffset.current}px);`;
  }, [scrollPosition]);

  const handleScroll = (event) => {
    scrollPosition = window.scrollY;
  };

  function linearInterpolation(x1, x2, easingValue) {
    return (1 - easingValue) * x1 + easingValue * x2;
  }

  return (
    <div id="main">
      <div className="layer1" />
      <div className="layer2" />
      <div className="layer3" />
    </div>
  );
}

Firebase Deploy Unexpected Error – How to Resolve? [An unexpected error has occurred.] [TypeError: Cannot read properties of null (reading ‘match’)]

Hello StackOverflow community,

I have been encountering an unexpected error while trying to deploy my project using Firebase. The error occurred suddenly; everything was working fine until August 28th. Here is the background and the error message I received:

Background:

  • Project Name: LINE-shift
  • Firebase Project ID: line-shift
  • Deployment command: firebase deploy
  • Firebase tools version: Latest (as of September 19, 2023)
  • Additional actions taken: PC reboot

Error Message:

=== Deploying to 'line-shift'...
i  deploying storage, firestore, functions, hosting
i  firebase.storage: checking storage.rules for compilation errors...
✔  firebase.storage: rules file storage.rules compiled successfully
i  firestore: reading indexes from firestore.indexes.json...
i  cloud.firestore: checking firestore.rules for compilation errors...
✔  cloud.firestore: rules file firestore.rules compiled successfully
i  functions: preparing codebase default for deployment
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
i  artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔  functions: required API cloudbuild.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
✔  artifactregistry: required API artifactregistry.googleapis.com is enabled
i  functions: Loading and analyzing source code for codebase default to determine what to deploy
Serving at port 8875
shutdown requested via /__/quitquitquit
Error: An unexpected error has occurred.

Debug Information:

I also ran the deploy command with the --debug option to get more details. The debug log is quite extensive, including various API calls and their responses. Here is a snippet of the debug log around the time the error occurred:

... 
[debug] [2023-09-19T01:45:05.303Z] Could not find functions.yaml. Must use http discovery 
[debug] [2023-09-19T01:45:05.307Z] Found firebase-functions binary at '/Users/User2/Desktop/Desktop/LINE-shift/node_modules/.bin/firebase-functions' 
[info] Serving at port 8149 
[debug] [2023-09-19T01:45:05.478Z] Got response from /__/functions.yaml {"endpoints":{"server":{"platform":"gcfv1","availableMemoryMb":null,"timeoutSeconds":null,"minInstances":null,"maxInstances":null,"ingressSettings":null,"serviceAccountEmail":null,"vpc":null,"region":[null],"httpsTrigger":{},"entryPoint":"server"}},"specVersion":"v1alpha1","requiredAPIs":[]} 
[info] shutdown requested via /__/quitquitquit 
[debug] [2023-09-19T01:45:10.643Z] TypeError: Cannot read properties of null (reading 'match') at resolveString (/opt/homebrew/lib/node_modules/firebase-tools/lib/deploy/functions/params.js:31:27) at /opt/homebrew/lib/node_modules/firebase-tools/lib/deploy/functions/params.js:47:36 at Array.map (<anonymous>) at Object.resolveList (/opt/homebrew/lib/node_modules/firebase-tools/lib/deploy/functions/params.js:47:21) at toBackend (/opt/homebrew/lib/node_modules/firebase-tools/lib/deploy/functions/build.js:180:30) at Object.resolveBackend (/opt/homebrew/lib/node_modules/firebase-tools/lib/deploy/functions/build.js:73:23) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async prepare (/opt/homebrew/lib/node_modules/firebase-tools/lib/deploy/functions/prepare.js:68:62) at async chain (/opt/homebrew/lib/node_modules/firebase-tools/lib/deploy/index.js:38:9) at async deploy (/opt/homebrew/lib/node_modules/firebase-tools/lib/deploy/index.js:95:5) 
[error] 
[error] Error: An unexpected error has occurred. 

Despite these efforts, the issue persists. I am looking for guidance on how to resolve this unexpected error. Has anyone faced a similar issue or can provide insights on what might be going wrong here?

Thank you in advance for your help!

What I have tried:
Updating Firebase tools to the latest version
Rebooting my PC

Transfer csv data from computer to html website to python file

I’m working on a project right now that I finished in python, but I want to upload it to the web. It requires csv inputs, and I’m having trouble transferring the data from the html page I’ve created to the python file. I’m currently using pyscript, and I’ve found out how to convert the contents of the csv file into strings using javascript, but I don’t know how to either call the python function from within a javascript function that gathers all these strings or how to call these javascript functions inside my python file. Any help would be greatly appreciated!

I’ve tried calling the javascript functions in the python file and the python functions in the javascript file, but errors pop up saying the fucntions are undefined. Most likely there’s some syntax I’m missing but I can’t find it for the life of me.

How to correctly implement different views for Desktop and Mobile views

I’m new to NextJS. Currently using NextJS 13. Previously Iv been using ReactJS like 4,5 years. I mostly use responsive media queries from CSS, if possible. But thing not always work like that. Desktop and Mobile view are usually too different to handle via media queries, even showing data different sometimes. So my previous layout was like

/app
    /components
        /Button
        /Input
        /Drawer
    /pages
        /products
            /_desktop
                index.tsx
            /_mobile
                index.tsx
            /[slug]
                /_desktop
                    index.tsx
                /_mobile
                    index.tsxt
        /stores
            index.tsx
                /[id]
                    /_desktop
                        /index.tsx
                    /_mobile
                        /index.tsx

As you can see /products page have different folders desktop and mobile, because their looking is very different. but stores page have single index, because UI somehow done via CSS regardless viewer device. But then store detail page (id) have different views etc.

In index.tsx file I could use my own helper function isMobile(). Basically it listens window resizing and it’s width. If screen width is lesser than 992px it returns true, else returns false.

Now in NextsJS 13, I no longer can do it because of server component sends every content sending to client must be same (called hydration issue?). Also on server side, it doesnt have attribute like window.width.

So currently I’m using this method

<div className="hideDestkop">
    <MobileHeader />
<div>
<div className="hideMobile">
    <DesktopHeader />
<div>


.hideDesktop {
  @media (min-width: 992px) {
    display: none !important;
  }
}

.hideMobile {
  @media (max-width: 991px) {
    display: none !important;
  }
}

As you can see It sends everything to client regardless viewer device, then hides some of them depending on viewers device width. You already guessed downside of it. Lot of non used hidden elements in browser. I don’t want use middleware or something for user-agent, unless it’s only solution. Because current days, phones are so advanced, some even higher resolution than old monitors. Is there proper way to implement it?

How to handle multiple input field which is rendered using map method, with react-redux?

I have a product list(without quantity) in json-server and fetch using react-redux and rendered in table. I also have a input field to get quantity from user to calculate the total by mutiplying product price(from json-server) with product quantity(from input field).

The total field in list showing NaN. I guess the problem is with qty. How to avoid the error? how to initialise initial state to 0 for all input field in table?

import FormInput from './Components/FormInput';
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { fetchList } from './Components/Store/action';
function App() {

  const { list } = useSelector((state) => state.list)
  const dispatch = useDispatch()
  const [qty, setQty] = useState({})
 
  const handleChange = (e) => {
    e.preventDefault()
    const { name, value } = e.target;
    setQty({
      ...qty,
      [name]:value 
    });
  }


  useEffect(() => {
    dispatch(fetchList())
  }, [dispatch])


  let sum = 0

  list.forEach((item) => {
    sum += item.price * qty[item.name]
  })


  const submitHandler = (e) => {
    e.preventDefault()
  }

  return (
    <div >
      <form onSubmit={submitHandler}>
        <table>
          <thead>
            <tr>
              <th>S.no</th>
              <th>Name</th>
              <th>Unit</th>
              <th>price</th>
              <th>Quantity</th>
              <th>total</th>
            </tr>
          </thead>
          <tbody>
            {list.map((item) => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.name}</td>
                <td>{item.unit}</td>
                <td>{item.price}</td>
                <td>
                  <FormInput
                    type="number"
                    name={item.name}
                    handleChange={handleChange}
                    value={qty[item.name]} 
                  />
                </td>
                <td>{item.price * qty[item.name]}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <button type='submit'>Submit</button>
      </form>
      <h1>total:{sum}</h1>
    </div>
  );
}

export default App;

I tried to set initial state for qty. i expect the all input fields to be a number 0 instead of string or undefined