Dynamic roulette in html css js (WITHOUT CANVAS)

I need a way to create a roulette in css html js but without using canvas and that is dynamic.

I can’t find anything about how to do this but DYNAMIC.

NO CANVAS

So far I have only been able to do this, but they are not even the same size and it is not adaptable at all, because if you put 10 elements they overlap.

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Div</title>

</head>
<body>

    <div class="roulette">
        <div class="element" style="--i: 0; background: #00aeff;"></div>
        <div class="element" style="--i: 1; background: #2f00ff;"></div>
        <div class="element" style="--i: 2; background: #00ff95;"></div>
        <div class="element" style="--i: 3; background: #eeff00; "></div>
        <div class="element" style="--i: 4; background: #ff00dd;"></div>
        <div class="element" style="--i: 5; background: red;"></div>
    </div>

</body>
</html>

<style>
*{
    --size: 80px;
    --n: 6;
    --degs:calc(360 / var(--n));
}


.roulette{
    width: calc(var(--size) * 2);
    height: calc(var(--size) * 2);
    position: relative;
    border-radius: 50%;
    overflow: hidden;
    background: black;
} 

.element{
    width: var(--size);
    height: var(--size);
    position: absolute;
    transform-origin: bottom right;
    transform: rotate(calc(var(--i) * var(--degs) * 1deg));
}

mongoose not updating document using findOneAndUpdate

I’m trying to update a document in my event schema when a successful order is placed. I want to make ‘isPurchased’ to true so the product can no longer be purchased but when i set it it stays as false. What am i doing wrong here?

Here is the action

export const createOrder = async (order: CreateOrderParams) => {
  try {
    await connectToDatabase();

    const eventId = order.eventId

    const updatedEvent = await Event.findOneAndUpdate(
      {eventId},
     { $set: { isPurchased: true } },
     {new:true}
   )
    
    const newOrder = await Order.create({
      ...order,
      event: order.eventId,
      buyer: order.buyerId,
    });

    console.log(updatedEvent)
    
    return {
      order: JSON.parse(JSON.stringify(newOrder)),
      updated: JSON.parse(JSON.stringify(updatedEvent))
    }
  } catch (error) {
    handleError(error);
  }
}

here is the schema for the ‘Event’ model

import { Document, Schema, model, models } from "mongoose";

export interface IEvent extends Document {
  _id: string;
  title: string;
  seatInfo: string;
  location: string;
  createdAt: Date;
  startDateTime: Date;
  ticketUrl:string;
  price: string;
  quantity: string;
  seller: { _id: string, firstName: string, lastName: string };
  isPurchased:boolean;
}

const EventSchema = new Schema({
  title: { type: String, required: true },
  seatInfo: { type: String },
  location: { type: String },
  createdAt: { type: Date, default: Date.now },
  startDateTime: { type: Date, default: Date.now },
  ticketUrl: {type: String },
  price: { type: String },
  quantity: {type: String },
  seller: { type: Schema.Types.ObjectId, ref: 'User' },
  isPurchased: {type:Boolean, default:false}
})

const Event = models.Event || model('Event', EventSchema);

export default Event;

finally here are the params used in the action

export type CreateOrderParams = {
  stripeId: string
  eventId: string
  buyerId: string
  totalAmount: string
  createdAt: Date
}

I tried the findOneAndUpdate as well as findByIdAndUpdate but it is not changing isPurchased to true. It is only creating the order which is fine, and creating the order in the MongoDB Database.

how can i use swiperjs to make the arrows work as intended

I am trying to make a website using html,css and js, and i try using swiperjs to make the arrows work but i cant seem to catch it. From what i tried, i can make the “Sports” movable from left to right or vice-versa, but i cant make the arrows look the same. The sports needs to be seen 3 on the screen, and another number added so that when you press right for example, it will show the next sport.

I am expecting to make the arrows work as intented, and still look how i want them to look.
what i triedhow i want them to look

How to convert mm to px, rem or em in html page

I know this is a recurring issue and perhaps there is no solution, I’ve seen other posts here and they didn’t solve my problem. But I need to make an HTML page that has 2 inputs (height and width) and below there is a rectangle that will be the same as the measurement given above, but the user has entered the measurements in millimeters and I am unable to convert these values ​​to px, rem or em (it doesn’t matter what), in fact I can do it on my monitor but when I change PC it doesn’t work. Any idea ?
I’m building the page in html and javascript only.

