Why is my XState graph not calling the Actor when I send an event?

I have a class like this creating a state graph

// Graph
const fetchTransactionsActor = fromPromise(async () => {
    console.log('fetchTransactions service called');
    const response = await fetch('/transaction');
    if (!response.ok) {
        throw new Error('Failed to fetch transactions');
    }
    return await response.json();
});
const transactionMachine = setup({
    actors: {
        fetchTransactionsActor,
        updateTransactionActor,
        deleteTransactionActor
    }
}).createMachine({
    id: 'transactions',
    initial: 'idle',
    entry: {
        type: 'FETCH'
    },
    context: {
        transactions: [],
        error: null
    },
    states: {
        idle: {
            on: {
                FETCH: 'loading',
                UPDATE: 'updating',
                DELETE: 'deleting'
            }
        },
        loading: {
            invoke: {
                src: 'fetchTransactionsActor',
                onDone: {
                    target: 'success',
                    actions: assign(
                        ({event}) => ({
                            transactions: event.output,
                        })
                    )
                },
                onError: {
                    target: 'failure',
                    actions: assign(({event}) => ({
                        error: event.error
                    }))
                }
            }
        },
        updating: {
            invoke: {
                src: 'updateTransactionActor',
                onDone: {
                    target: 'success'
                },
                onError: {
                    target: 'failure',
                    actions: assign(({event}) => ({
                        error: event.error
                    }))
                }
            }
        },
        deleting: {
            invoke: {
                src: 'deleteTransactionActor',
                input: ({event}) => event.data,
                onDone: {
                    target: 'success'
                },
                onError: {
                    target: 'failure',
                    actions: assign(({event}) => ({
                        error: event.error
                    }))
                }
            }
        },
        success: {
            // on: {
            //     REFRESH: 'loading'
            // }
        },
        failure: {
            // on: {
            //     RETRY: 'loading'
            // }
        }
    }
});
// Provider
import React, {createContext, useContext, useEffect} from 'react';
import {useMachine} from '@xstate/react';
import transactionMachine from './transactionMachine';

const TransactionContext = createContext();

export const TransactionProvider = ({children}) => {
    const [state, send] = useMachine(transactionMachine);

    useEffect(() => {
        (async () =>
                await send(
                    {type: 'FETCH'}
                )
        )();
    }, [send]);

    return (
        <TransactionContext.Provider value={{state, send}}>
            {children}
        </TransactionContext.Provider>
    );
};

export const useTransactionContext = () => {
    return useContext(TransactionContext);
};

This works great but now I would like to call the same (for now) FETCH function from another component so I wrap my app in <TransactionProvider> and I try the following…

