revalidateTag/revalidatePath in sever actions updates the UI without visiting the page, why?

revalidateTag/revalidatePath “only invalidates the cache when the path is next visited in Next.js” (https://nextjs.org/docs/app/api-reference/functions/revalidatePath), and they work fine inside server actions for data revalidation and UI update when the page is navigated to. The bit I do not follow is why they also working producing a desired outcome of revalidating and updating UI when we are performing data mutation (like adding product) on the page that displays data, meaning that we are not navigating to a new page after performing a mutation yet apparently cache on the page we are currently on gets purged, data gets revalidated and UI updated. One answer to that is that “Server Actions integrate with the Next.js caching and revalidation architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip.” (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations), and yes it does make sense only how does the next.js knows which ‘updated UI’ is supposed to send back? updated UI in terms of server component means some form of html that is ready to be displayed, and we can have many pages that are displaying data that our revalidateTag/revalidatePath is revalidating, one server actions can be imported to many different components and yet er get the specific html update relevant for our page without navigating to that page? To reiterate my problem is that I understand the when we navigate to new page then we can get the updated UI, but when we are already on the page and display data on it and perform mutation on it (given that we can be displaying the same data on many pages) how do we get the updated UI in the server action return trip for our desired page?

mongoose and express i want user related data in comment modal

I have a user ,post,comment modal

This is my comment modal

import mongoose from "mongoose";

const CommentSchema = new mongoose.Schema({
  postId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Post",
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  content: {
    type: String,
    required: true,
  },
  image: {
    type: String,
  },
  likes: {
    type: Array,
    default: [],
  },
});

export default mongoose.model("Comment", CommentSchema);

and this is my addComment controller

export const addComment = async (req, res) => {
  try {
    const post = await Post.findById(req.body.postId);
    if (!post) {
      return res.status(404).json({ message: "Invalid Post Id" });
    }
    const comment = await new Comment(req.body);
    await comment.save();
    res
      .status(200)
      .json({ success: true, message: "Comment added Successfully!" });
  } catch (err) {
    res.status(500).json({ message: "Internal Server Error!" });
  }
};and this is my getComments controller

export const getAllCommentsOfPost = async (req, res) => {
  try {
    const post = await Post.findById(req.body.postId);
    if (!post) {
      return res.status(404).json({ message: "Invalid Post Id" });
    }
    const comments = await Comment.find({ postId: req.body.postId });
    res.status(200).json({ success: true, comments: comments });
  } catch (err) {
    res.status(500).json({ message: "Internal Server Error!" });
  }
};

This is my response

{
    "success": true,
    "comments": [
        {
            "_id": "65f2eec753e8de0aa1fffb26",
            "postId": "65f2e983f80127323fc86d8e",
            "content": "bad",
            "likes": [],
            "__v": 0
        }
    ]
}

in the response i am only getting postId , why am i not getting userId despite mentioning userId in comment modal and referenced it to user Modal and also how can i get the username as well .I need both username and userId in comments modal, can you guys tell me ways to do it?

How to open a page in a new tab after finalize purchase in woocommerce

How can I set up my checkout page so it opens in a new tab while still maintaining the regular WooCommerce behavior when the user presses the confirm purchase button?
I want to add a new method to the WooCommerce button so it opens a new tab.

I tried this in a Elementor HTML block:

<script>
document.addEventListener('DOMContentLoaded', function() {
    var abrirContratoButton = document.getElementById('place_order');
    if (abrirContratoButton) {
        abrirContratoButton.addEventListener('click', function(event) {
            //event.preventDefault();

          
            var firstName = document.getElementById('billing_first_name').value;
            var lastName = document.getElementById('billing_last_name').value;
            var cpfCnpj = document.getElementById('billing_cpf_cnpj').value;

            
            localStorage.setItem('billing_first_name', firstName);
            localStorage.setItem('billing_last_name', lastName);
            localStorage.setItem('billing_cpf_cnpj', cpfCnpj);

            
            window.location.href = abrirContratoButton.getAttribute('href');
        });
    }
});
</script>

Send value from cshtml (ASP.NET MVC) to js

How can I pass this to js module

home.cshtml

<p id="timer" end-date="2030.12.31."

Presently sadly the cshtml file does not notice that the end-date is a variable.
I tried to set up there as
@{var end-date = …..}

But it did not really want to work out.

How can I send the date value to the js. And how do I code in the js file this.

thanks a lot

react native gives TypeError: Cannot read property ‘useRef’ of null,

im new to react native so i really don’t know why this issue is coming up. if u need any additional info feel free to ask. im trying to build a navigation system similar to windows phone where we can swipe to the next screen.

here is my code

import { StyleSheet, Text, View, FlatList, TouchableOpacity, Dimensions } from 'react-native'
import React , {useState,useRef} from 'react'

const allData = [
    {name:'Explore',id:'1'},
    {name:'Trending',id:'2'},
    {name:'Post',id:'3'},
    {name:'Messages',id:'4'},
    {name:'Marketplace',id:'5'}
]
const reff = useRef()
const [index,setIndex] = useState(2)
const spacing = 10;


export default function topDynamicBar() {
  return (
    <View style ={styles.container}>
      <FlatList
      ref={reff}
      initialScrollIndex={index}
      keyExtractor={(item)=>item.id}
      data={allData}  
      renderItem={({item, index: findex})=>(<Text style={styles.items}>{item.name}</Text>)}
      horizontal
      showsHorizontalScrollIndicator={false}
      />
    </View>
  )
}

const styles = StyleSheet.create({
    container:{
        backgroundColor:'#000000'
    },
    items:{
        padding:2,
        fontSize:30,
        height: "auto",
        margin:10,
        borderColor:'#fff',
        borderWidth:2,
        borderRadius: spacing
        

    }

})

How to insert ‘dropdownMenu’ in ‘rhandsontable’?

The JavaScript library Handsontable has the ‘dropdownMenu’ option, which allows displaying an icon in the column headers and opening a dropdown menu with various options.

I know this can be achieved using JavaScript, but my knowledge of JavaScript is practically nonexistent. How can this option be included using the ‘rhandsontable’ package in Shiny?

Recoil state only changing after reloading the page

I am using recoil for state management, for a very basic todo app for practice, but my todolist.tsx is not showing the updated username and I need to refresh everytime to see the updated username and todos change as soon as the username changes. I can’t figure out the issue.

This is my authState

import { atom } from 'recoil';

export const authState = atom({
    key: 'authState',
    default: { token: null, username: null },
});

and this is the iniital State

function InitState() {
  const setAuth = useSetRecoilState(authState);
  const navigate = useNavigate();

  const init = async () => {
    const token = localStorage.getItem("token");
    try {
      const response = await fetch('http://localhost:3000/auth/me', {
        headers: { Authorization: `Bearer ${token}` }
      });
      const data = await response.json();
      console.log(data);
      console.log(data.username);
      if (data.username) {
        setAuth({ token: data.token, username: data.username });
        navigate("/todos");
      } else {
        navigate("/login");
      }
    } catch (e) {
      navigate("/login");
    }
  }

  useEffect(() => {
    init();
  }, [])

and inside my todolist.tsx , I am using authStata like this :

  const authStateValue = useRecoilValue(authState);

and the username is not updating until I refresh and reload the page, todos fetched are the updated ones but the username is not updating until page is reloaded

 return (
        <div>
            <div style={{ display: "flex" }}>
                <h2>Welcome {authStateValue.username}</h2>
                <div style={{ marginTop: 25, marginLeft: 20 }}>
                    <button onClick={() => {
                        localStorage.removeItem("token");
                        navigate("/login");
                    }}>Logout</button>
                </div>
            </div>
            <h2>Todo List</h2>
            <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />
            <input type="text" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Description" />
            <button onClick={addTodo}>Add a new Todo</button>
            {todos.map((todo) => (
                <div key={todo._id}>
                    <h3>{todo.title}</h3>
                    <p>{todo.description}</p>
                    <button onClick={() => markDone(todo._id)} >{todo.done ? 'Done' : 'Mark as Done'}</button>
                </div>
            ))}
        </div>
    )
};

export default TodoList

The username should also update as the todolist component re-renders , but except username everythign is fetching is being displayed fine. I can’t figure out the issue, I am just starting out to use typescript with recoil

How can I get my content hash code to work?

I’m following this https://www.youtube.com/watch?v=MpGLUVbqoYQ webpack tutorial precisely, and have gotten to the part of the video where he talks about content hashing. On the video he does:


    const path = require("path");
    module.exports = {
      mode: "development",
      entry: "./src/index.js",
      output: {
        filename: "main.[contentHash].js",
        path: path.resolve(__dirnamem, "dist")
      },
      module: {
        rules: [
          {
            test: /.scss$/,
            use: [
              "style-loader",
              "css-loader",
              "sass-loader"
            ]
          }
        ]
      }
    };

I have done:

const path = require("path");

module.exports =  {
    mode: "development",
    entry: "./src/index.js",
    output: {
        filename: "main.[contentHash].js",
        path: path.resolve(__dirname, "dist")
    },
    module: {
        rules: [
            {
                test: /.scss$/,
                use: [
                    "style-loader", // 3. Injects styles into DOM
                    "css-loader",  // 2. Turns css into commonjs
                    "sass-loader" // 1. Turns sass into css
                ]
            }
        ]
    }
};

On the video this code works and appends a content hash where indicated, but when I ran npm start, I got this:

enter image description here

How can I create a global state that can be accessed or modified from these pages? I’m using React RouterProvider

How can I create a global state that can be accessed or modified from these pages?

import React from 'react'
import ReactDOM from 'react-dom/client'
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import './index.css'

import Home from './pages/Home.jsx'
import Login from './pages/Login.jsx'
import SignUp from './pages/SignUp.jsx'

const router = createBrowserRouter([
  {path: '/', element: <Home />},
  {path: '/login', element: <Login />},
  {path: '/register', element: <SignUp />},
])

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>,
)