I already tried to get the monitor size but using the window.innerHtml or outerHTML method it didn’t work.

injecting javascript on samsung internet browser?

Is there any way to inject JS in websites on Samsung internet browser anymore? They patched bookmarklets a year ago as a “vulnerability” (So now you can’t run javascript: bookmarks)

Extensions are propietary and you can’t add third party ones it seems

I’ve tried looking to make either extensions, userscripts or others to inject JS on websites like custom playback speed script for YouTube. However it doesn’t seem like I can inject JS in any way on Samsung Internet Browser

How to let the browser handle video downloads directly in a Next.js application using ytdl-core?

I’m building a video downloader application with Next.js and ytdl-core where users can download YouTube videos. Currently, the server handles the video download, which is inefficient for longer videos due to processing time and potential errors. I want the browser to handle the download directly to improve performance and reliability.

I wanna know if this is possible using Next.js. or if other popular websites have their own private libraries instead of open source library like ytdl-core.

Current Backend Code:

API Endpoint for video info:


export async function POST(req: NextRequest) {
  const body = await req.json();
  const url = body.url;

  if (!ytdl.validateURL(url)) {
    return new NextResponse(
      JSON.stringify({
        error: 'Invalid URL provided. Please provide a valid YouTube URL.',
      }),
      {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      }
    );
  }

  try {
    const info = await ytdl.getInfo(url);
    const formats = ytdl.filterFormats(info.formats, 'audioandvideo');
    return new NextResponse(
      JSON.stringify({ videoDetails: info.videoDetails, formats }),
      {
        headers: { 'Content-Type': 'application/json' },
      }
    );
  } catch (error) {
    return new NextResponse(
      JSON.stringify({ error: 'Failed to fetch video information' }),
      {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      }
    );
  }
}

API Endpoint for downloading:

async function streamToBuffer(stream: Readable): Promise<Buffer> {
  const chunks: Buffer[] = [];
  for await (const chunk of stream) {
    chunks.push(Buffer.from(chunk));
  }
  return Buffer.concat(chunks);
}

export async function POST(req: NextRequest) {
  const body = await req.json();
  const url: string = body.url;
  const itag: number = parseInt(body.itag, 10);

  if (!ytdl.validateURL(url)) {
    return new NextResponse(
      JSON.stringify({
        error: 'Invalid URL provided. Please provide a valid YouTube URL.',
      }),
      {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      }
    );
  }

  try {
    const info = await ytdl.getInfo(url);
    const format = info.formats.find((f) => f.itag === itag);

    if (!format) {
      return new NextResponse(
        JSON.stringify({ error: 'Format not available' }),
        {
          status: 404,
          headers: { 'Content-Type': 'application/json' },
        }
      );
    }

    const videoStream = ytdl.downloadFromInfo(info, { format });
    const videoBuffer = await streamToBuffer(videoStream);

    const headers = new Headers({
      'Content-Disposition': `attachment; filename="${info.videoDetails.title}.${format.container}"`,
      'Content-Type': 'application/octet-stream', // or the specific media type
      'Content-Length': videoBuffer.length.toString(),
    });

    return new NextResponse(videoBuffer, { headers });
  } catch (error) {
    return new NextResponse(
      JSON.stringify({ error: 'Failed to download video' }),
      {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      }
    );
  }
}

Current Frontend Code:

This function is to get the video information to display the title and the thumbnail in the ui:

const getVideoInformation = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/video-info', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ url: videoUrl }),
      });

      if (response.ok) {
        const data = await response.json();
        console.log(data);
        setVideoDetails({
          title: data.videoDetails.title,
          thumbnail:
            data.videoDetails.thumbnails[
              data.videoDetails.thumbnails.length - 1
            ].url,
          duration: formatDuration(data.videoDetails.lengthSeconds),
        });

        setAvailableFormats(
          data.formats.map((format: any) => ({
            itag: format.itag,
            quality: format.qualityLabel,
            container: format.container,
            hasAudio: format.hasAudio,
            hasVideo: format.hasVideo,
            audioQuality: format.audioQuality,
            url: format.url,
            mimeType: format.mimeType,
          }))
        );
      } else {
        const errorResponse = await response.json();
        console.error(
          'Failed to fetch video information:',
          errorResponse.error
        );
        toast.error(errorResponse.error || 'An unexpected error occurred');
      }
    } catch (error) {
      console.error(error);
      toast.error(
        'Failed to connect to the service. Please check your network.'
      );
    } finally {
      setIsLoading(false);
    }
  };