const TransactionItem = ({txn: initialTxn, refreshTransactions}) => {
    const { send } = useTransactionContext();
    const [txn, setTxn] = useState(initialTxn);
    ...
    const onSave = async () => {
        console.log("Trying to send the information")
        send({ type: 'FETCH' });
    };

I see the “Trying to send the information” but never “fetchTransactions service called”

What am I missing why isn’t the actor getting called and why am I not seeing the info in the console?

Rules in ESlint’s flat config not working with `flat/strongly-recommended`, but work with `vue3-strongly-recommended`

I’m using eslint-plugin-vue and I’m trying to set a flat/strongly-recommended preset in flat config in eslint.config.js, instead of a legacy vue3-strongly-recommended which was used in .eslintrc, but it doesn’t work as expected. For example, ‘vue/require-prop-types’ rule doesn’t work in flat/strongly-recommended, although the official documentation says it should: https://eslint.vuejs.org/rules/. If I switch to vue3-strongly-recommended in flat config, the rule instantly applies.

I’m looking for a possible solution.

FabricJS: TextBox poorly rendered when overloading _renderBackground method

I want to add a box around a Fabric JS TextBox object.
But strange behavior (two vertical lines) occurs when I try to expand then collapse the TextBox along the horizontal axis.

Here is the code and the output :

fabric.CustomTextbox = fabric.util.createClass(fabric.Textbox, {
    type: 'CustomTextbox',

    initialize: function(text, options) {
        options || (options = {});
        this.callSuper('initialize', text, options);
        this.bgpad = options.bgpad || 10;

    },

    _renderBackground: function(ctx) {
        const w = this.width + this.bgpad * 2,
          h = this.height + this.bgpad * 2,
          x = -this.width / 2 - this.bgpad,
          y = -this.height / 2 - this.bgpad;

        ctx.beginPath();
        ctx.fillStyle = this.backgroundColor;
        ctx.roundRect(x, y, w, h, 10);
        ctx.fill();
        ctx.closePath();
    },
});

let text =  new fabric.CustomTextbox('  ...  ', {
                fontSize: 14,
        fontWeight: 600,
        left: 100,
        top: 50,
        width: 100,
        backgroundColor: 'red',
     });
     
let canvas = new fabric.Canvas('mycanvas', { width: 1000, height: 1000});
canvas.add(text);
canvas.renderAll();
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
<canvas id="mycanvas"></canvas>

See the output textbox

How to Navigate and Click a Row in Vuetify v-data-table-server Using Keyboard in Vue 3

I’m working with Vue 3 and Vuetify, and I have a v-data-table-server component where users can click on rows to go to each user’s profile (triggered by the @click:row event). I want to enhance accessibility by allowing users to navigate through rows using the keyboard (Arrow keys) and trigger the row click using the Enter key. So far what works by default is pressing “space” and that makes the checkbox on the left of each row to be checked… Pressing “enter” does not do anything.

What I have is this:

<template>
  <v-data-table-server
    class="result-table"
    @click:row="handleRowClick"
    data-testid="result-table"
    density="compact"
    :headers="headers"
    :items="items"
    :items-length="totalItems"
    :items-per-page="itemsPerPage"
    :items-per-page-options="[30, 50, 100, 300]"
    :items-per-page-text="$t('itemsPerPage')"
    :item-value="itemValuePath"
    :page="currentPage"
    ref="v-data-table-server"
    select-strategy="page"
    :showCurrentPage="true"
    show-select
    :sort-by="currentSort ? [currentSort] : []"
    @update:options="onUpdateOptions"
    @update:page="(page: number) => $emit('onPageUpdate', page)"
    @update:itemsPerPage="(limit: number) => $emit('onItemsPerPageUpdate', limit)"
    :no-data-text="$t('noDataFound')"
  >
    <template
      v-for="(_, name) in $slots as unknown as Readonly<Slots>"
      #[name]="slotProps"
    >
      <slot
        :name="name"
        v-bind="slotProps"
      />
    </template>
  </v-data-table-server>
</template>

Chartjs only showing first digit in data

I am making a stacked chart to display how many hours have been made on a project. The only problem is that chartjs is only displaying the first digit of the data. So it’s not that it can’t read the data, it just only reads the first digit.

Here is my chartjs code. Added array for simplicity.

var datasetes= new Array();
datasets[0] = [
    "label" => "roland",
    "data" => "336",
];
datasets[0] = [
    "label" => "roland",
    "data" => "336",
];
datasets[1] = [
    "label" => "koen",
      "data" => "2",
];
datasets[2] = [
    "label" => "gerald",
    "data" => "43",
];

var total = 645; // Does not matter right now what the total is.

var ctx = document.getElementById('projectOfferte').getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['medewerkers'],
                    datasets: datasetes,
                },
                options: {
                    plugins: {
                        title: {
                            display: true,
                            text: "Totaal Aantal uur: "+total ,
                            position: 'top',
                            align: 'start',
                        },
                    },
                    scales: {
                        y: {
                            stacked: true,
                        },
                        x: {
                            stacked: true
                        }
                    }
                }
            })

Image of chart

I tried making the data as an interger, but then it does not even display the data.

MVC catch event when browser back button is clicked

I am doing an MVC 6 Application.

I have a primary Menu and Secondary Menu in _layout Page. When I click the secondary Menu, I navigate within the pages of that menu.
I use a function to detect the browser’s Back button and I can catch the event before returning to the previous page and being able to redirect to another page or do some other thing.

This is the function I have in all the pages

var backButtonHandler = 'SearchResult';// change name for every page
 var backHandledSearchResult = false;
  
 $(function () {
     if (window.history && window.history.pushState) {
         window.history.pushState('', null, './');
         $(window).on('popstate', function () {
             if (backButtonHandler == 'SearchResult' && !backHandledSearchResult) {
                 backHandledSearchResult = true;
                     BackToView();
                 }
             }
         });
     }
 });

