Use rejectWithValue to send original error object to middleware

I have a middleware that specificly reacts on two types of status codes of requests. Also I have a bunch of thunks that looks like this:

const updateUser = createAsyncThunk(
  'users/update',
  async (userData, { rejectWithValue }) => {
    const { id, ...fields } = userData
    try {
      const response = await userAPI.updateById(id, fields)
      return response.data.user
    } catch (error) {
      return rejectWithValue({ ...error.response.data, status: error.response.status })
    }
  },
)

I use rejectWithValue to send status code into middleware. But I littlebit confused and don’t know, is it a good practive to use such construction with try catch and rejectWithValue in every request or there is some better solution?

How to prevent hiding plotly chart bar on chart legend click

How to prevent hiding plotly chart bar on chart legend click in an angular application.

   <plotly-plot
        [divId]="graph.selectedGraph.name"
        [data]="graph.selectedGraph.data"
        [config]="graph.selectedGraph.config"
        [layout]="graph.selectedGraph.layout"
        (relayout)="draggedShape($event)"
        [ngClass]="{ 'single-data': graph.data && graph.data.length === 1 }"
        (legendClick)="launchColorPicker($event); $event.stopPropagation()"
      >
      </plotly-plot>

Next 14 hydration error when using custom isMobile hook

For a long time, I’ve been using a custom react hook called useIsMobile that returns true if the viewport is under a specific width. I used this hook in all my projects and I never had an issue with it.

Recentlly I started a new project using Next 14 and I started to get this error:
Error: Text content does not match server-rendered HTML. See more info here: https://nextjs.org/docs/messages/react-hydration-error

After some debugging, I realize that the issue is with my custom hook. When I’m using the hook, the server sends the “mobile version” first but the client renders the “desktop version” as it should and creates a difference between the react tree that was pre-rendered from the server and the react tree that was rendered during the first render.

This issue persists even if I use ‘use client’.
I’ve also noticed that occasionally, the error can be triggered by CSS media queries, or they might be outright ignored.

Did anyone else encounter this issue? Does anyone know how I can fix this?

This is the hook that I use:

'use client';
import { useState, useEffect } from 'react';

const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: typeof window !== 'undefined' ? window?.innerWidth : null,
    height: typeof window !== 'undefined' ? window?.innerHeight : null,
  });

  useEffect(() => {
    const handleResize = () => {
      if (typeof window !== 'undefined') {
        setWindowSize({
          width: window?.innerWidth,
          height: window?.innerHeight,
        });
      }
    };

    window?.addEventListener('resize', handleResize);

    handleResize();

    return () => window?.removeEventListener('resize', handleResize);
  }, []);

  return windowSize;
};

export default useWindowSize;
'use client';
import { useState, useEffect } from 'react';
import useWindowSize from './useWindowSize';

const useIsMobile = (breakpoint: number = 768): boolean => {
  const { width } = useWindowSize()!;
  const [isMobile, setMobile] = useState<boolean>(
    width! <= (breakpoint || 768)
  );

  useEffect(() => {
    setMobile(width! <= (breakpoint || 768));
  }, [width, breakpoint]);

  return isMobile;
};