And this function is to download the video after selecting the desired format:

const downloadVideo = async () => {
    if (!videoUrl) return;

    if (!selectedItag) {
      setIsFormatSelectedError(true);
      toast.error('Please select a format to download');
      return;
    }

    try {
      setIsDownloading(true);
      handleVideoProgress();
      const response = await fetch('/api/download', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ url: videoUrl, itag: selectedItag }),
      });

      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${videoDetails?.title}.${
          availableFormats.find((format) => format.itag === selectedItag)
            ?.container
        }`;
        a.click();
        window.URL.revokeObjectURL(url);
        setProgressValue(100);
      } else {
        const errorResponse = await response.json(); // Parse the JSON error response
        console.error('Failed to download video:', errorResponse.error);
        toast.error(errorResponse.error || 'An unexpected error occurred');
      }
    } catch (error) {
      console.error('Error downloading video:', error);
      toast.error('Failed to download the video. Please try again.');
    } finally {
      setIsDownloading(false);
    }
  };

I attempted to use an anchor <a> tag with the href set to the video URL and the download attribute, but it only plays the video instead of prompting for download.

Thank you in advance!

Can’t open another modal in Magnific Pop Up library (Uncaught TypeError: Cannot read properties of null (reading ‘type’))

I am trying to have a button, that is already inside a popup modal, to close the current modal and open another modal.

Here is the HTML:

<div class="portfolio_navigation">
         <div class="nav_item prev-project">
               <a class="project" data-mfp-src="#project1-wrapper">
                   <i class="fas fa-arrow-left"></i>
                   <div class="nav_project">
                        <div class="label">Previous Project</div>
                        <h3 class="title">Project 1</h3>
                   </div>
               </a>
        </div>
</div>

Here is the javascript:

        $(".modal-popup").magnificPopup({
            type: "inline",
            fixedContentPos: false,
            fixedBgPos: true,
            overflowY: "auto",
            closeBtnInside: true,
            preloader: false,
            midClick: true,
            removalDelay: 300,
            mainClass: "popup-mfp",
        });

        $(".project").magnificPopup({
            type: "inline",
            fixedContentPos: false,
            fixedBgPos: true,
            overflowY: "auto",
            closeBtnInside: true,
            preloader: false,
            midClick: true,
            removalDelay: 300,
            mainClass: "popup-mfp",
        });
        
        $('.project').on('click', function(e) {
            e.preventDefault();
            if ($.magnificPopup.instance && $.magnificPopup.instance.isOpen) {
                $.magnificPopup.close();
            }
            var targetModal = $(this).data('mfp-src');
            if (targetModal && $(targetModal).length > 0) {
                $.magnificPopup.open({
                    items: {
                        src: targetModal
                    },
                    type: 'inline'
                });
            }
        });
    

The modal closes perfectly, and the targetModal variable is fetched correctly, however, the new modal is not opening at all.

With the current code, when I click on the .project, it closes all modals with no error, but if I try to open any modal I get this error:

Uncaught TypeError: Cannot read properties of null (reading 'inline')  magnific-popup.js:200    
     at t.updateItemHTML (magnific-popup.js:200:28)     
     at t.open (magnific-popup.js:67:31)
     at t._openClick (magnific-popup.js:273:19)
     at HTMLButtonElement.d (magnific-popup.js:249:19)
     at HTMLButtonElement.dispatch (jquery.min.js:1924:100)
     at v.handle (jquery.min.js:1856:106)

This breaks the project, as I need it to not just close, but also open another modal popup.

If I remove the

$(".project").magnificPopup({
    type: "inline",
    fixedContentPos: false,
    fixedBgPos: true,
    overflowY: "auto",
    closeBtnInside: true,
    preloader: false,
    midClick: true,
    removalDelay: 300,
    mainClass: "popup-mfp",
});

the first modal closes but I instantly get this error:

Uncaught TypeError: Cannot read properties of null (reading 'type')
     at t._close (magnific-popup.js:173:84)
     at magnific-popup.js:150:19

why is the

$.magnificPopup.open({
items: {
src: '#pomodoro-wrapper'
},
type: 'inline'
});

Not working properly?

HTML images don’t scale correctly in flex boxes

I have the following code (simplified, I actually get the images from a server). The goal is to have the images shrink and grow to fill the entirety of the input_socket while keeping the buttons aligned to the left and right side. As you can see in the snippet, however, the image doesn’t scale and forces everything around it to move.

I’ve tried a bunch of things (I made another post about it a bit ago), but everything I try isn’t what I’m after (like simply hiding the excess instead of shrinking it). Am I using the wrong things here? Is the flex properties not what I want?

Any help at all would be greatly appreciated! (Also, apologies if I didn’t simply the .css enough! I didn’t want to accidentally give too little information.)

function moveSocketLeft() {
  index = index - 1 <= 0 ? placeholders.length - 1 : index - 1;
  img = document.getElementById('socket-image');
  img.src = placeholders[index]
}

function moveSocketRight() {
  index = index + 1 => placeholders.length ? 0 : index + 1;
  img = document.getElementById('socket-image');
  img.src = placeholders[index]
}


var index = 0;

const placeholders = [
  'https://place-hold.it/500x300', 
  'https://place-hold.it/300x500', 
  'https://place-hold.it/200x700',
  'https://place-hold.it/700x200', 
  'https://place-hold.it/900x1600', 
  'https://place-hold.it/1600x900'
];
/* General */

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

:root {
  --background-color: #0f0f0f;
  --foreground-color: #282828;
  --text-color: #f1f1f1;
}

body {
  background-color: var(--background-color);
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  font-size: 16px;
  line-height: 1.5;
  color: var(--text-color)
}


/* Top - Media Viewer */

.media-bar {
  height: 60vh;
  display: flex;
}


/* Viewer */

.media-viewer {
  width: 40vh;
  margin: 5px;
  outline: 2px solid var(--foreground-color);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.action-bar {
  margin: 3px;
  height: 30px;
  background-color: transparent;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn-action {
  margin-left: 3px;
  height: 24px;
  background-color: var(--foreground-color);
  border: transparent;
  border-radius: 5px;
  opacity: 50;
  color: var(--text-color);
}

.media-socket {
  margin: 0px 3px;
  background-color: var(--background-color);
  min-height: 300px;
  /* Temp */
  display: flex;
  flex-direction: row;
  justify-content: center;
  text-align: center;
  align-items: center;
}

.input-socket {
  width: 1250px;
  height: 100%;
  flex-shrink: 1;
  justify-content: center;
}

.input-socket-item {
  max-height: 100%;
}

.btn-socket {
  margin: 3px;
  height: 30px;
  width: 30px;
  background-color: var(--foreground-color);
  border: transparent;
  border-radius: 5px;
  opacity: 0.5;
  color: var(--text-color);
}

.media-selector {
  margin: 3px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.btn-selector {
  width: 75px;
  border: transparent;
  background-color: transparent;
  color: var(--text-color);
  text-decoration: underline;
}


/* Editor */

.media-editor {
  width: 60vh;
  margin: 5px;
  display: flex;
  flex-direction: column;
  outline: 2px solid var(--foreground-color);
  border-radius: 5px;
}


/* Middle - Album Bar */

.album-bar {
  height: 15vh;
  display: flex;
}

.fav-socket {
  width: 15vh;
  margin: 5px;
  outline: 2px solid var(--foreground-color);
  border-radius: 5px;
}

.albums {
  margin: 5px;
  flex: 1;
  display: flex;
  flex-direction: row;
  flex-grow: 1;
  align-items: center;
  outline: 2px solid var(--foreground-color);
  border-radius: 5px;
}


/* Utils */

.display-text {
  margin: 3px;
}

.btn {
  min-width: 5px;
  min-height: 5px;
  padding: 3px;
  font: 16;
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Define And Conquer</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
  <script src="{{ url_for('static', filename='scripts.js') }}"></script>
</head>

<body>
  <div class="media-bar">
    <div class="media-viewer">
      <div class="action-bar">
        <p class="display-text" id="file_name">Filename</p>
        <div class="btn-container">
          <button class="btn btn-action">Fav</button>
          <button class="btn btn-action">Fullscreen</button>
        </div>
      </div>
      <div class="media-socket">
        <button class="btn btn-socket" onclick="moveSocketLeft()">&lt;</button>
        <div class="input-socket" id="input_socket">
          <img class="input-socket-item" id="socket_image" src="https://place-hold.it/500x300">
          <video class="input-socket-item" id="socket_video" display='none'></video>
        </div>
        <button class="btn btn-socket" onclick="moveSocketRight()">&gt;</button>
      </div>
      <div class="media-selector">
        <button class="btn btn-selector" id="first_media_selector">1</button>
        <p class="display-text">...</p>
        <button class="btn btn-selector" id="current_media_selector">2</button>
        <p class="display-text">...</p>
        <button class="btn btn-selector" id="last_media_selector">1386</button>
      </div>
    </div>
    <div class="media-editor">
    </div>
  </div>
  <div class="album-bar">
    <div class="fav-socket">
    </div>
    <div class="albums">
    </div>
  </div>
</body>

</html>

Enable/disable editable field based on another editable field value in the grid

In my Rails 7 application, I have a Stimulus JS controller that uses AG-Grid to create a table. Each row in the table has an edit button, allowing editing of EDITABLE_FIELDS which are:

const EDITABLE_FIELDS = [
  "cheque_number",
  "comment",
  "payment_amount",
  "payment_date",
  "payment_method",
]

The thing is that cheque_number should be editable only when payment_method is CHEQUE. So I’ve got below grid options to make it work:

// https://www.ag-grid.com/javascript-data-grid/reference-data/#using-the-refdata-property
function buildEditablePaymentMethodsCollDef(paymentMethods) {
  return {
    cellEditor: 'agSelectCellEditor',
    cellEditorParams: {
      values: Object.keys(paymentMethods),
      useFormatter: true
    },
    editable: true,
    refData: paymentMethods,
    cellRenderer(params) {
      return paymentMethods[params.value]
    },
}
(...)

const columnOptions = {
  columnDefs: {
    cheque_number: { ...EDITABLE_TEXT_COL_DEF, cellClass: 'font-mono', maxWidth: 300, sortable: true, editable: params => params.data.payment_method === 'CHEQUE' },
    (...)
    payment_method: { cellClass: 'font-mono', maxWidth: 300, sortable: true },`