So every time I click Back button, the function BacktoView() is executed.

The problem I have is that when I click the different options of the Primary menu, the popstate does not change so I can not catch the Browser Back button and do whatever I need.

Every Main Option menu, when it is clicked has it own Landing Page.

The only thing I found to add in that landing pages, reading all the post is this

if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
    //do something
  }

But this is executed after the Landing Page is reloading. I need a way to make popstate works when the URL does not change, or something similar.

Any Idea how can I make it work?

thanks

Access index 0 of array that has numbered keys starting at unknown values

I have an object that is generated in php that looks something like:

Object { 1: {…}, 2: {…}, 3: {…} etc..}

It is sent from the backend to the vue.js frontend, where it’s iterated through and put into some charts.

I have a filter set up that filters based on content within the objects, but I’m having an issue with the keys that the objects are sent with. As soon as I filter, any loops that I have that require using the indices of the objects to access them break.

For example, say I have a loop like:

for (let i = 0; i < Object.keys(this.data).length; i++) {
   return this.data[i]; //or whatever
}

Because the backend sends the data with preexisting numbered keys, if the filter results in a set of objects that are no longer numbered 0, 1, 2, 3, 4 etc but are instead something like 3,5,6,8 then the loops will break because it will look for index [0] and not find it.

What’s the best way to handle this in javascript? Can I strip the object of the keys? Or ignore the keys and still look for this.data[0] in some way that ignores the numbered keys?

Website opens with different settings just before it refreshes

I made a personal portfolio site. When I open my website on a different browser, the font and other settings look differently to what I set them just 1-2 seconds before they are refreshed into the desired settings.

This is my code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>...</title>
    <link href="https://fonts.googleapis.com/css2?family=Caveat:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
  </head>
<body>
  <nav>
    <ul>
      <li><a href="#home">Home</a></li>
      <li><a href="#projects">OS Projects</a></li>
      <li><a href="#education">Education</a></li>
      <li><a href="#experience">Industry</a></li>
      <li><a href="#awards">Awards</a></li>
    </ul>
  </nav>

  <div class="main-container">
    <aside class="static-left">
      <img src="assets/AI-me2-transparent.jpg" alt="Levent Özbek" class="profile-picture">
      <div class="contact-info">
        <p>...</p>
      </div>
    </aside>

    <div class="scrollable-right">
      <section id="home" class="section">
        <h1>...</h1>
        <p>...</p>
      </section>

      <section id="projects" class="section">
        <h1>Open Source Projects</h1>
        <div id="project-list">
          <p>Projects will be dynamically loaded here...</p>
        </div>
      </section>

      <section id="education" class="section">
        <h1>Education</h1>
        <div class="education-list">
          <div class="education-item">...</div>
          <div class="education-item">...</div>
        </div>
      </section>

      <section id="experience" class="section">
        <h1>Industry</h1>
        <div class="experience-list">
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
          <div class="experience-item">...</div>
        </div>
      </section>

      <section id="awards" class="section">
        <h1>Awards</h1>
        <div class="awards-list">
          <div class="award-item">...</div>
          <div class="award-item">...</div>
        </div>
      </section>
    </div>
  </div>

  <script src="script.js"></script>
</body>
</html>

style.css

/* General Reset */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* Global Body Styles */
body {
  font-family: 'Caveat', cursive; /* Apply the Caveat font globally */
  background-color: white;
  color: black;
  line-height: 1.6;
  scroll-behavior: smooth;
}

/* Navigation Bar */
nav {
  position: fixed;
  top: 0;
  right: 20px;
  background-color: white;
  z-index: 1000;
}

nav ul {
  list-style: none;
  display: flex;
  flex-direction: row;
  gap: 10px;
}

nav ul li a {
  text-decoration: none;
  font-weight: bold;
  color: black;
  font-size: 1.5rem;
}

nav ul li a:hover {
  text-decoration: underline;
}

/* Main Layout */
.main-container {
  display: flex;
  height: 100vh;
}

/* Static Left Section */
.static-left {
  position: fixed;
  left: 0;
  top: 0;
  width: 30%;
  height: 100vh;
  background-color: white;
  padding: 20px;
  overflow: hidden;
  border-right: 1px solid #ddd;
}