How to save the brush event when hovering over elements with their own events

I have a brush overlay that tracks zoom events. it is stretched over the entire graph area and is drawn first, and then the graph lines. This is done so that I can process click events, mouseover, mouseout separately, for example, to highlight the graph. At the same time, I want to maintain the ability to zoom while being above the graph line, but my brush is lost, how can I fix this?

I thought about sending the event to the overlay using dispatchEvent, but I don’t understand how to create brush events.
Or maybe you need to somehow reactivate the brush?

Open next tab using puppeteer

How can I open next tab upon closing existing tab? The main thing here is I have a continuasly reloading pages in executingFunctions and as soon as one of the pages has proper html, puppeteer starts to interact with it, closes it and opens a new one. But what if I don’t want this page to be interacted and I want to close it.

concurrentOrders.js

export default async function concurrentOrders(limit, links) {
  const executingFunctions = [];

  let currentIndex = 0;

  while (currentIndex < links.length) {
    while (executingFunctions.length < limit && currentIndex < links.length) {
      const link = links[currentIndex];
      currentIndex++;

      const promise = createBuyOrderPromise(...link).finally(() => {
        const index = executingFunctions.indexOf(promise);
        if (index !== -1) executingFunctions .splice(index, 1);
      });
      executingFunctions.push(promise);
    }

    await Promise.race(executingFunctions);
  }
}