It works well, but payment_method is also an editable field. So, when a user changes it to CHEQUE (chosen from the dropdown), the cheque number field should become available as well. Currently, if the payment method is CHEQUE by default, it works fine. However, when a user changes it from, say, Wire to Cheque, the editable form for the cheque number doesn’t show up.

How can I call an exposed function of a vue component in a default slot?

I have a vue playground.

ChildA and ChildB both expose a function called interfaceFunction.

I can call this function from App by getting a reference to the component. With the reference, I can call the function directly.

I would like Container to be able to call this function of the children in its default slot. How can Container get a reference to the components and call the function?

App.vue

<script setup>
import { ref} from 'vue'

import Container from './Container.vue'
import ChildA from './ChildA.vue'
import ChildB from './ChildB.vue'

const childa = ref(null)

function callInterfaceFunction() {
    childa.value.interfaceFunction()
}
</script>

<template>
    <button @click="callInterfaceFunction">Call from App</button>

    <Container>
        <ChildA ref="childa"/>
        <ChildB />
    </Container>
</template>

Container.vue

<script setup>
import { useSlots} from 'vue'

const slots = useSlots()

function callInterfaceFunction() {
  const children = slots.default()

  for ( const child of children ) {
    child.interfaceFunction()
  }
}
</script>

<template>
  <button @click="callInterfaceFunction">Call from Container</button>

  <slot />