export default useIsMobile;
  const isMobile = useIsMobile(500);

  return (
    <div className={styles.nav}>
      {!isMobile && <div className={styles.logo}>Logo</div>}

Playwright angular application : When i trying to save click button getting invalid form / Reference Error: page is not defined

click events are correctly triggering other actions but encountering issues specifically with the save button resulting in an “invalid form” message

async fillCustomerForm(customerData) {
this.logger.info(‘Filling customer details’);

    try {
        // Wait for the file input element to be visible
        await this.page.waitForSelector("#fileInput");

        // Set the file input (assuming the file path is correct)
        await this.page.setInputFiles("#fileInput", "C:\Users\sathishd\Downloads\EtihadAirways.jpg");
        await this.page.waitForTimeout(2000);

        // Fill in the form inputs and select dropdown options
        await this.page.fill('(//input[@id="organizationName"])[1]', customerData.customerName);
        await this.page.getByLabel('Short Name').click();
        await this.page.getByLabel('Short Name').fill('SPR');
       // await this.page.fill("(//input[@id='shortName'])[1]", customerData.shortName);
        await this.page.fill("(//input[@id='shortName'])[2]", customerData.customerECode);
        await this.page.selectOption("(//select[@id='opucode dropdown-toggle'])[2]", customerData.customerType);
        await this.page.waitForTimeout(2000);
        await this.page.fill("(//input[@type='text'])[5]", customerData.ICAO);
        await this.page.fill("(//input[@type='text'])[6]", customerData.IATA);
        await this.page.waitForTimeout(2000);

        // Click on the date picker input and set the date
        await this.page.click('#ej2-datepicker_0 input');
        await this.page.fill("(//input[@id='ej2-datepicker_0_input'])[1]", customerData.InductionDate);

        // Select user-defined category from a dropdown
        await this.page.selectOption("(//select[@id='opucode dropdown-toggle'])[3]", customerData.userdefinedCategory);
        await this.page.waitForTimeout(2000);

        try {
            // Wait for the save button to be visible and clickable
            
            await this.page.waitForSelector('button:has-text("Save")', { visible: true, timeout: 5000 });
            
            // Click the save button
            //await this.page.click('button:has-text("Save")');
            await this.page.getByRole('button', { name: 'Save' }).first().click({ force: true });
           // await page.getByRole('button').click({ force: true });
            this.logger.info('Save button clicked successfully');
        } catch (error) {
            this.logger.error(`Error clicking save button: ${error}`);
        
            // Attempt to capture a screenshot for debugging
            try {
                const screenshotPath = 'C:/sathish/AiDocx_Automation_Plywrt02/screenshot/save_button_error.png';
                await this.page.screenshot({ path: screenshotPath });
                this.logger.info(`Screenshot captured: ${screenshotPath}`);
            } catch (screenshotError) {
                this.logger.error(`Error capturing screenshot: ${screenshotError}`);
            }
        }

How to prevent image loading after it’s already loaded in dom in react

enter image description here

these images are already cached by the browser and also we have implemented caching of the image URL in indexdb.

in order to improve the user experience we are facing an image flickering issue on the listing page of our react project.

is there any solution to this image flickering issue
expectation:- if image is already loaded the image should be immediately rendered on dom instead of after loading

getting unauthorized 401 error in MERN app

I am developing a web app on MERN stack blog app, I have developed the backend API in render, frondend in vercel and they are working fine on postman and working fine in localhost. The problem is when I’m connecting backend with frontend and after giving a post request -adding a new comment to a post it failed with 401 anauthorized,its not working on deployment but working right at local machine. Whenever I’m running this it shows unauthorized 401 error. Here’s the code I don’t know what I’m doing wrong. What I could figure out from reading the error is that the problem is in auth some axios like error code, it shows error name as 401 unauthorized.

Here is the error image:-

enter image description here

This is my front end code

import { useNavigate, useParams } from "react-router-dom"
import Comment from "../components/Comment"
import Footer from "../components/Footer"
import Navbar from "../components/Navbar"
import {BiEdit} from 'react-icons/bi'
import {MdDelete} from 'react-icons/md'
import axios from "axios"
import { URL,IF } from "../url"
import { useContext, useEffect, useState } from "react"
import { UserContext } from "../context/UserContext"


const PostDetails = () => {

  const postId=useParams().id
  const [post,setPost]=useState({})
  const {user}=useContext(UserContext)
  const [comments,setComments]=useState([])
  const [comment,setComment]=useState("")
  // const [loader,setLoader]=useState(false)
  console.log(postId)
  const navigate=useNavigate()

  const fetchPost=async()=>{
    try{
      const res= await axios.get(URL+"/api/posts/"+postId)
      // console.log(res.data)
      setPost(res.data)
    }
    catch(err){
      console.log(err)
    }
  }

  useEffect(()=>{
    fetchPost()

  },[postId])

  // handle delete post
    const handleDeletePost=async ()=>{

    try{
      const res=await axios.delete(URL+"/api/posts/"+postId,{withCredentials:true})
      console.log(res.data)
      navigate("/")

    }
    catch(err){
      console.log(err)
    }

  }

  useEffect(()=>{
    fetchPost()

  },[postId])

  const fetchPostComments=async()=>{
    // setLoader(true)
    try{
      const res=await axios.get(URL+"/api/comments/post/"+postId,{withCredentials:true})
      setComments(res.data)
      // setLoader(false)

    }
    catch(err){
      // setLoader(true)
      console.log(err)
    }
  }

  useEffect(()=>{
    fetchPostComments()

  },[postId])

  const postComment=async(e)=>{
    e.preventDefault()
    try{
      const res=await axios.post(URL+"/api/comments/create",
      {comment:comment,author:user.username,postId:postId,userId:user._id},
      {withCredentials:true})
      console.log(res.data)
      fetchPostComments()
       setComment("")
       window.location.reload(true)

    }
    catch(err){
         console.log(err)
    }

  }
  
  return (
    <div>
        <Navbar/>
        <br/>
        <br/>
        <br/>
        <div className="px-8 md:px-[200px] mt-8">
            <div className="flex items-center justify-between">
                <h1 className="text-2xl font-bold text-black md:text-3xl">{post.title}</h1>
                <div className="flex items-center justify-center space-x-2">
                    <p className="cursor-pointer" onClick={()=>navigate("/edit/"+postId)}><BiEdit/></p>
                    <p className="cursor-pointer" onClick={handleDeletePost}><MdDelete/></p>
                </div>
            </div>
            <div className="flex items-center justify-between mt-2 md:mt-4">
            <p>@{post.username}</p>
            <div className="flex space-x-2">
                <p>{new Date(post.updatedAt).toString().slice(0,10)}</p>
                <p>{new Date(post.updatedAt).toString().slice(16,24)}</p>
            </div>
            </div>
            <img src={IF+post.photo} className="w-full mx-auto mt-8" alt=""/>
            <p className="mx-auto mt-8">{post.desc}</p>
            <div className="flex items-center mt-8 space-x-4 font-semibold">
                <p>Categories:</p>
                <div className="flex items-center justify-center space-x-2">
                    {post.categories?.map((c,i)=>(
                 <>
                <div key={i} className="px-3 py-1 bg-gray-300 rounded-lg">{c}</div>
                 </>
            
                   ))}
            
                 </div>
             </div>
                 <div className="flex flex-col mt-4">
                    <h3 className="mt-6 mb-4 font-semibold">Comments:</h3>
                    {/* comment */}
                      {comments?.map((c)=>(
                        <Comment key={c._id} c={c} post={post} />
                    ))}
                 </div>
                       {/* write a comment */}
                       <div className="flex flex-col mt-4 md:flex-row">
                         <input onChange={(e)=>setComment(e.target.value)} type="text" placeholder="write a comment" className="md:w-[90%] outline-none px-4 mt-4 md:mt-0"/>
                         <button onClick={postComment} className="bg-black text-sm text-white px-2 py-2 md:w-[20%] mt-4 md:mt-0">Add Comment</button>
                         <br/>
                       </div>
            </div>
        <Footer/>
    </div>
  )
}

export default PostDetails

This is my backend API file

where CREATE is the func. not working on deploy


const express=require('express')
const router = express.Router();
const User=require('../models/User')
const bcrypt=require('bcrypt')
const Post=require('../models/Post')
const Comment=require('../models/Comment');
const verifyToken = require('../verifyToken');


//CREATE
router.post("/create",verifyToken,async(req,res)=>{
  try{
     const newComment=new Comment(req.body)
     const savedComment=await newComment.save()
     res.status(200).json(savedComment)
  }
  catch(err){
    res.status(200).json(err)
  }
})


//UPDATE
router.put("/:id",verifyToken,async (req,res)=>{
    try{
       
        const updatedComment=await Comment.findByIdAndUpdate(req.params.id,{$set:req.body},{new:true})
        res.status(200).json(updatedComment)

    }
    catch(err){
        res.status(500).json(err)
    }
})

//DELETE
router.delete("/:id",verifyToken,async (req,res)=>{
    try{
        await Comment.findByIdAndDelete(req.params.id)
         res.status(200).json("Comment has been deleted!")

    }
    catch(err){
        res.status(500).json(err)
    }
})




//GET POST COMMENT
router.get("/post/:postId",async (req,res)=>{
    try{
        const comments=await Comment.find({postId:req.params.postId})
        res.status(200).json(comments)
    }
    catch(err){
        res.status(500).json(err)
    }
})



module.exports=router

this is my model code:-

const mongoose=require('mongoose')

const CommentSchema=new mongoose.Schema({
    comment:{
        type:String,
        required:true,
    },
    author:{
        type:String,
        required:true,
    },
    postId:{
        type:String,
        required:true,
    },
    userId:{
        type:String,
        required:true
    }
},{timestamps:true})

module.exports=mongoose.model("Comment",CommentSchema)

this is my server api code :-

const express=require('express')
const app=express()
const mongoose=require('mongoose')
const dotenv=require('dotenv')
const cors=require('cors')
const path=require("path")
const multer=require('multer')
const cookieParser=require('cookie-parser')
const authRoute=require('./routes/auth')
const userRoute=require('./routes/users')
const postRoute=require('./routes/posts')
const commentRoute = require("./routes/comment")
const ottRoute=require('./routes/ott')
const releaseRoute=require('./routes/release')
const responseRoute=require('./routes/response');
const ratingRoute=require('./routes/rating')

//database
const connectDB=async()=>{
    try{
        await mongoose.connect(process.env.MONGO_URL)
        console.log("database is connected successfully!")

    }
    catch(err){
        console.log(err)
    }
}

//middlewares
dotenv.config()
app.use(express.json())
app.use("/images",express.static(path.join(__dirname,"/images")))
app.use(cors({ origin: "http://localhost:5173", credentials: true }));
app.use(cookieParser())
app.use("/api/auth",authRoute)
app.use("/api/users",userRoute)
app.use("/api/posts",postRoute)
app.use("/api/comments", commentRoute)
app.use("/api/otts",ottRoute);
app.use("/api/releases",releaseRoute)
app.use("/api/responses",responseRoute)
app.use("/api/rating",ratingRoute)



//image upload
const storage=multer.diskStorage({
    destination:(req,file,fn)=>{
        fn(null,"images")
    },
    filename:(req,file,fn)=>{
        fn(null,req.body.img)
        // fn(null,"image1.jpg")
    }
})

const upload=multer({storage:storage})
app.post("/api/upload",upload.single("file"),(req,res)=>{
    res.status(200).json("Image has been uploaded successfully!")
})

app.listen(process.env.PORT,()=>{
    connectDB()
    console.log("app is running on port "+process.env.PORT)
})

and this is my verifyToken code:-

const jwt=require('jsonwebtoken')

const verifyToken=(req,res,next)=>{
    const token=req.cookies.token
    console.log(token)
    if(!token){
        return res.status(401).json("You are not authenticated!")
    }
    jwt.verify(token,process.env.SECRET,async (err,data)=>{
        if(err){
            return res.status(403).json("Token is not valid!")
        }
        
        req.userId=data._id
       
       console.log("passed")
        
        next()
    })
}

module.exports=verifyToken

For Referances:-
my backend gitcode
my frontend gitcode

I am trying to deploy my learning mern blog app project which is working in local machine. I need to host it such that able to perform Whole CRUD operations as in localhost.

How can I Filter Drive API list results by a domain with write permission

I am trying to get a list of files from the drive API with a service account, that allow a specific domain to edit them. I have it working for specific emails without issue, but I also need to be able to list them based on domains with write permission.

My query works as I expect when filtering by a specific email:

const query = `'some-id' in parents and '[email protected]' in writers`
const response = await DRIVE_API.files.list({
  q: query,
  fields: "files(id, name, mimeType, description)",
});
console.log("response.data:", response.data)

When I change the query to: const query = "'some-id' in parents and 'example.com' in writers and... The file list is empty.

I have verified that it should work by checking the permissions. Permissions on multiple files look like this:

permissions: [
    {
      id: '1234...',
      displayName: 'test',
      type: 'user',
      kind: 'drive#permission',
      emailAddress: '[email protected]',
      role: 'writer'
    },
    {
      id: '1234...',
      displayName: 'some name...',
      type: 'domain',
      kind: 'drive#permission',
      role: 'writer',
      domain: 'example.com'
    },
    ...

how can i use RNFirebase with expo-go

I have been attempting to use the modular firebase sdk with RN for quite some days now… just learned about react-native-firebase upon reading the docs, I found how to use it with regular bare react-native not with expo-go react native
I Have a Problem writing native code, any solutions using it please also give the code

I have tried using firebase sdk for auth and database, auth works fine, but database cant write…

where I write (to database)…

import React, {useEffect, useState} from 'react';
import { useUid } from '../Backend/UidContext';
import {Button, TextInput, View} from 'react-native';
import { getDatabase, ref, child, push, update } from "firebase/database";
import style from "../Style";

const Post = ({user}) => {
    const [post, setPost] = useState('');
    const [newPostAdded, setNewPostAdded] = useState(false);

    const Tuid = useUid();// Move the useUid hook call inside the component

    const uid = Tuid["uid"]

    function HandlePost(){
        const db = getDatabase();

        // A post-entry.
        const postData = {
            text: post,
        };

        // Get a key for a new Post.
        const newPostKey = push(child(ref(db), 'posts')).key;

        // Ensure the uid is a valid string before using it in the Firebase database reference
        if (typeof uid === 'string' && uid.length > 0) {
            // Remove invalid characters from the uid using a regular expression
            const sanitizedUid = uid.replace(/[^a-zA-Z0-9]/g, '');

            // Write the new post's data simultaneously in the posts list and the user's post list.
            const updates = {};
            updates['/posts/' + newPostKey] = postData;
            updates['/user-posts/' + sanitizedUid + '/' + newPostKey] = postData;

            update(ref(db), updates)
                .then(() => {
                    setPost('');
                    setNewPostAdded(true);
                });
            console.log('Updated')
        } else {
            console.error('Invalid uid:', uid);
        }
    }

    useEffect(() => {
        if (newPostAdded) {
            setNewPostAdded(false);
            // Perform any additional actions or update state variables to reset the component
        }
    }, [newPostAdded]);

    return (
        <View style={style.container}>
            <View>
                <TextInput
                    placeholder="Enter new post"
                    value={post}
                    onChangeText={setPost}
                />
                <Button title="Add Post" onPress={HandlePost}/>
            </View>
        </View>
    )
}

export default Post;

code for UID

const userCredential= await createUserWithEmailAndPassword(auth, email, password);
            console.log('User registered successfully!');
            isNotLoggedIn  = false;

            const firebaseUid = userCredential.user.uid;
            // You might want to setUid(firebaseUid) here as well if needed

            setUid(firebaseUid)

            // Example database operation
            const db = getDatabase();
            const postData = { user: firebaseUid };
            const updates = {};
            updates['/user-posts/' + firebaseUid + '/'] = postData;
            await update(ref(db),updates);

thanks for your help

When creating a custom ui node in Node-RED for Dashboard 2, where do i have to integrate the HTML Code?

I want to create a custom ui node for Dashboard 2 in Node-RED.

Where can I include my HTML code to be displayed on the dashboard? Do I need to integrate the code into the html or js file? Or is it necessary to create a new file?

Does anyone have experience with creating a custom UI node, whether dashboard or dashboard 2?

Is there a difference between the structure of Dashboard and Dashboard 2?

ChatGPT Polsku: Rewolucja w Świecie Sztucznej Inteligencji

your textWprowadzenie

your textW dzisiejszym dynamicznie rozwijającym się świecie, technologia staje się coraz bardziej nieodłączną częścią naszego codziennego życia. W tym kontekście narzędzia oparte na sztucznej inteligencji (SI) nabierają szczególnego znaczenia, przynosząc nowe możliwości i wyzwania. Wśród nich wyróżnia się wyjątkowa popularność serwisu ChatGPT Polsku, który dzięki przyjaznemu interfejsowi i innowacyjnemu podejściu do obsługi, zdobył uznanie użytkowników na całym świecie.

your textPodziel się z Tobą naszą wiedzą : ChatGPTPolsku
enter image description here

your textChatGPT Polsku: Innowacyjny Interfejs

your textGłównym atutem serwisu ChatGPT Polsku jest jego przyjazny interfejs, który sprawia, że korzystanie z niego staje się intuicyjne i przyjemne dla użytkowników w każdym wieku i na każdym poziomie doświadczenia. Zaprojektowany z myślą o maksymalnej użyteczności, interfejs umożliwia łatwą nawigację po serwisie oraz szybki dostęp do funkcji i treści. To sprawia, że nawet osoby niezaznajomione z zaawansowaną technologią mogą w pełni korzystać z możliwości, jakie oferuje ChatGPT Polsku.

your textSzybki System Reakcji

your textJednym z kluczowych elementów, który wyróżnia ChatGPT Polsku na tle innych podobnych serwisów, jest niezwykle szybki system reakcji chatbota. Dzięki zastosowaniu najnowszych osiągnięć w dziedzinie SI oraz zaangażowaniu eksperta ds. badań nad SI i dekodowania, Bengta Ariena, serwis ten zapewnia użytkownikom natychmiastową odpowiedź na ich pytania i potrzeby. To sprawia, że interakcja z chatbotem staje się nie tylko efektywna, ale także przyjemna i satysfakcjonująca.

your textZastosowanie w Różnych Obszarach

your textPopularność ChatGPT Polsku nie ogranicza się jedynie do jednej grupy użytkowników czy jednego konkretnego obszaru zastosowań. Dzięki swojej wszechstronności i elastyczności, serwis ten znajduje zastosowanie w różnych dziedzinach życia, od edukacji po biznes i rozrywkę. Może być wykorzystywany zarówno w celach naukowych do analizy tekstów czy generowania nowych pomysłów, jak i w codziennych sytuacjach, takich jak rozmowy towarzyskie czy pomoc w rozwiązywaniu problemów.

your textPodsumowanie

your textW świetle powyższych faktów nie sposób nie dostrzec ogromnego znaczenia, jakie ma serwis ChatGPT Polsku dla społeczności użytkowników na całym świecie. Jego przyjazny interfejs, szybki system reakcji oraz wszechstronne zastosowanie sprawiają, że stanowi on niezastąpione narzędzie w erze cyfrowej rewolucji. Dzięki ciągłemu rozwojowi i innowacjom, ChatGPT Polsku nie tylko spełnia, ale także przewyższa oczekiwania użytkowników, stając się prawdziwym pionierem w świecie sztucznej inteligencji.

your textInformacja :
your textAdres : Polna 8B,Bydgoszcz, Poland
your textNaród : Poland
your textMiasto : Bydgoszcz
your textKod pocztowy : 85-163
your textTelefon : +48 691-404-165
your textE-mail : [email protected]/[email protected]
your textMoja strona internetowa : https://chatgptpolsku.org/

your text#ChatGPTPolksu , #chatgptpolsku.org , #chatgptdarmo

got CORS type response using fetch api [closed]

I just wanted to know how requested response looks like before jsonifying it.

then i got:

enter image description here

code i wrote:

async function a(){
    fetch('https://jsonplaceholder.typicode.com/todos/')
      .then(response =>{
        console.log(response);
        return response.json()
      })
      .then(json => console.log(json))
  }
  a();
  • want to know why it causes cors error like this

React webiste showing blank screen with error on the console the server responded with a status of 404 ()

I have deployed my react wesite portfolio on Github and it is showing a blank screen with error in console ->Failed to load resource: the server responded with a status of 404 ()

and link to the repository/site is https://elochimombe.github.io/portfolio/
and the link to the githup is https://github.com/EloChimombe
and the name of repository is portfolio

I tried some solutions but I dont where am I failing

Does splice() always leave empty strings in place of the spliced elements, instead of cleanly removing them?

I am learning JS from SuperSimpleDev’s tutorial and got stuck.
I am confused about the functionality of splice(). Online I am only finding examples where splice() cleanly removes elements. But it’s leaving me with empty strings instead.

I have an array of to-do elements, and each to-do element has a delete button beside it, which, on being clicked, should disappear along with the to-do text. I logged my array on the console after splicing, and saw that I was getting left with [todo1, ”, ”, todo4] and so on. So the delete buttons were still being displayed (beside the empty string elements which I didn’t know were there) even though I had spliced those elements. The left behind delete buttons:

function renderTodoList() {
  const inputElement = document.querySelector('.js-name-input');
  const name = inputElement.value;

  todoList.push(name);

  let todoListHTML = '';

  for(let i=0; i<todoList.length; i++){
    const todo = todoList[i];
    const html = `
      <p>
        ${todo}
        <button onclick="
          todoList.splice(${i},1);
          renderTodoList();
        ">Delete</button>
      </p>
    `;
    todoListHTML += html;
  }

  console.log(todoListHTML);

  document.querySelector('.js-display-todo').innerHTML = todoListHTML;

  inputElement.value = '';

  console.log(todoList);
}