createBuyOrderPromise.js

export default async function createBuyOrderPromise(link) {
  return new Promise(async (resolve, reject) => {
    try {
      const page = await makeConnection();  // launch in existing browser using puppeteer (via webSocketUrl)
      await gotoMarketItemPage(page, link);
      await closeTabPage(page);     // closing tab
      resolve();
    } catch () {
      reject();
    }
  });
}

gotoMarketItemPage.js

export default async function gotoMarketItemPage(page) {
  try {
    await page.goto(page,
      {
        waitUntil: "domcontentloaded",
        timeout: 0,
      }
    );

    const image = await page.$(itemImageSelector);

    if (image) elementFound = true;
    if (!image) await page.reload();
  }
}

Tried to implement puppeteer’s

     await page.on("close", () => {
       reject();
     });

with passing reject function to gotoMarketItemPage

in gotoMarketItemPage.js but it made it work like:
if I close one of html loaded pages without the content that I need, this action stops reloding other pages in process in addition to that it stops adding up a page to the stack.

P.S. That is not full version of code for the sake of understanding. Sorry for bad explanation. Let me know if I can clarify this.

Is there any better alternative of firebase/supbase? [closed]

Firebase = has their own database that’s why I don’t like it because it creates their dependency and it is super hard to migrate from Firebase.

Supbase = It is good but it does not have MongoDB support and their auto-generated APIs are not that much feature-rich.

  • And for custom business logic, anyway need to create separate backend projects and need to use supabase sdk.

I want something that is self-hosted and should be super easy and free/open source and feature-rich also.

Nuxt 3 middleware from and to routes are always the same

I am facing a strange problem in my Nuxt 3 application. I do want to add my first middleware to my project called auth.ts. This middleware should protect certain pages from users who are not logged in. Basically it should grant access to the requested page to those who are logged in and navigate those who are not logged in to the login page. Quite simple and straight forward.