</template>

ChildA.vue

<script setup>

function interfaceFunction() {
  console.log( "Called interfaceFunction A" )
}

defineExpose({ interfaceFunction })
</script>

<template>
  <div>
    ChildA
  </div>
</template>

ChildB.vue

<script setup>

function interfaceFunction() {
  console.log( "Called interfaceFunction A" )
}

defineExpose({ interfaceFunction })
</script>

<template>
  <div>
    ChildB
  </div>
</template>

How can I send a nightly CSV report from one System that has no API’s to another system using JSON & target system’s POST call in their documentation

I am a business analyst with not much exposure to this type of programming work, but I am working with two vendor systems with the following requirements/steps:
(forgive me for my lack of knowledge in hosting and infrastructure here)

  1. System 1 (Source): Download a nightly Report with Appointment Data in CSV file

  2. Transform CSV File to JSON Format for uploading to Target System

  3. System 2 (Target): Use Vendor (Target) Provided POST Call to Send Appointment Data to Target System

How Far I’ve Gotten:

I’ve been able to test part of Step 3, all the way up to authentication and getting a hold of a token.

My question is… how do I download and call upon the Source Data on a nightly basis and how do I point to specific reports each night? Do I use python to retrieve the components nightly and write a script that transforms it into JSON format?

Where do I host a job like this if I want it running nightly?

