Data is lost on page refresh, Is there a way to persist data stored in database on page refresh

I am working on a commenting feature for a blog using latest version of NextJs.
Text input collects data, and sends it to the database ‘Vercel` hosted,
and I fetch the data from the frontend successfully as expected.

However, displaying the data in the frontend behaves as expected, but if user
refreshes the page the data gets lost for some reasons (pls see attached gif) – This behavior is not
expected as data is not persistent. Is this because this is a dynamic route in a page route app or perhaps the comments are displayed in a component rather than the actual page – Can you help figure this out? Thanks in advance.

//Dynamic Route  '/pages/blog/[slug].js'

import React, { useRef, useState, useEffect } from 'react';
import { getSinglePost, getPosts } from '../../lib/posts';
import { Button } from '@nextui-org/react';
import CommentBox from '../../components/Blogs/CommentBox';
import useSWR from 'swr';
import { useSession } from "next-auth/react";


const PostPage = ({ post }) => {
    const [postContent, setPostContent] = useState({
        id: post.id,
        title: post.title,
        content: post.html
    });
    const [comments, setComments] = useState([]);
    const [newComment, setNewComment] = useState('');
    const [value, setValue] = useState(0);

    const { data: session } = useSession();


    const handleCommentChange = (event) => {
        setNewComment(event.target.value);
    };


    //Access post.id and sets it as postId, and the using `SWR` to fetch data from the database
    const postId = post.id;
    const { data: commentsData, error } = useSWR(`/api/blog/commentsystem?postId=${postId}`);

    // Update comments state when data is fetched
    useEffect(() => {
        if (commentsData) {
            setComments(commentsData);

        }
    }, [commentsData]);

    // Function to handle form submission
    const handleSubmit = async (event) => {
        event.preventDefault();

        if (newComment.trim() !== '' && session) {
            setLoading(true);

            const user = session.user;

            const commentObject = {
                articleContent: newComment,
                user: user,
                date: new Date().toLocaleString(),
            };

            const { user: articleUser, name: articleEmail } = user;
            const title = post.title;

            try {
                const response = await fetch('/api/blog/commentsystem', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ user: articleUser, articleContent: newComment, email: articleEmail, postTitle: title, postId: postId })
                });

                if (!response.ok) {
                    throw new Error('Failed to post comment');
                }

                const responseData = await response.json();
                console.log("data from DB:", responseData);  // returns data as expected.

                setComments(prevComments => [...prevComments, responseData]);
                setNewComment('');
                setLoading(false);

            } catch (error) {
                console.error('Error posting comment:', error.message);
            }
        }
    };

    console.log("Comments data from DB:", comments);  // returns data as expected.

    return (
        <div>
           <span >
            {/* Component that displays comments takes in data set as state variable as a prop*/}
            < CommentBox comments={comments} />
            </span>
           <form onSubmit={handleSubmit}>
           <div >
            <div >
                <label htmlFor="comment" >Share your thoughts</label>
                <textarea
                    id="comment"
                    rows="4"
                    placeholder="Post comments..."
                    value={newComment}
                    onChange={handleCommentChange}
                    required
                />
            </div>
            <div >
                <button type="submit">
                    Post comment
                </button>
            </div>
            </div>
            </form>
        </div>
    );
};


//Function below gets 'post' from external api, and sets it as props
export async function getStaticPaths() {
    const allPosts = await getPosts();

    const paths = allPosts.map((post) => ({
        params: { slug: post.slug }
    }));

    return {
        paths,
        fallback: false
    };
}

export async function getStaticProps({ params }) {
    const post = await getSinglePost(params.slug);

    if (!post) {
        return {
            notFound: true
        };
    }

    return {
        props: { post }
    };
}

export async function generateMetadata({ params }) {
    const post = await getSinglePost(params.slug);
    return {
        title: post.title,
        description: post.excerpt,
        openGraph: {
            title: post.title,
            description: post.excerpt,
            images: [
                {
                    url: post.image,
                },
            ],
        },
    };
}

export default PostPage;
///////////////////////////////////
// Component
///////////////////////////////////

const CommentBox = ({ comments }) => {

    //comments is imported from the dynamic page as prop 

    console.log(comments);  // returns data as expected.
    return (
        <div>
            <div>
                {comments && comments.map((item, index) => {
                    return (
                        <div key={item.id}>
                            {Array.isArray(item.comments) && item.comments.map((comment, commentIndex) => (
                                <div key={comment.id}>
                                    {/* Render each comment */}
                                    {console.log(comment)}
                                    <div>
                                        {/* Render profile image */}
                                        <div>
                                            {/* Render comment author */}
                                            <div>
                                                <span>{comment.commentBy}</span>
                                            </div>
                                            {/* Render comment content */}
                                            <div>
                                                <p>{comment.comment}</p>
                                            </div>
                                            {/* Render posted time */}
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

export default CommentBox;

Why is my SQL table only showing one one row with null columns after I run this code?

const db = require('./db');
const { createHash } = require('crypto');

async function registerUser(user, pass, email) {
    if (pass.includes('?') || pass.includes(''') || pass.includes('"')) {
        return false;
    }

    const salt = makeSalt(16);
    console.log("salt: " + salt);
    var hash = salt.concat(pass);
    console.log("salt and pass: " + hash);
    hash = createHash('sha256').update(hash).digest('hex');
    console.log(hash);

    try {
        await db.query('INSERT INTO users (user, salt, hash, email) VALUES (?,?,?,?)', [user, salt, hash, email]);
        console.log("User registered successfully");
    } catch (error) {
        console.error("Error registering user:", error);
    }
}

function makeSalt(length) {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@!#$&_';
    const charactersLength = characters.length;
    let counter = 0;
    while (counter < length) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
        counter += 1;
    }
    return result;
}

// Example usage
registerUser("test", "spacefort66", "[email protected]");

I tried setting all database columns to different values (they are all currently set to VARCHAR), I am expecting a row with the user name, salt, hash, and then the email.

Shadow root bypass by Html Agility Pack c#

Can someone help i tried to take some values from another site and use for it Html Agility Pack all work for moment, that it not show all values and then i check and saw shadow-root(open), how i can bypass it?

        public static String Test() {
            var web = new HtmlWeb();
            var document = web.Load("https://gamewith.net/cod-mw3/41723");
        
            var weapons = new List<Model>();
            var productHTMLElements = document.DocumentNode.QuerySelectorAll("div.weapon_list");

            foreach (var productElement in productHTMLElements) {
                var tr = productElement.QuerySelectorAll("tr");
                var allTR = tr.Skip(1);
                foreach (var trr in allTR)
                {
                    var td = trr.QuerySelectorAll("td");

                    var Name = td.First().InnerText;

                    var scoreElement = td.Last().QuerySelector("gds-walkthrough-vote-en");



                    //Console.WriteLine(Name + " " + Score);
                }
            }

Who need this is link for site: https://gamewith.net/cod-mw3/41723
Need to take User Rating values

I tried search info in internet, but did not find anything about it

Reading huge JSON array to get specific item

I have a huge JSON file where the top level structure is an array, and it basically contains many subarrays like this: [ [], [], [], … [] ]

Each subarray is actually quite small so it is loadable in memory; the sheer size of the file comes from the number of subarrays.

Suppose I already know the index of the subarray I want to access beforehand; how can I get just that subarray without having to load the entire JSON file into memory? What’s the least convoluted way to achieve this?

Megamenu implementation on Shopify Store. CSS gets messed up

I have tried in this regard as follows. All can contribute

  1. Found a fantastic mega menu implemnt at https://www.cssscript.com/demo/responsive-mega-menu/ This is open avaiable.

  2. Copied relevant html+css and javascript.

  3. Put html + CSS in a .liquid file (megamenu.liquid) togather and javascript in separate .js file (say,megamenu-liquid-support.js) . Put <script src="{{ 'megamenu-liquid-support.js' | asset_url }}"> </script> at the end of html of megamenu.liquid

  4. Opened header.liquid file of Shopify Dawn theme.

  5. Commented lines 159 to 346 which are responsible for display of menu.

  6. On line no. 347, put the tag {% render 'megamenu.liquid' %} to render it on screen. Uptill here, we are talking about lines in header.liquid

  7. Now, you need to put a small code (in megamenu.liquid)as follows starting from line no.54 to 71 and comment out line no. 72 to 133. Basically, commenting it will disable hard coded CSS and below code will implement link list menu from shopify. Also put <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/4.6.3/css/ionicons.min.css"> at beginning of megamenu.liquid. The code to be put is as mentioned below:

  8. Vola ! You have megamenu functional on yourshopify site. Icing on the cake – it will be functional on mobile as well !!!

  9. Now the problem part, after you do above you will have functinal menu because now CSS gets messed up and font size etc becomes weired on every page of shopify store. Any solution to this. I came up to this and hope someone will definately get help from this and some veteran can help us out also.

 <li class="menu-item-has-children">
        <a href="#">Category <i class="ion ion-ios-arrow-down"></i></a>
              <div class="menu-subs menu-mega menu-column-4">
                 {%- for link in section.settings.menu.links -%}
                    <div class="list-item">
                       <h4 class="title">{{ link.title | escape }}</h4>
                        <ul >
                           {%- for childlink in link.links -%}
                              <li> <a id="mega_headerMenu-{{ link.handle }}-{{ childlink.handle }}" href="{{ childlink.url }}" >{{ childlink.title | escape }} </a> </li>
                           {% endfor %}
                        </ul>
                      </div>
                {% endfor %}

                <div class="list-item">
                  <img src="<<Put image link here"  class="responsive"  width="300" height="173" alt="Shop Product">
                </div>
                 </div>
        </li>

How does one host a web server that has an SSL certificate signed by a free provider like Cloudflare, without having an index.html

All I want is a javascript program running that has a domain name to itself. I want a client to be able to send a simple HTTPS request to this server, which can then interpret it and send commands out to other devices over the network using HTTP. I have all the juicy communication stuff prepared

send requests
recieve requests

The problem arises when I directly reference the ‘receive requests’ server, the browsers don’t like it being over HTTP so I must use HTTPS, but the certificate I have (self-signed) doesn’t sit well with basically any of the security checks built into the browser. To get it signed by the authority, I must have a domain name rather than an IP. Which brings us back to the original problem, how can I host this second script with a domain name and its own URL, without dealing with any if that HTML stuff?

I tried hooking the browser up to my raspberry pi server directly over HTTPS but it decided to give a ‘hey use HTTPS’ error. So I generated a self-signed certificate but it complained that it wasn’t signed by an authority it trusts. So I’ll get my own domain running this script with a certificate and just force it to accept HTTP to the pi itself, but how do I do that without having a webpage running as well?

Add key to an object in an array without mutating original variable

I am trying to understand how to add an element to an object without mutating the original variable.

For instance, this is what I have:

let orders = [];
const order = { name: "John", phone: "+12345" };

if (orders.length === 0) {
  orders = [{ ...order, invoice: "INV-1" }];
} else {
  let temp;
  temp = parseInt(orders[orders.length - 1].invoice.replace(/INV-/, ""));
  orders = [...orders, order];
  orders[orders.length - 1].invoice = `INV-${temp+1}`;
};

console.log(order)
console.log(orders);

I notice for the first condition it works as I don’t see the variable “order” being mutated when orders is an empty array. However, if for example, now orders is equal to the following:

let orders = [{name: "Maria", phone:"+19876", invoice:"INV-1"}];

I can see it goes through the “else” statement and the operation in there adds the new key to orders, however, the variable order is mutated as well.

My question is, e.g. how can I add INV-2 in this specific example without mutating order?

Thanks.

In VSCode, how can I add comment characters spanning the length to the end of my vertical ruler? Is this possible?

I often separate blocks of code using comment characters spanning a specified distance horizontally. The character depends on the language, but for the sake of this example I’m using JavaScript and the “/” character.

Here is some sample code:

// const / start 

        settings_init = {

            // extension.js
            'p_path': '',

            // main.js
            'mode_current': 'insert-listview',
            'c_cid': -1,                        
            'filter_open': false,               
            'filter_val': '',                   
            'picker_open': false,               
            'picker_color': '',                 
            'picker_color_init': '',            
            'scroll_pos': -1,                   
            'cm_width': 380,                    
        };

What I’d like to do is this:

// const / start ///////////////////////////////////////////////////////////////////////////////////////////

        settings_init = {

            // extension.js
            'p_path': '',

            // main.js
            'mode_current': 'insert-listview',
            'c_cid': -1,                        
            'filter_open': false,               
            'filter_val': '',                   
            'picker_open': false,               
            'picker_color': '',                 
            'picker_color_init': '',            
            'scroll_pos': -1,                   
            'cm_width': 380,                    
        };

Or even this:

// const / start ///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////

        settings_init = {

            // extension.js
            'p_path': '',

            // main.js
            'mode_current': 'insert-listview',
            'c_cid': -1,                        
            'filter_open': false,               
            'filter_val': '',                   
            'picker_open': false,               
            'picker_color': '',                 
            'picker_color_init': '',            
            'scroll_pos': -1,                   
            'cm_width': 380,                    
        };

An image as an example so you can see the ruler position:

Before


enter image description here

After 1


enter image description here

After 2


enter image description here

Is there a plugin, hack, or other method I can utilize in VSCode that will do this for me without having to type each character by hand or copy paste blocks of characters? Really would love this functionality.

Any help appreciated!

Tumblr Automatic Insertion of Image Caption Base Upon Image File Name? – Example Script I Use on Blogger to Do This

On Blogger I use the following script to automatically insert image captions.

The caption is file name of the image less the image extension.

The script also adds “Figure ” before the name.

Thus a image named “1-0-1.jpg” would be automatically captioned “Figure 1-0-1”.

Is there a way to to do this on Tumblr?

I use both text posts with images inserted and image posts.

<script type='text/javascript'>
//<![CDATA[

function addCaption(img) {
  var ele=$(img);
  if(ele.parent().is(".caption-wrap")) return;
  var alter = ele.attr('alt')
  var srcurl = ele.attr('src')
  var altsrc = ""  
  altsrc = srcurl + "*" + alter;
  var title=altsrc
  if(typeof title === "undefined" || title=="") return;
  if(ele.parent().is("a")) ele=ele.parent();
  var align=ele.attr("align");
  if(!align) align=ele.css("float");
  if(align=="") align="none";
  var container=ele.wrap('<div style="display:inline-block" class="caption-wrap '+align+'" />').parent();
  container.css("float", align);
  container.css("width", ele.outerWidth()+"px");
  container.css("margin-left", ele.css("margin-left"));
  container.css("margin-right", ele.css("margin-right"));
  container.css("margin-bottom", ele.css("margin-bottom"));
  ele.css("margin-left", "0px");
  ele.css("margin-right", "0px");
  ele.css("margin-bottom", "0px");
  var begin = title.lastIndexOf("/") + 1;
  var end = title.lastIndexOf(".") - 3;
  var length = end - begin + 1;
  var title = title.substr(begin, length);
  var begin = title.lastIndexOf("*") + 1;
  var title = title.substr(begin);
  var text=container.append('<p class="caption-text">Figure '+title+'</p>').find(".caption-text");
  text.css("width", ele.outerWidth()+"px");
}
// add captions on window.load to img's with class "caption"
$(window).load(function() {
  $("img").each(function() {
    addCaption(this);
  });
});
//]]>
</script>  

I’ve looked at this page:

https://www.tumblr.com/docs/en/custom_themes

I’ve searched various terms in Google for automatically adding image captions but have found no documentation or examples of how to modify a Tumblr template.

Node-RED – Variable Set Not Setting

The Code Overall is to act as a switch making it saying if its ‘hit’. The switch activates once until needing to reset. However, the hitobject or reset isn’t restarting thus activating hit repeatedly if payload is true.

How can I fix it so it requires a false in payload to be active again

var hitobject = context.get("hitojbect") || true;

if (msg.payload == true && hitobject == true) {
  hitobject = false;
  context.set("hitobject", hitobject);
  console.log("Hit");
} else if (msg.payload == false && hitobject == false) {
  hitobject = true;
  context.set("hitobject", hitobject);
  console.log("Not Hit");
}

return;

I tried:

  • different datatypes to bool & number but hasn’t changed at all
  • inserting an only 1 output

How to add padding to a navbar element while keeping the .container’s width

I want to add some padding horizontally on a navbar, but if I apply padding: 10px; directly to the .container, it forces the elements inside of it to reduce the width. However, I want to keep the width of the .container element, but outside the current width. How do I do it?
enter image description here

<nav class="navbar navbar-expand-sm fixed-top" id="navId">
    <div class="container-fluid" style="background:rgba(0,0,0,0.2)">
        <div class="container justify-content-between d-flex" id="navbar_container">
            <a class="navbar-brand" href="#" style="color:#fff">MyNavBarName</a>
            <ul class="navbar-nav" id="topmost_navbar">
                <li class="navbar-item">
                    <a class="nav-link" href="#">Home</a>
                </li>
                <li class="navbar-item">
                    <a class="nav-link" href="#">About</a>
                </li>
                <li class="navbar-item">
                    <a class="nav-link" href="#">Option</a>
                </li>
                <li class="navbar-item">
                    <a class="nav-link" href="#">Contact</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

react native webview at latest version doesn’t have injectJavascript in its reference

I am fighting with this problem for about a week.
It is React Native, and I am using React Native Webview for my project.

React Native Webview

I am having problems using injectJavaScript with the WebView referenced. Here is my code.

import WebView from 'react-native-webview';

const ParentView = () => {
  const ref = useRef<WebView>(null);

  const wrapperContent = `
    <body><div>some content</div></body>
  `;

  const onButtonClick = () => {
    console.log(ref.current);
    ref.current.injectJavaScript(`alert("here"); true;`);
  }

  return <View>
    <WebView
        ref={ref}
        source={{html: webViewWrapperContent}}
        style={{width: '100%', height: '100%'}}
        showsVerticalScrollIndicator={false}
        showsHorizontalScrollIndicator={false}
        scrollEnabled={false}
        originWhitelist={['*']}
        sharedCookiesEnabled={true}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        injectedJavaScript={`console.log("injected")`}
        javaScriptCanOpenWindowsAutomatically={true}
        onMessage={(event) => {}}
      />
    <Button onPress={onButtonClick}></Button>
  </View>
}

This code prints “injected” to the console correctly. And when I click the button, then it prints this:
console output

As you can see there, there is no injectJavaScript object.

I am on React Native 0.68.2, and React Native Webview 11.23.1, and building web in windows machine.

I tried almost everything I can find with Stack Overflow and their Github issues.

A simple spelling mistake but this shows injectJavaScript in the ref object.

This issue is very close, but how come they can say it works on Windows even if it doesn’t have injectJavaScript?

Also, I tried putting the injectJavaScript in setTimeout,

I am sure I am doing something wrong with the configuration, or is it something I cannot use with windows machines?

I would like to get this work. I have other workarounds, like using websocket and broadcast to send the click event to server and listen to that thread within the WebView, but this is (obviously) an ill pattern.

Please help me fixing this issue. Thanks in advance!

The router.query becomes undefined on page refresh

I was working on this website it’s for driving test for Canadians, the problem i am facing is when someone chooses from three differnet types of quizzes (Traffic Signs, Rules of Road, Full Test) from index.js page and it goes to Quiz page which contain logic for all three different quizzes like using different data and div’s which i am getting from query named dataType passed while clicking on quiz option. On first reload everything works perfectly fine but when you refresh the page the router.query.dataType becomes undefined and it starts the different quiz and shows different divs coz basically most of the stuff depends on router.query.dataType. how can i set its value first and then the page loads: here is the link to the website which is uplaoded on vercel: https://driving-test-ten.vercel.app/

and here is the Quiz.js

import NavTimer from "@/components/NavTimer";
import Results from "@/components/Results";
import { rorData } from "@/storage/rorData";
import { signData } from "@/storage/signsData";
import { useRouter } from "next/router";
import { createRef, useEffect, useRef, useState } from "react";
import { darkMode, lightMode } from "../colorModes";
import { useAtom } from "jotai";
import { userData } from "@/jotaiStorage";
import Cookies from "js-cookie";
export default function Quiz() {
    const router = useRouter();
    const dataType = router.query.dataType;
    const MAX_QUESTIONS = dataType === "FullTest" ? 40 : 20;
    const RED_COLOR = "rgb(255, 0, 0)";
    const GREEN_COLOR = "rgb(27, 148, 27)";

    const [data, setData] = useState(
        dataType === "signData" ? [...signData] : [...rorData]
    );

    const confirmContainerRef = useRef(null);
    const signContainerRef = useRef(null);
    const currentSignRef = useRef(null);
    const questionCountForTop = useRef(null);
    const currentQuestionRef = useRef(null);
    let timeoutRef = useRef(null);
    let runningTimeoutRef = useRef(null);
    // const optionContainerRef = Array.from({ length: 4 }, () => useRef());
    //    const optionContainerRef = useRef(Array.from({ length: 4 }).map(() => createRef()));
    const optionContainerRef = [useRef(), useRef(), useRef(), useRef()];

    const [confirmDisplay, setConfirmDisplay] = useState(false);
    const [currentOptionSet, setCurrentOptionSet] = useState(0);
    const [currentAnswer, setCurrentAnswer] = useState(0);

    const [questionCount, setQuestionCount] = useState(1);
    const [showResults, setShowResults] = useState(false);
    const [selectedOption, setSelectedOption] = useState(null);
    const [initialized, setInitialized] = useState(false);
    const [trackIndexForBoth, setTrackIndexForBoth] = useState([]);
    const [trackIndexForSignQuiz, setTrackIndexForSignQuiz] = useState([]);
    const [trackIndexForRorQuiz, setTrackIndexForRorQuiz] = useState([]);
    const [isTryingToGoBack, setIsTryingToGoBack] = useState(false);

    const [isSignDiv, setIsSignDiv] = useState(
        dataType === "signData" ? true : false
    );

    const [resultData, setResultData] = useState({
        resultDataType: [],
        time: { minutes: 0, seconds: 0 },
        totalQuestions: MAX_QUESTIONS,
        storedWrongAnswers: [],
    });

    const [resultDataType, setResultDataType] = useState(null);
    const [user, setUser] = useAtom(userData);

    useEffect(() => {

        setTimeout(() => {
            optionContainerRef.forEach((option) => {
                if (option.current) option.current.style.pointerEvents = "all";
            });
        }, 1000);
    }, []);

    useEffect(() => {
        if (!isSignDiv && currentQuestionRef.current) {
            // Set the ror question when isSignDiv becomes false
            if (currentQuestionRef.current) {
                if (!initialized) {
                    currentQuestionRef.current.classList.add("fadeIn");
                    setTimeout(() => {
                        if (currentQuestionRef.current)
                            currentQuestionRef.current.classList.remove(
                                "fadeIn"
                            );
                    }, 1000);
                } else {
                    currentQuestionRef.current.classList.add("slideRight");
                    setTimeout(() => {
                        if (currentQuestionRef.current)
                            currentQuestionRef.current.classList.remove(
                                "slideRight"
                            );
                    }, 1000);
                }
            }
            currentQuestionRef.current.innerHTML =
                rorData[currentOptionSet].question;
        }
        if (currentSignRef.current) {
            currentSignRef.current.src = data[currentOptionSet]?.imageUrl;
        }
    }, [isSignDiv, currentQuestionRef, currentOptionSet]);

    useEffect(() => {
        return () => {
            clearTimeout(timeoutRef.current);
            clearInterval(runningTimeoutRef.current);
        };
    }, []);

    useEffect(() => {
        if (!initialized) {
            getRandomQuestion();
            doInitialAnimation();
        }
        setInitialized(true);
    }, [initialized]);

    useEffect(() => {
        confirmContainerRef.current.style.visibility = confirmDisplay
            ? "visible"
            : "hidden";
    }, [confirmDisplay]);

    useEffect(() => {
        const userCookie = Cookies.get("user");
        if (userCookie) {
            const userData = JSON.parse(userCookie);
            setUser(userData);
        }
        user?.isDarkMode ? darkMode() : lightMode();
    }, [user?.isDarkMode]);

    const handleOptionClick = (index) => {
        if (selectedOption !== null) {
            optionContainerRef[selectedOption].current.style.backgroundColor =
                "";
        }

        if (selectedOption === index) {
            setSelectedOption(null);
            setConfirmDisplay(false);
        } else {
            setConfirmDisplay(true);
            setSelectedOption(index);
            setCurrentAnswer(index + 1);
            optionContainerRef[index].current.style.backgroundColor =
                GREEN_COLOR;
        }
    };

    const renderQuestions = () => {
        return (
            <>
                <div className="question-count-container">
                    <div ref={questionCountForTop} className="question-count">
                        1/{MAX_QUESTIONS}
                    </div>
                </div>
                {isSignDiv ? (
                    <div ref={signContainerRef} className="sign-main-container">
                        <div className="sign-container">
                            {/* Image will go here! */}
                            <img
                                ref={currentSignRef}
                                className="sign-image"
                                src=""
                                loading="eager"
                            ></img>
                        </div>
                    </div>
                ) : (
                    <div
                        ref={signContainerRef}
                        className="ror-question-main-container"
                    >
                        <div className="ror-question-sign-container">
                            {/* Image will go here! */}
                            <img
                                ref={currentSignRef}
                                className="sign-image"
                                src=""
                                loading="eager"
                            ></img>
                        </div>
                        <div
                            ref={currentQuestionRef}
                            className="ror-question-container"
                        ></div>
                    </div>
                )}
            </>
        );
    };

    const renderOptions = () => {
        return Array.from({ length: 4 }, (_, index) => (
            <div
                key={index}
                ref={optionContainerRef[index]}
                onClick={() => handleOptionClick(index)}
                className="option-main-container"
            >
                <div className="option-count">{index + 1}</div>
                <div className="option">
                    {data[currentOptionSet].options[index]}
                </div>
            </div>
        ));
    };

    const doInitialAnimation = () => {
        const onAnimationEnd = () => {
            // Remove event listeners to avoid potential issues
            signContainerRef.current.removeEventListener(
                "animationend",
                onAnimationEnd
            );
            confirmContainerRef.current.removeEventListener(
                "animationend",
                onAnimationEnd
            );
            optionContainerRef.forEach((option) => {
                option.current.removeEventListener(
                    "animationend",
                    onAnimationEnd
                );
            });

            if (
                signContainerRef.current &&
                confirmContainerRef.current &&
                optionContainerRef.every((option) => option.current)
            ) {
                // Remove animation classes
                signContainerRef.current.classList.remove("fadeIn");
                confirmContainerRef.current.classList.remove("fadeIn");
                optionContainerRef.forEach((option) => {
                    option.current.classList.remove("fadeIn");
                });
            }
        };

        if (
            signContainerRef.current &&
            confirmContainerRef.current &&
            optionContainerRef.every((option) => option.current)
        ) {
            // Apply animation classes
            signContainerRef.current.classList.add("fadeIn");
            confirmContainerRef.current.classList.add("fadeIn");
            optionContainerRef.forEach((option) => {
                option.current.classList.add("fadeIn");
            });

            // Add event listeners to handle animation end
            signContainerRef.current.addEventListener(
                "animationend",
                onAnimationEnd
            );
            confirmContainerRef.current.addEventListener(
                "animationend",
                onAnimationEnd
            );
            optionContainerRef.forEach((option) => {
                option.current.addEventListener("animationend", onAnimationEnd);
            });
        }
    };

    const doTheAnimation = () => {
        confirmContainerRef.current.style.backgroundColor = GREEN_COLOR;
        currentSignRef.current.classList.add("slideLeft");
        optionContainerRef.forEach((option) => {
            option.current.classList.add("slideLeft");
        });
        confirmContainerRef.current.classList.add("slideLeft");

        if (currentQuestionRef.current)
            currentQuestionRef.current.classList.add("slideLeft");

        timeoutRef.current = setTimeout(() => {
            confirmContainerRef.current.style.backgroundColor = "";
            currentSignRef.current.classList.remove("slideLeft");
            optionContainerRef.forEach((option) => {
                option.current.classList.remove("slideLeft");
            });
            confirmContainerRef.current.classList.remove("slideLeft");
            if (currentQuestionRef.current)
                currentQuestionRef.current.classList.remove("slideLeft");

            slideRightAnimation();
        }, 1000);
    };

    const slideRightAnimation = () => {
        currentSignRef.current.classList.add("slideRight");
        optionContainerRef.forEach((option) => {
            option.current.classList.add("slideRight");
        });
        confirmContainerRef.current.classList.add("slideRight");

        setConfirmDisplay(false);
        optionContainerRef.forEach((option) => {
            option.current.style.backgroundColor = "";
        });
        setQuestionCount((prev) => {
            var nextNumber = prev + 1;
            questionCountForTop.current.innerHTML = `${nextNumber}/${MAX_QUESTIONS}`;
            return nextNumber;
        });

        timeoutRef.current = setTimeout(() => {
            if (currentSignRef.current)
                currentSignRef.current.classList.remove("slideRight");
            optionContainerRef.forEach((option) => {
                if (option.current)
                    option.current.classList.remove("slideRight");
            });
            if (confirmContainerRef.current)
                confirmContainerRef.current.classList.remove("slideRight");
        }, 1000);
    };

    const checkAnswer = () => {
        const correctAnswerIndex = data[currentOptionSet].correctAns;

        // Check if the selected answer is correct
        if (currentAnswer === correctAnswerIndex)
            highlightOption(currentAnswer - 1, GREEN_COLOR);
        else {
            //Wrong answer
            highlightOption(currentAnswer - 1, RED_COLOR);
            // Right One
            highlightOption(correctAnswerIndex - 1, GREEN_COLOR);

            const newWrongAnswer = {
                question: currentOptionSet,
                wrongAnswerIndex: currentAnswer - 1,
            };

            setResultData((prevData) => ({
                ...prevData,
                resultDataType: [...prevData.resultDataType, resultDataType],
                storedWrongAnswers: [
                    ...prevData.storedWrongAnswers,
                    newWrongAnswer,
                ],
            }));
        }
    };

    const highlightOption = (index, color) => {
        optionContainerRef[index].current.style.backgroundColor = color;
    };

    const continueQuiz = () => {
        return (
            <>
                <NavTimer
                    setIsTryingToGoBack={setIsTryingToGoBack}
                    setResultData={setResultData}
                />

                <div className="quiz-outer-main-container">
                    {isTryingToGoBack && renderGoBack()}

                    <div className="quiz-main-container">
                        {renderQuestions()}
                        {renderOptions()}
                        <div className="confirm-main-container">
                            <div
                                ref={confirmContainerRef}
                                onClick={() => handleConfirm()}
                                className="confirm-container"
                            >
                                <i className="fa-solid fa-check"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </>
        );
    };

    const handleConfirm = () => {
        checkAnswer();
        if (questionCount !== MAX_QUESTIONS) {
            timeoutRef.current = setTimeout(() => {
                getRandomQuestion();
            }, 1000);
            doTheAnimation();
        } else setShowResults(true);
    };

    // This function is doing what it suppose to even thought it looks quite ugly
    // Purpose :: It's main responsibility is to get a unique number based on Quiz type
    //      1. It will check the Quiz type if it's just a Sign Quiz or Rules of Road quiz
    //         the logic is quite simple just get a random number when is not repeated
    //      2. But when we have Full Test we are suppose to get a random quiz type first,
    //         After that we need to check if the index which is tracking how many questions
    //         we have already asked in this case we are suppose to get 20 unique questions for
    //         Sign as well we  as Rules of Road
    const getRandomQuestion = () => {
        let randomOptionSet;

        const getUniqueNumber = (tracker, setTracker, limit) => {
            var randomNumber;
            while (true) {
                randomNumber = Math.floor(Math.random() * limit);
                if (tracker.includes(randomNumber)) continue;
                else {
                    const newData = [...tracker, randomNumber];
                    setTracker(newData);
                    break;
                }
            }
            return randomNumber;
        };

        if (dataType !== "FullTest") {
            setResultDataType(dataType);
            randomOptionSet = getUniqueNumber(
                trackIndexForBoth,
                setTrackIndexForBoth,
                data.length
            );
        } else {
            const randomDataType = getZeroOne();

            if (randomDataType === 0) {
                const newData = [...signData];
                setResultDataType("signData");

                if (trackIndexForSignQuiz.length < 10)
                    randomOptionSet = getUniqueNumber(
                        trackIndexForSignQuiz,
                        setTrackIndexForSignQuiz,
                        newData.length
                    );
                else
                    randomOptionSet = getUniqueNumber(
                        trackIndexForRorQuiz,
                        setTrackIndexForRorQuiz,
                        newData.length
                    );

                setIsSignDiv(true);
                setData(newData);
            } else {
                const newData = [...rorData];
                setResultDataType("rorData");

                if (trackIndexForRorQuiz.length < 10)
                    randomOptionSet = getUniqueNumber(
                        trackIndexForRorQuiz,
                        setTrackIndexForRorQuiz,
                        newData.length
                    );
                else
                    randomOptionSet = getUniqueNumber(
                        trackIndexForSignQuiz,
                        setTrackIndexForSignQuiz,
                        newData.length
                    );
                setIsSignDiv(false);
                setData(newData);
            }
        }
        if (currentSignRef.current) {
            currentSignRef.current.src = data[randomOptionSet]?.imageUrl;
        }
        if (currentQuestionRef.current) {
            currentQuestionRef.current.innerHTML =
                data[randomOptionSet].question;
        }
        setCurrentOptionSet(randomOptionSet);
    };

    const getZeroOne = () => {
        return Math.floor(Math.random() * 2);
    };

    const renderGoBack = () => (
        <div className="quiz-backDrop">
            <div className="confirm-go-back-main-container">
                <div className="go-back-warning">
                    Going back will erase your quiz progress. Are you sure?
                </div>
                <div className="go-back-options-container">
                    <div
                        onClick={() => setIsTryingToGoBack(false)}
                        className="go-back-option-cancel"
                    >
                        <i className="fa-solid fa-xmark"></i>
                    </div>
                    <div
                        onClick={() => {
                            router.push("/");
                        }}
                        className="go-back-option-confirm"
                    >
                        <i className="fa-solid fa-check"></i>
                    </div>
                </div>
            </div>
        </div>
    );

    return (
        <>
            {showResults ? (
                <>
                    <Results
                        resultData={resultData}
                        data={data}
                        dataType={dataType}
                        trackIndexForRorQuiz={trackIndexForRorQuiz}
                        trackIndexForSignQuiz={trackIndexForRorQuiz}
                    />
                </>
            ) : (
                continueQuiz()
            )}
        </>
    );
}

I have tried to use the use UseEffect with Dependency of router.query but it makes me change a whole bunch of logic also i needed the value of it for these useStates :
`
const MAX_QUESTIONS = dataType === “FullTest” ? 40 : 20;

const [data, setData] = useState(
    dataType === "signData" ? [...signData] : [...rorData]
);

`

and if i put these also in the useEeffect where i have Dependency of router.query the page reloads before they are Initialized. please help me working on this project from 3 months

Is it possible to scale a pathItem in Photoshop CC?

I’m trying to scale a pathItem using Javascript in Photoshop CC. I need to scale it with the TOPCENTER constraint. This pathItem is tied to a text layer (for type on a path).

When you scale a text layer that is bound to a path in Photoshop, it scales the path, not the text. So I tried scaling the actual layer – but it didn’t behave as expected. This just scales the text itself.

app.activeDocument.activeLayer.resize(100, amount, AnchorPosition.TOPCENTER);

It appears “resize” is not one of the methods of the pathItem object. I know you can scale paths in Illustrator with Javascript, but it doesn’t work here.

app.activeDocument.pathItems[1].resize(100, amount, AnchorPosition.TOPCENTER);

This documentation for Photoshop seems to suggest that there is no such method. Am I missing something? Or is there some alternate way, like directly changing the position of the points on the path?