However, my to and from variables in my middleware are always the same. This results in an infinite redirection in a navigation guard.

This is my middleware:

export default defineNuxtRouteMiddleware((to, from) => {
    const userStore = useUserStore();

    console.log('From auth middleware')
    console.log('to', to)
    console.log('from', from)
    console.log('authenticated', userStore.authenticated)

    // If the user is authenticated, continue to the requested route
    if (userStore.authenticated === true) {
        return navigateTo(to.fullPath);
    }

    // If the user is not authenticated, redirect to the login page
        return navigateTo('/login');
    })

The authenticated variable comes from my Pinia store.

This is how I add the middleware to my /profile page:

definePageMeta({ middleware: ["auth"] });

This is the error I get:

[Vue Router warn]: Detected a possibly infinite redirection in a navigation guard when going from "/profile" to "/profile". Aborting to avoid a Stack Overflow. Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.

This is the console log I get from my auth.ts middleware:

From auth middleware auth.ts:4:9

to Object { fullPath: "/profile", hash: "", query: {}, name: "profile", path: "/profile", params: {}, matched: (1) […], meta: Proxy, redirectedFrom: {…}, href: "/profile" } auth.ts:5:9

from Object { fullPath: "/profile ", path: "/profile", query: {}, hash: "", name: "profile", params: {}, matched: (1) […], meta: {…}, redirectedFrom: undefined, href: "/profile " } auth.ts:6:9

authenticated true

When the user is not authenticated it successfully navigates the user to the /login page. But when the user is logged in I always get the error. It would make sense to me if I am already on the profile page and then refresh the page.

But I get this error as well when I am at / and navigate to the /profile page. But how can the from variable be /profile when I navigate from the / page to the /profile page?

Kind regards

React ChartJS Drop Shadow; How to [duplicate]

I’ve come across several good looking ChartJS line charts that have just a small and fading shading under each line. However, I’m not able to implement that for myself, nor have I found any good example code on the internet that does the thing with React/NextJS. Below is a picture of my desired state and the current component which adds a shadow to the line chart but does not make it more transparent to the outside. Any ideas or solutions to that?

import React, { useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);
Chart.defaults.borderColor = "#434343";
Chart.defaults.color = "#bfbfbf";
Chart.defaults.font.family = 'Inter, sans-serif'; 
Chart.defaults.font.size = 12;

const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
        y: {
            type: 'linear',
            display: true,
            position: 'left',
            grid:{
                display:false,
                drawOnCharArea: false,
            }
        },
        y1: {
            type: 'linear',
            display: true,
            position: 'right',
            grid:{
                display:false,
                drawOnCharArea: false,
            }
        },
        x : {
            display: true,
            beginAtZero:true,
            grid:{
                display:false,
                drawOnCharArea: false,
            }
        }
    },
    plugins:{
    }, 
};

export default function OverviewSalesLine({ data }) {

    // Custom shadow for chart
    useEffect(() => {
        Chart.register({
        id: 'customShadow',
        beforeDraw: (chart) => {
            const ctx = chart.ctx;
            ctx.save();

            const originalLineDraw = ctx.stroke;
            ctx.stroke = function () {
            ctx.save();
            ctx.shadowColor = 'rgba(0, 0, 0, 0.2)';
            ctx.shadowBlur = 10;
            ctx.shadowOffsetX = 4;
            ctx.shadowOffsetY = 4;
            originalLineDraw.apply(this, arguments);
            ctx.restore();
            };
        }
        });
    }, []);

    const chartData = {
        type: 'customShadow',
        labels: data.map(item => item.interval_start),
        datasets: [

            {
                label: 'Gross Sales',
                data: data.map(item => item.total_sales),
                borderColor: 'rgba(143, 143, 143, 1)', 
                backgroundColor:  'rgba(143, 143, 143, 0.2)',
                yAxisID: 'y',
                fill: true,
                tension:0.4,
            },

            {
                label: 'Items Sold',
                data: data.map(item => item.total_items_sold),
                borderColor: 'rgba(119, 111, 252, 1)', 
                backgroundColor: 'rgba(119, 111, 252, 0.2)', 
                yAxisID: 'y1',
                fill: true,
                tension:0.4,
            },

        ],
    };


    return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', width: "100%" }}>
            {!data || data.length == 0 ?<div> No data available </div> : <Line options={chartOptions} data={chartData} />}
         </div>
    ) 

enter image description here