In my previous role we used Informatica – but don’t have a tool like that at my current organization to facilitate ETL

Property “id” does not exist on type “UserContextType”

I got a problem at the eventSubmit the (user_id: user:id), i ever created an app similar to this before, before this i’ve done this part with no error, but when i try to make a new app, i got an Property “id” does not exist on type “UserContextType” error for the (user_id: user:id)

"use client";
import React, { useEffect, useState } from "react";
import Image from "next/image";
import { FieldValues, SubmitHandler, useForm } from "react-hook-form";
import { useSupabaseClient } from "@supabase/auth-helpers-react";
import { useRouter } from "next/navigation";
import { useUser } from "@/hooks/useUser";

const svg = {
  userDarken: require("@/shared/icons/user-darken.svg"),
  pillDarken: require("@/shared/icons/pill-darken.svg"),
  vaccineBottleDarken: require("@/shared/icons/vaccine-bottle-darken.svg"),
  calendarExclamationDarken: require("@/shared/icons/calendar-exclamation-darken.svg"),
  checkupListDarken: require("@/shared/icons/checkup-list-darken.svg"),
  plusSecondary: require("@/shared/icons/plus-secondary.svg"),
  xSecondary: require("@/shared/icons/x-secondary.svg"),
};

interface AddProviderProps {
  className: string;
  onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}

const ComponentAddProvider: React.FC<AddProviderProps> = ({
  className,
  onClick,
}) => {
  const [controlExpand, setControlExpand] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const supabaseClient = useSupabaseClient();
  const router = useRouter();
  const user = useUser();

  useEffect(() => {
    const controlExpandBreakpoint = window.innerWidth < 1024;
    setControlExpand(!controlExpandBreakpoint);
  }, []);

  const { register, handleSubmit, reset } = useForm<FieldValues>({
    defaultValues: {
      date_added: new Date().toISOString().split("T")[0],
      patient: "",
      medicine: "",
      dosage: "",
      dosage_unit: "Pilih Dosis",
      schedule: "Pilih Penjadwalan",
      notes: "",
    },
  });

  const eventSubmit: SubmitHandler<FieldValues> = async (values) => {
    try {
      setIsLoading(true);

      const { error: supabaseError } = await supabaseClient
        .from("reminders")
        .insert({
          user_id: user.id,
          date_added: values.date_added,
          patient: values.patient,
          medicine: values.medicine,
          dosage: values.dosage,
          dosage_unit: values.dosage_unit,
          schedule: values.schedule,
          notes: values.notes,
        });

      if (supabaseError) {
        setIsLoading(false);
        console.log(supabaseError.message);
      }

      router.refresh();
      reset();
    } catch (error) {
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <></>
  );
};

export default ComponentAddProvider;

And maybe you need useUser.tsx this for more information

import { UserDetails } from "@/types/types";
import { User } from "@supabase/auth-helpers-nextjs";
import {
  useSessionContext,
  useUser as useSupaUser,
} from "@supabase/auth-helpers-react";
import { createContext, useContext, useEffect, useState } from "react";

type UserContextType = {
  accessToken: string | null;
  user: User | null;
  userDetails: UserDetails | null;
  isLoading: boolean;
};

export const UserContext = createContext<UserContextType | undefined>(
  undefined
);

export interface Props {
  [propName: string]: any;
}

export const AppUserContextProvider = (props: Props) => {
  const {
    session,
    isLoading: isLoadingUser,
    supabaseClient: supabase,
  } = useSessionContext();
  const user = useSupaUser();
  const accessToken = session?.access_token ?? null;
  const [isLoadingData, setIsLoadingData] = useState(false);
  const [userDetails, setUserDetails] = useState<UserDetails | null>(null);

  const getUserDetails = () => supabase.from("users").select("*").single();

  useEffect(() => {
    if (user && !isLoadingData && !userDetails) {
      setIsLoadingData(true);

      Promise.allSettled([getUserDetails()]).then((results) => {
        const userDetailsPromise = results[0];

        if (userDetailsPromise.status === "fulfilled") {
          setUserDetails(userDetailsPromise.value.data as UserDetails);
        }

        setIsLoadingData(false);
      });
    } else if (!user && !isLoadingUser && !isLoadingData) {
      setUserDetails(null);
    }
  }, [user, isLoadingUser]);

  const value = {
    accessToken,
    user,
    userDetails,
    isLoading: isLoadingUser || isLoadingData,
  };

  return <UserContext.Provider value={value} {...props} />;
};

export const useUser = () => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error(
      "useUser harus digunakan dalam jangkauan AppUserContextProvider"
    );
  }

  return context;
};