.profile-picture {
  width: 200px;
  height: 250px;
  object-fit: cover; /* Ensures the image scales properly within the dimensions */
  border: 3px solid black; /* Keeps the border */
  margin-bottom: 20px;
}


.contact-info {
  font-size: 1.2rem;
  line-height: 1.8;
}

.contact-info a {
  color: black;
  text-decoration: none;
  font-weight: bold;
}

.contact-info a:hover {
  text-decoration: underline;
}

/* Scrollable Right Content */
.scrollable-right {
  margin-left: 30%;
  width: 70%;
  padding: 20px;
  overflow-y: auto;
}

h1, h2, h3 {
  font-family: 'Caveat', cursive;
}

.section {
  padding: 50px 20px;
  border-bottom: 1px solid #ddd;
}

.section h1 {
  font-size: 3rem;
  margin-bottom: 20px;
}

.section p {
  font-size: 1.5rem;
  font-family: 'Caveat', cursive;
}

/* Projects Section */
#projects h1 {
  font-size: 3rem;
  margin-bottom: 20px;
}

#project-list {
  display: flex;
  flex-direction: column;
  gap: 20px; /* Add spacing between projects */
}

.project-item {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #f9f9f9;
}

.project-item h3 {
  font-size: 2rem;
  margin-bottom: 10px;
}

.project-item p {
  font-size: 1.4rem;
  margin-bottom: 10px;
}

.project-item a {
  text-decoration: none;
  font-size: 1.2rem;
  font-weight: bold;
  color: black;
}

.project-item a:hover {
  text-decoration: underline;
}

/* Education Section */
.education-list {
  display: flex;
  flex-direction: column;
  gap: 20px; /* Add spacing between education entries */
}

.education-item {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #f9f9f9;
}

.education-item h2 {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 10px;
}

.education-item p {
  font-size: 1.5rem;
}

/* Experience Section */
.experience-list {
  display: flex;
  flex-direction: column;
  gap: 20px; /* Add spacing between experience entries */
}

.experience-item {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #f9f9f9;
}

.experience-item h2 {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 10px;
}

.experience-item p {
  font-size: 1.5rem;
}

.experience-item ul {
  list-style: disc;
  padding-left: 20px;
  margin-top: 10px; /* Add spacing above the list */
}

.experience-item ul li {
  margin-bottom: 5px;
  font-size: 1.4rem;
}

/* Awards Section */
.awards-list {
  display: flex;
  flex-direction: column;
  gap: 20px; /* Add spacing between award entries */
}

.award-item {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #f9f9f9;
}

.award-item h2 {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 10px;
}

.award-item p {
  font-size: 1.5rem;
}

/* Scrollbar Styling (Optional) */
.scrollable-right::-webkit-scrollbar {
  width: 8px;
}

.scrollable-right::-webkit-scrollbar-thumb {
  background-color: #888;
  border-radius: 4px;
}

.scrollable-right::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

@media (max-width: 768px) {
  /* General layout stacking for mobile */
  .main-container {
    flex-direction: column; /* Stack items vertically */
    align-items: center; /* Center-align content for a clean look */
  }

  /* Static-left adjustments */
  .static-left {
    position: relative; /* Remove fixed positioning */
    width: 100%; /* Full width for mobile */
    text-align: center; /* Center-align content */
    padding: 20px 10px;
    border: none; /* Remove border on mobile */
    overflow: visible; /* Ensure content is not clipped */
  }

  /* Profile picture adjustments */
  .static-left .profile-picture {
    width: 150px; /* Reduce image size for smaller screens */
    height: auto; /* Maintain aspect ratio */
    margin: 0 auto; /* Center the image */
    display: block; /* Ensures it's treated as a block-level element */
    z-index: 1; /* Bring it to the front */
  }

  /* Ensure contact info is visible */
  .static-left .contact-info {
    margin-top: 20px; /* Add spacing below the profile picture */
    font-size: 1.2rem; /* Adjust for readability */
    line-height: 1.8;
  }

  /* Scrollable-right adjustments */
  .scrollable-right {
    margin-left: 0; /* Remove margin for stacked layout */
    width: 100%; /* Full width for mobile */
    padding: 20px 10px;
    overflow: visible; /* Allow content to flow naturally */
  }

  /* Navigation */
  nav {
    position: static; /* Remove fixed positioning */
    width: 100%;
    text-align: center;
    padding: 10px 0;
    border-bottom: 1px solid black;
  }

  nav ul {
    flex-direction: row;
    justify-content: center;
    gap: 15px;
  }

  nav ul li a {
    font-size: 1.2rem;
  }

  /* Section padding adjustments for mobile */
  .section {
    padding: 20px 10px; /* Adjust padding for smaller screens */
  }

  .section h1 {
    font-size: 2.5rem; /* Slightly smaller headings for mobile */
  }

  .section p {
    font-size: 1.2rem; /* Smaller font for better readability */
  }
}