and maybe the types.ts

export interface UserDetails {
  id: string;
  first_name: string;
  last_name: string;
  full_name?: string;
  avatar_url?: string;
}

export interface ReminderDetails {
  id: string;
  user_id: string;
  date_added: string;
  patient: string;
  medicine: string;
  dosage: string;
  dosage_unit: string;
  schedule: string;
  notes: string;
}

i added the relation at the supabase, but nothing happened, the uuid still NULL at the row

Why was increment operator executed an extra time in the forEach loop? [closed]

I’m from python and I’m struggling to get JS basic in terms of scopes and closures.

I’m faced with a tricky moment using forEach loop.

let args = [{},null,"3"]

Case #1

var argumentsLength = function(...args) {

    let counter = 0;

    args.forEach((_) => {
        counter++;
    });

    return counter;
};

Result: 4

Case #2

let counter = 0;

var argumentsLength = function(...args) {
   
    args.forEach((_) => {
        counter++;
    });

    return counter;
};

Result: 3

In case #2, I had an extra executing of a increment operator. This is because of variable “`counter“`, but what the difference between declarating variables in block and outside the block. How does it work? And what I’ve to read to get this concept.

Inline script to randomize part of a sentence

I am building a webpage where I want to display parts of a sentence on page load/reload.

For example:

I love pasta with mushroom sauce

becomes this upon reload:

I love lentils with butter

Beginning text stays the same, and the randomized part changes from a list that is somewhere in the HTML code (otherwise it will be unmanageable).

I am trying to find the simplest and fastest solution to do this without having changes in the style of the division (I don’t want linebreaks or style changes between the static text and the random part, it needs to be seamless) and having all the code contained in one page (there won’t be more than 5 variables per sentence and less than 10 sentences in total), I’d rather have a large self-contained file than external scripts.

I’ve seen a lot of similar questions here, but when I tried them they didn’t work correctly. I am good with HTML but not advanced in JS.

My current code is here, adapted from this but I don’t know how to pull the text samples into the div.

Partial View .Net MVC render javascript file

I have an error when loading a partial view in the following way, the problem is that when loading a second time the modal window tries to load the javascript file, therefore it gives an error in the variables that have already been declared more than once.

Partial View Controller

  [AllowAnonymous]
        public ActionResult _ClaimDetail()
        {
            return PartialView();
        }

Javascript call to load modal
$(buttonCharge).ModalPersonalize('show', urlController, 'rebuild title');

PartialView Modal cshtml

<div class="modalbody">

</div>
<div class="modalbuttons">

</div>
</div>
<script src="@Url.Content("~/JavacriptLogicModal.js")" type="text/javascript"></script>

The error occurs when the modal is opened for the second time, How could I solve it, some way to render once the javascript file?

I already tried adding validations but nothing works