and this is script.js:

document.addEventListener("DOMContentLoaded", () => {
  // Fetch and display projects from projects.json
  fetch("projects.json")
    .then((response) => response.json())
    .then((data) => populateProjects(data.projects))
    .catch((error) => console.error("Error loading projects.json:", error));

  function populateProjects(projects) {
    const projectList = document.getElementById("project-list");
    if (!projectList) return;

    projectList.innerHTML = ""; // Clear placeholder

    projects.forEach((project) => {
      const projectItem = document.createElement("div");
      projectItem.className = "project-item";

      projectItem.innerHTML = `
        <h3>${project.name}</h3>
        <p>${project.description}</p>
        ${
          project.link
            ? `<a href="${project.link}" target="_blank">View Project</a>`
            : ""
        }
      `;

      projectList.appendChild(projectItem);
    });
  }
});

I did omit the personal details for brevity.
I am using dreamhost as my provider. I don’t know if that has something to do with it.

intl-tel-input library is always giving me invalid number error

I’m using intl-tel-input library. I found this library by chance, and since I liked it from the beginning I tried to use it.

Here you can find the documentation: Documentation

As you can see from the code mentioned below, if you try to insert the number (for example an Italian number, 3250001100) I get the following message:

Invalid number. Please try again.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/build/css/intlTelInput.css">

    <title>IntlTelInput</title>
</head>

<body>
    <p id="message"></p>

    <form id="form">
        <input id="phone" type="tel" name="phone" />
        <button class="button" type="submit">Submit</button>
    </form>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/js/intlTelInput.min.js"></script>
    <script>
        const input = document.querySelector("#phone");
        const form = document.querySelector("#form");
        const message = document.querySelector("#message");

        const iti = window.intlTelInput(input, {
            initialCountry: "it",
            loadUtilsOnInit: "/intl-tel-input/js/utils.js?1730730622316" // just for formatting/placeholders etc
        });

        form.onsubmit = () => {
            if (!iti.isValidNumber()) {
                message.innerHTML = "Invalid number. Please try again.";
                return false;
            }
        };

        const urlParams = new URLSearchParams(window.location.search);
        const fullPhone = urlParams.get('full_phone')
        if (fullPhone) {
            message.innerHTML = `Submitted hidden input value: ${fullPhone}`;
        }
    </script>
</body>

</html>

Can someone tell me why I always get the error?

Thanks to everyone in advance, beautiful people!

What is `var`, `let`, `const` in JavaScript? [duplicate]

I’m trying to understand the difference between the let, var and const keywords in JavaScript. What are the main aspects that change from each other and how should each be used in my code?

my code:

function testVariables() {
    if (true) {
        var x = 10;
        let y = 20;
        const z = 30;
    }

    console.log(x);
    console.log(y);
    console.log(z);
}

testVariables();

Uncaught ReferenceError: y is not defined
    at testVariables (index.html:18:25)
    at index.html:22:9

Nodemon not restarting after making changes locally in docker

I want to use nodemon on the docker environment using volume such that if I make any changes locally it will get reflected on the built container.I have tried multiple ways and also did previous stack overflow solution and still didn’t get the outcome I was looking for.

This is my dockerfile

FROM node:latest
RUN npm install -g nodemon
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD ["npm" , "run" , "dev"]

index.js

import express from 'express';

const app = express();

app.get('/', (req, res) => {

    res.json([{
        id: 1,
        name: "Maadasdsasdasnk",
        age: 205
    }, {
        id: 2,
        name: "Tsar",
        age: 24
    }, {
        id: 3,
        name: "Vansh",
        age: 21
    }, {
        id: 4,
        name: "Aditya",
        age: 22
    }])
});

app.listen(3000, (req,res)=>{
    console.log("Server is running on 3000")
})

package.json

{
  "name": "basic-app",
  "version": "1.0.0",
  "description": "docker tutorial",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "nodemon -L index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.21.1",
    "nodemon": "^3.1.7"
  }
}

Command I am using to create volume

docker run --name basic-container -p 3000:3000 --rm -v UsersWelcomeDesktopDockerbasic-app:/app basic-app

Async function that depends on setState

I have code that’s structured like the following.

Parent component:

useState(intialValue)

asyncFunction() {
  do something with State
}

Child component:

State = useContext()

syncFunction() {
  setState(newValue)
  asyncFunction()
}

So far it’s been working as intended, but I’m unsure of if it’s designed badly. Since both setState and the asyncFunction are async, can I run into a scenario where the async function runs before state’s been updated with the new value?

Error displaying createAt Date in NextJs from Mongo

When i try to log whole mongo table it logs everything in it, but when i separatly try to log user.createdAt it logs undefined
When i use user.createdAt.toString() it shows error (toString for undefined)

When using Date(user.createdAt) works fine but the new problem is
I have 6 user details
Only 1 of it has createAt field and its value date. But it logs 6 times and same date for 6 users, but actually the other user doesn’t even have the createdAt field. I am using nextjs project and array map to render it in a table of users

const users = await fetchUsers();

console.log(users);


{users.map(user => (

    <tr key={user.id}>

        <td>

            <div className={styles.user}>

                <Image src={user.img || "/noavatar.png"} alt="userAvatar" width={40} height={40} className={styles.userImage} />

                {user.username}

            </div>

        </td>

        <td>{user.email}</td>

        <td>{user.createdAt?.toString().slice(4,16)}</td>

        <td>{user.isAdmin ? "Admin" : "Client"}</td>

        <td>{user.isActive ? "Active" : "Passive"}</td>

        <td>

            <div className={styles.buttons}>

                <Link href={`/dashboard/users/${user.id}`}>

                    <button className={`${styles.button} ${styles.view}`} >VIEW</button>

                </Link>

                <Link href="/">

                    <button className={`${styles.button} ${styles.delete}`} >DELETE</button>

                </Link>

            </div>

        </td>

    </tr>

))}

I tried logging with conditions but it like somekind of undefined data

Is there other ways to convert Unix timestamp to local time in javascript with openWeather API timezone involved?

I’m using the OpenWeather API to create a simple web page that displays dynamic weather data, including sunrise and sunset times. The API provides these times in seconds (Unix timestamp), and I’ve attempted to convert them to the local time for each city. However, I’m not sure if my conversion is accurate.

For example, the API gives me the sunrise in Toronto as 2:00 AM and sunset as 11:00 AM. However, according to Google (for today), the sunrise in Toronto should be 7:26 AM, and the sunset should be 4:44 PM.

Here is my code snippet

var timezoneOffset = weatherData.timezone; // Offset in seconds
var sunriseDate = new Date((weatherData.sys.sunrise + timezoneOffset) * 1000)
            .toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
var sunsetDate = new Date((weatherData.sys.sunset + timezoneOffset) * 1000)
            .toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

console.log(sunriseDate);
console.log(sunsetDate);

I want to be sure that this code is giving the right output.

How to check if an item is in the root folder?

How to check if an item is in the root folder?
I have an array with all folders allFolders, from it I need to get the ROOT folder, knowing only one of the subfolders

const selectedFolder = {id: 6, parent_id: 5, children: []};

const allFolders = [
  {
    id: 1, // ROOT
    parent_id: null,
    children: [
      {
        id: 2,
        parent_id: 1,
        children: [{ id: 3, parent_id: 2, children: [] }],
      },
    ],
  },
  {
    id: 4, // ROOT
    parent_id: null,
    children: [
      {
        id: 5,
        parent_id: 4,
        children: [{ id: 6, parent_id: 5, children: [] }],
      },
    ],
  },
];

I need to get the root folder knowing only one of the subfolders, now I’m trying to do this:

let nestedFolderMove = [];
     const addChild = el => {
     if (selectedFolder?.parent_id === el?.id) {
       nestedFolderMove.push(...el.children);
     }
       return el.children.map(addChild).flat();
     };

allFolders?.map(addChild).flat(); // need root {id: 4, parent_id: null, children: ...}