ypeError: Cannot read properties of undefined error in GeoGebra Javascript

Threre are 3 integrated ggb applets injected at https://www.im-uff.mat.br/igsl/s2x2-br.html.

I am trying to register changes in the variables “s” and “t”!in the third applet , but Google Chrome complains:

TypeError: Cannot read properties of undefined (reading ‘registerObjectUpdateListener)

at s2x2-br.html:159:20

how to make changes in “s” and “t” active?

Thanks in advance.

When making a Music Bot with Distube, the sound does not come out when the music ends

I am writing a music bot, but when the song is finished with distube, the sound does not come out.

index.js

const { getVoiceConnection } = require('@discordjs/voice');

distube.on('finish', async queue => {

const connection = getVoiceConnection(queue.guild.id);


if (connection) {
  connection.destroy(); // Bu ses kanalından çıkacaktır
  console.log('Ses kanalı kapatıldı.');
} else {
  console.log('Ses bağlantısı bulunamadı.');
}
});

How do I solve this problem? It says there is no guild ID.

I want to reflect the results of a pay-as-you-go payment in Run Payments with Stripe in firestore

I am using basic html and javascript.I’m a beginner programmer.

I am currently working on a program that uses Stripe to process payments on a pay-as-you-go basis and reflect the results in Firestore. However, we are facing the following issue:

Problem Description:
I have set up a webhook in Firebase Functions, but I am getting the following error log:

❗️[Error]: Webhook handler for Stripe event [] of type [checkout.session.completed] failed: User not found!

my functions code


const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports['ext-firestore-stripe-payments-handleWebhookEvents'] = functions.https.onRequest(async (req, res) => {
const stripe = require('stripe')(functions.config().stripe.secret_key);

let event;

try {
event = stripe.webhooks.constructEvent(
req.rawBody,
req.headers['stripe-signature'],
functions.config().stripe.webhook_sub_secret
);
} catch (err) {
console.log(err);
return res.sendStatus(400);
}

if (event.type === 'checkout.session.completed') {
const session = event.data.object;
const userId = session.client_reference_id;
const incrementValue = 10;

      const userRef = admin.firestore().collection('users').doc(userId);
    
      return userRef.update({
          clickCount: admin.firestore.FieldValue.increment(incrementValue)
      }).then(() => {
          return res.status(200).send('Success');
      }).catch((error) => {
          console.error('Firestore Error', error);
          return res.status(500).send('Error');
      });

}

res.status(200).end();
});

I checked the webhook request in the Stripe dashboard, and it indeed does not contain a Firebase Auth user ID.
On the Stripe dashboard, I have confirmed the payment_intent.succeeded and checkout.session.completed events.

Question:
How can I get Firestore to update correctly after a payment is completed in Stripe?

My goal is for the user’s Firestore document to reflect the purchase information once the purchase is completed. I would appreciate any specific implementation advice or solutions you can provide.

Thank you for reading my poor English. Best regards.

Bundling javascript – I must be doing something wrong

So, I’ve been maintaining a front and back end web application for some time now. I learned Javascript when it was without any namespaces and you just pulled it into the browser and prayed that you didn’t cause any race conditions.

So now, Javascript has real modules, and a supported module type, and importmaps. Awesome. So, I re-architect my code to use those, and it’s a serious improvement in structure. I am a fan. What else am I missing?

Well, most JS developers now work in typescript with nodejs and vscode so they can get intellisense assistance while they write. The trick is then getting the result into a browser.

So I’m getting proficient in typescript, slowly. I restructure a small part of my app and finally get the compiler dumping out javascript. But part of it is in nodejs modules. So I look at bundlers. I try all of the popular ones, and every single one either doesn’t build a bundle for me due to various complaints, or generates code that my browser is not ok with. Confused.

Lets get specific. I’m using rollup, and here is my rollup.config.js

import esbuild from 'rollup-plugin-esbuild';
import commonjs from '@rollup/plugin-commonjs';

export default {
  input: 'js/main.js',
  output: {
    format: 'es',
    file: 'bundle/app.js'
  },
  plugins: [
    nodeResolve(),
    esbuild(),
    commonjs()
  ]
};

Meanwhile my package.json:

  "name": "mikejs",
  "version": "1.0.0",
  "description": "Mike's JS framework",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "rollup:build": "rollup js/main.js --file bundle/app.js --format es",
    "watch": "tsc -w",
    "build": "tsc && npm run rollup:build",
    "clean": "rm -rf js bundle"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@rollup/plugin-node-resolve": "^15.2.3",
    "browserify": "^17.0.0",
    "jquery": "^3.7.1",
    "nunjucks": "^3.2.4",
    "rollup-plugin-esbuild": "^6.1.1"
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "^26.0.1",
    "@types/jquery": "^3.5.30",
    "@types/node": "^22.2.0",
    "@types/nunjucks": "^3.2.6",
    "rollup": "^4.20.0",
    "typescript": "^5.5.4"
  },
  "keywords": []
}

And here’s a run of rollup:

npx rollup -c rollup.config.js 

js/main.js → bundle/build.js...
[!] RollupError: js/modules/mikejs.js (1:9): "configure" is not exported by "node_modules/nunjucks/index.js", imported by "js/modules/mikejs.js".
https://rollupjs.org/troubleshooting/#error-name-is-not-exported-by-module
js/modules/mikejs.js (1:9)
1: import { configure, compile } from 'nunjucks';

So, the typescript compiler thought it was ok but rollup does not.

So I run it through browserify for comparison:

browserify js/main.js js/modules/mikejs.js -r nunjucks -p esmify > bundle/app.js

Builds, but the browser doesn’t like it.

Uncaught ReferenceError: require is not defined
    at app.js:1:8

Why are we making code that the browser doesn’t like? Kinda defeats the purpose, no?

Apologies if I’m a tad lost and frustrated, I’ve been going at this a while reading blog posts that don’t work. Clearly some detail is being missed.

Help appreciated. Surely the state of bundlers can’t be this bad, it’s just me.

JavaScript to queue submit request on client side and Trigger Submit Button at a Specified Time

I am working on developing a script that triggers the submit button at the end of a form at a specified time on client side. The goal of this test is to simulate a scenario where multiple users submit the same form simultaneously but with different details. Imagine 20 people in a room, all connected to the same network and each with their own device. They’ve all completed the application, and when someone says ‘1, 2, 3, go,’ they all press the submit button at the exact same time.

I created the following script with the help of AI, but the problem is that it only refreshes the page instead of actually triggering the submit button.

let me tell you in advance that I am a beginner.

// Function to schedule a submit request
function scheduleSubmit() {
    // Set the specific time to submit
    const timeInput = "10:30 PM"; // Change this to your desired time

    // Validate the time input format
    const timePattern = /^(0?[1-9]|1[0-2]):[0-5][0-9] (AM|PM)$/;
    if (!timePattern.test(timeInput)) {
        console.error("Invalid time format. Please use HH:MM AM/PM format.");
        return;
    }

    const [time, period] = timeInput.split(' ');
    let [hours, minutes] = time.split(':').map(Number);

    // Convert hours to 24-hour format
    if (period === 'PM' && hours < 12) {
        hours += 12;
    } else if (period === 'AM' && hours === 12) {
        hours = 0;
    }

    const now = new Date();
    const submitTime = new Date();

    // Set the submit time to today at the specified hours and minutes
    submitTime.setHours(hours, minutes, 0, 0);

    // If the specified time is in the past, set it for tomorrow
    if (submitTime < now) {
        submitTime.setDate(submitTime.getDate() + 1);
    }

    // Schedule the submit button click
    const delay = submitTime - now;
    setTimeout(() => {
        const submitButton = document.querySelector('.btn.btn-danger.btn-block.mt-3');
        if (submitButton) {
            submitButton.click();
            console.log(`Submit triggered at ${submitTime.toLocaleTimeString()}`);
        } else {
            console.error("Submit button not found.");
        }
    }, delay);

    console.log(`Submit scheduled for ${submitTime.toLocaleTimeString()}`);
}

// Call the scheduleSubmit function to start the process
scheduleSubmit();

trying to learn the script in multiple request scenario.

Google Apps Script error: “GoogleJsonResponseException: API call to drive.files.insert failed with error: Bad Request”

I’m trying to trigger a Google Apps Script to copy an attached xlsx file from a Gmail email to a Google Sheet, but I’m getting the following error:

GoogleJsonResponseException: API call to drive.files.insert failed with error: Bad Request
fetch   @ fetch.gs:17

Line 17 in my code is:

var convertedSpreadsheetId = Drive.Files.insert({ mimeType: MimeType.GOOGLE_SHEETS }, xlsxBlob).id;

And this is the full code before line 17:

function fetch() {
  var searchQuery = "in:inbox from:[email protected] has:attachment filename:Stockfile filename:.xlsx";
  var threads = GmailApp.search(searchQuery);

  if (threads.length > 0) {
    var latestThread = threads[0];
    var latestEmail = latestThread.getMessages()[0];
    var attachments = latestEmail.getAttachments();

    if (attachments.length > 0) {
      for (var i = 0; i < attachments.length; i++) {
        var attachment = attachments[i];
        var attachmentName = attachment.getName();

        if (attachmentName.indexOf("stockfile") === 0) {
          var xlsxBlob = attachment;
          var convertedSpreadsheetId = Drive.Files.insert({ mimeType: MimeType.GOOGLE_SHEETS }, xlsxBlob).id;
          var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0];
          var data = sheet.getDataRange().getValues();

I’m not exactly sure what the issue is, but I should point out that this code was working for months in 2022. I’ve only just gotten back to it and for some reasons I can’t get it to work. I’m not sure what changed, in the code and/or in Google Apps Scripts.

The Drive services is set to v2, I’ve tried changing it to v3 but then Drive.Files.insert is not a function in v3.

My userId is not passing from the page to the slice, but the form is. I am not sure why it is not passing correctly

postSlice.js

   createPost: builder.mutation({
      query: ({ usersId, ...form }) => ({
        url: `/createPost/user/${usersId}`,
        method: "POST",
        body: { form, userId: usersId },
        // responseHandler: (response) => response.text(),
      }),
      invalidatesTags: ["User"],
    })

post.jsx

  const [createPost] = useCreatePostMutation();
  const state = useSelector((state) => state);
  const usersId = window.sessionStorage.getItem("User");

  const [form, setForm] = useState({
    title: "",
    content: "",
  });

  const [message, setMessage] = useState("");

  const update = (e) => {
    setForm((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  };

  const submit = async (e) => {
    e.preventDefault();
    setMessage("");
    try {
      if (!form.title || !form.content) {
        setMessage("Please fill in all required fields.");
        return;
      }

      let response = false;

      response = await createPost(form, usersId).unwrap();
      console.log(response);

      if (response) {
        setMessage("Post successful!");
        navigate("/");
      }
    } catch (error) {
      setMessage("Post failed. Please try again.");
    }
  };

Using dev tools, I can see that the form is being passed correctly, the usersId is coming back as undefined in the slice. It is appearing in the submit function, but it is not being passed. Not sure why??

How do I properly iterate, match, and splice spans with getelementsbyclassname?

I’m trying to put together a thing that will add tooltips to a page whenever a word has a definition. I have partially succeeded in doing so. The thing: https://codepen.io/veav/pen/vYqdEdB

The setup is intended to grab spans from the page with a class of “check” and check if their content can be found in a set of keywords. If it finds a keyword, it splices a new span in place with a class of “tooltip”, then opens the next “check” span to house the remaining content.

Right now, one of three things is happening at any given time: it only splices a tooltip onto the last match for a keyword, it only splices tooltips for the last keyword in the dictionary, or it splices tooltips into the meta text of a tooltip span, because a tooltip’s text can potentially contain a keyword. The class “check” is intended to prevent this.

I know that this is 200% user error but I don’t know the right questions to ask in order to fix my mistakes. Am I completely off-base with my approach?

const keywords = {
  "background":
  "pg 20. Your pilot`s background describes their life before they became a mech pilot."
  ,"invoke":
  "pg 20. Outside of combat, you (or the GM) can invoke your pilot`s background to receive 1 ACCURACY or 1 DIFFICULTY on any skill check, if their background is relevant."
  ,"ACCURACY":
  "pg 13. ACCURACY adds 1d6 to a roll. Multiple ACCURACY dice are a keep-highest roll. ACCURACY and DIFFICULTY cancel each other out on a 1:1 basis."
  ,"DIFFICULTY":
  "pg 13. DIFFICULTY adds 1d6 to a roll. Multiple DIFFICULTY dice are a keep-highest roll. ACCURACY and DIFFICULTY cancel each other out on a 1:1 basis."

};

function tooltipper() {
      var spans = document.getElementsByClassName('check');   
      for (var y in keywords) { 
      for (var x of spans) {
          console.log('checking '+y+' against span '+x.innerHTML+'...');
          var spantipper = inserttip(x, y);
          if (typeof spantipper !== 'undefined') {
            console.log('final before: '+x.innerHTML);
            x.innerHTML = spantipper; 
            console.log('final after: '+x.innerHTML);
          }
          else { console.log(y+' not found in span'+x.innerHTML.substr(0,50)+'...'); }
    }
    }
}

function inserttip(brick, keyword) {
    var bricktext = brick.innerHTML;
    var brickpost = '';
    var brickpre = brick.innerHTML;
    var match = brickpre.indexOf(keyword);
    var ogmatch = bricktext.indexOf(keyword);
    while ( match != -1) {
        console.log(keyword+' found')
        var brickopen = match;
        var brickclose = match+keyword.length;
        var remaining = brickpre.length-brickclose;
        brickpost += brickpre.substr(0, match);
        brickpost +='</span><span class="tooltip" data-tooltip="' +keywords[keyword] + '" data-tooltip-position="bottom">' + keyword + '</span><span class="check">';
        console.log('set: '+brickpost)
        brickpre = brickpre.substr(brickclose, remaining);
        console.log('marched: '+brickpre.substr(0,50)+'...');
        match = brickpre.indexOf(keyword);
        if ( match == -1) { console.log('end of matches for '+keyword); }
      }
    if (ogmatch != -1) {
    brickpost += brickpre;
    return brickpost;
    }
}

How to run webworker in a chrome extension’s content script on sites that have strict Content Security Policy

I’m trying to create a chrome extension that uses Tesseract.js (https://github.com/naptha/tesseract.js) to perform OCR on the captured images from a webpage.

I’ve created content script and a service worker for my extension.

In the content script I’m sending the request to service worker to capture screenshot of the webpage, then I’m sending the screenshot back to the content script, and I initialize tesseract’s service worker there and perform OCR on the screenshot.

The above approach works on most of the pages, however on pages that have stricter CSP like github, where the plicy looks like this: “worker-src github.com/assets-cdn/worker/ github.com/webpack/ github.com/assets/ gist.github.com/assets-cdn/worker/” this approach does not work.

How else can I use webworker on such pages?

I can’t spawn webworker from the main chrome extension’s service worker.

I’ve tried created a small html page with tesseract.min.js and worker.min.js files, and open it in a new tab, and ocr works fine there

  const customTab = chrome.runtime.getURL('./ocr_page.html');
  const tab = await chrome.tabs.create({
       url: customTab
    });

However I don’t want to open a new tab everytime I want to do ocr on a page.

I’m having trouble injecting my service class into my component constructor – Angular 18

I’m using Angular 18 and I’m trying to work through a tutorial which is geared for a much older version.

Here is my Service class:

export class ProductsService
{ 
    getProducts() : string[] 
    { 
        return ["Learning Angular","Pro TypeScript","ASP.NET"]; 
    } 
}

I’m trying to use this from my Component class by injecting it into the constructor. As such:

import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ProductsService } from './products.service';

@Component({
  selector: 'app-products',
  standalone: true,
  templateUrl: './products.component.html',
  styleUrl: './products.component.css',
  imports: [CommonModule]
})
export class ProductsComponent implements OnInit {

  products: string[] = [];

  constructor(ps: ProductsService)
  { 
    this.products = ps.getProducts(); 
  }

  ngOnInit(): void
  {
  }
}

The error I’m getting is: NullInjectorError: NullInjectorError: No provider for ProductsService!

Now the documentation states that I need to add some code into app.module.ts:

enter image description here

But in this version of Angular, there is no such file as app.module.ts. So where am I supposed to define this dependency?

Angular: Scroll to a section on page load when navigating to a specific URL fragment

I’m working on an Angular application and I have a function that scrolls smoothly to a specific section on the page. The function works perfectly when I trigger it manually. However, I want the page to automatically scroll to a specific section when the user navigates directly to a URL with a fragment, such as http://localhost:4200/section-2.

How can I modify my code or implement additional logic to make sure that when the page is loaded with a specific fragment in the URL, it automatically scrolls to that section?

Here’s my current scroll function:

public scrollToSection(sectionId: string): void {
  const targetElement = document.getElementById(sectionId);
  if (targetElement) {
    const navHeight = this.navigationService.getNavHeight();
    const yPosition = targetElement.getBoundingClientRect().top + window.scrollY - navHeight;
    window.scrollTo({ top: yPosition, behavior: 'smooth' });
  }
}

Making a Solitaire game

Im working on a solitaire game project and now im working on gaps between cards.
I work on .ts files and using pixi.
I want to make bigger gaps (ROW_GAP) for cards that are visible, and ROW_SMALL_GAP for invisible cards (those, that were turned down) in tableau columns.
I v got this method:


updateColumnGaps(): void {
        console.log('Updating column gaps...');
    
        // Going through each column
        this.tableau.forEach((column, colIndex) => {
            let currentY = 0;
            let gap = 0;
    
            console.log(`Column ${colIndex}: X position = ${column[0]?.container?.x}`);
    
            // Count gap based on number of cards
            if (column.length > 20) {
                gap = ROW_GAP;
            }
            
            // Iterate through each card in the column
            column.forEach((card, cardIndex) => {
                // If there is < 20 cards, we set a specific gap.
                if (column.length <= 20) {
                    gap = card.visible ? ROW_GAP : ROW_SMALL_GAP;
                }
    
                // Set card position
                card.setPosition(new Point(column[0].container.x, currentY));
                currentY += gap;
    
                console.log(`Card ${card._id} Position (Y) = ${card.container.y}, Gap = ${gap}`);
            });
    
            console.log(`Column ${colIndex}: Final Y position = ${currentY}`);
        });
    }

I added this method to my onUndo() method, which adds gaps that i want when i click on undo button.
I was adding this also to dragCard() and dropCard() methods, but it was updating screen only after next move (for example at begining of game I have moved Queen to a Column with 2 aversed card and King – there should be AVERSED>ROW_SMALL_GAP>AVERSED>ROW_SMALL_GAP>KING>ROW_GAP>QUEEN but it all have ROW_SMALL_GAP until I try to make another move (then it starts to update screen)

Also when i try to move group of cards but decide to leave them where they were gaps between this column are set back to ROW_SMALL_GAP.

HERE IS MY ONUNDO() METHOD- I THINK I SHOULDNT USE * ROW_SMALL_GAP in it, but then what should i use?

onUndo() {
        const lastMove = this.moves.pop();
        if (!lastMove) return;
        if (this.moves.length === 0) this.undoButton.setDisabled(true);
        this.moveGroup = lastMove.list.map((id) => this.cards.find((c) => c._id === id)) as Card[];
        if (this.moveGroup.length === 0) return;
        const place = lastMove.from;
        const firstCard = this.moveGroup[0];
        this.moveGroupContainer.position = firstCard.place.position;
        GameEvent.emit(EventName.UNDO_MOVE, lastMove);
        if (place.cardPlace === CardPlace.STOCKPILE && place.value === -1) {
            //reverse flip cards
            this.stockpile = [];
            this.moveGroup.forEach((card, index) => {
                if (card) {
                    card.setPlace({
                        cardPlace: CardPlace.WASTE_PILE,
                        value: index,
                        zIndex: TOP_DEAL_Z_INDEX + index,
                        position: new Point(wastePilePosition.x, wastePilePosition.y),
                    });
                    card.setOrder(MOVE_Z_INDEX);
                    card.moveTo(card.place.position, 0, () => {
                        card.setVisible(true);
                        card.setOrder(card.place.zIndex);
                        this.blockMove = false;
                    });
                    this.wastePile.push(card);
                }
            });
            setTimeout(this.shrinkWastePile, 1);
            setTimeout(this.refreshWastePile, 3);
            return;
        }
        this.moveGroup.forEach((card, index) => {
            this.clearPlace(card);
            let targetPosition = new Point();
            switch (place.cardPlace) {
                case CardPlace.TABLEAU:
                    targetPosition = new Point(
                        this.getColumnPosition(place.value),
                        (this.tableau[place.value].length + index) * ROW_SMALL_GAP
                    );
                    break;
                case CardPlace.FOUNDATION:
                    targetPosition = new Point(this.getFoundationPosition(place.value), foundationPosition.y);
                    break;
                case CardPlace.WASTE_PILE:
                    targetPosition = stockPilePosition.clone();
                    break;
                case CardPlace.STOCKPILE:
                    targetPosition = stockPilePosition.clone();
                    targetPosition.x += (this.stockpile.length + index) * STOCK_PILE_GAP_X;
                    targetPosition.y += (this.stockpile.length + index) * STOCK_PILE_GAP_Y;
                    break;
            }

            card.setPlace({
                cardPlace: place.cardPlace,
                value: place.value,
                zIndex: place.zIndex + index,
                position: targetPosition,
            });
        });
        this.placeMoveGroup();
        if (lastMove.cardToActivate) {
            lastMove.cardToActivate.setActive(false);
        }
        if (lastMove.cardToHide) {
            lastMove.cardToHide.setVisible(false);
        }
        if (lastMove.cardToActivate?.place.cardPlace === CardPlace.WASTE_PILE) this.refreshWastePile();
        if (place.cardPlace === CardPlace.STOCKPILE) setTimeout(this.refreshWastePile, 300);
        
    }```

What are the standards for when my module has it’s own webpack and I need to import and use in a main app with its own webpack?

As the title states, I have a module I developed with it’s own webpack. It is intended for use in one of my company’s main apps as well as for other developers to use in their own applications. I noticed that when I generate my modules build in development mode and import to my main app everything works as intended. When I switch my module’s webpack mode to production my main app’s webpack detects code that is not transpiled in the build file and throws the -> ‘you may need an appropriate loader’ error.

My Suspicion
I am thinking that production mode there is prebundling and minification or some other difference which is resulting in es6 being present in the build file.

What additional steps might one have to take when switching to production for an imported module that is consumed by a main app with it’s own webpack?

Should I just import raw source code and rely on the main app’s webpack to transpile?

I could release the build file generated by development mode because the module is relatively simple and small, ~3M…

Why are these variables undefined ? Is this about the proxy issue?

Here is my store.js:-

import { configureStore } from "@reduxjs/toolkit";
import authSlice from "./authSlice";

export const store = configureStore(
    {
        reducer: {auth: authSlice.reducer}
    }
)

Here is my index.js:-

import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';
import './index.css';

const container = document.getElementById('root');
const root = createRoot(container);

root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

Here is my authSlice.js:-

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import authService from './authService';


const localuser = JSON.parse(localStorage.getItem('user'));

//initial state for the authentication slice
const initialState = {
    user: localuser ? localuser : null,
    isError: false,
    isSuccess: false,
    isLoading: false,
    message: ''
}

export const register = createAsyncThunk( // thunk for dispatching actions(TYPE) and managing API calls (like for registering user)
    'auth/register', //unique identifier for this thunk
    async (user, thunkAPI) => { //payload creator that returns a result by performing a action of API call
        try {
            return await authService.register(user)
        } catch (error) {
            const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString() 
            return thunkAPI.rejectWithValue(message)   
        }
    }
)


// Creating the authentication slice
export const authSlice =  createSlice({
    name: 'auth', //name of the slice
    initialState, //initial state of this slice
    reducers: {
        //reducer function to reset the state
        reset: (state) => {
            state.isLoading = false
            state.isSuccess = false
            state.isError = false
            state.message = ''
        },
    },
    // takes a object i.e. builder with cases such as pending, etc and states are updated.
    extraReducers: builder => {
        builder.addCase(register.pending, (state)=>{
            state.isLoading = true;
        })
        builder.addCase(register.fulfilled, (state, action) => {
            state.isLoading = false;
            state.isSuccess = true;
            state.user = action.payload;
        })
        builder.addCase(register.rejected, (state, action)=>{
            state.isLoading = false;
            state.isError = true;
            state.message = action.payload;
            state.user = null;
        })
    }
})

//exporting the actions and reducers
export const { reset } = authSlice.actions;
export default authSlice;

Here is my authService.js:-

import axios from 'axios';
const API_URI = '/api/users';

const register = async(userData) => {
    const response = await axios.post(API_URI, userData);
    if (response.data) {
        localStorage.setItem('user', JSON.stringify(response.data));
    }
    return response.data;
}

const authService = { register }
export default authService;

Here is my Register.js where I have used the useSelector:-

import React, { useEffect, useState } from "react";
import {useDispatch} from "react-redux";
import { useSelector } from "react-redux";
import {useNavigate} from "react-router-dom";
import {register, reset} from "../features/auth/authSlice";

export default function Register(){
    const [formData, setFormData] = useState({ name: '', email: '', password: '', password2: ''});
    const {name, email, password, password2} = formData;
    const navigate = useNavigate();
    const dispatch = useDispatch();

    const {user, isLoading, isError, isSuccess, message} = useSelector(state => state.auth);
    
    return(
       <div>
            <section className="heading">
              <h1><FaUser/> Register</h1>
              <p>Please create a account</p>
            </section>
            <section className="form">
                <form onSubmit={onSubmit}>
                    <div className="form-group">
                        <input type="text" className="form-control" id="name" name="name" value={name} placeholder="Enter your name" onChange={onChange}/>
                    </div>
                    <div className="form-group">
                        <input type="email" className="form-control" id="email" name="email" value={email} placeholder="Enter your email" onChange={onChange}/>
                    </div>
                    <div className="form-group">
                        <input type="password" className="form-control" id="password" name="password" value={password} placeholder="Enter your password" onChange={onChange}/>
                    </div>
                    <div className="form-group">
                        <input type="password" className="form-control" id="password2" name="password2" value={password2} placeholder="Confirm password" onChange={onChange}/>
                    </div>
                    <div className="form-group">
                        <button type="submit" className="btn btn-block">Submit</button>
                    </div>
                </form>
            </section>
        </div>
    )

This is error I am getting in Register.js:-

Uncaught runtime errors:
×
ERROR
Cannot destructure property ‘user’ of ‘(0 , react_redux__WEBPACK_IMPORTED_MODULE_1__.useSelector)(…)’ as it is undefined.
TypeError: Cannot destructure property ‘user’ of ‘(0 , react_redux__WEBPACK_IMPORTED_MODULE_1__.useSelector)(…)’ as it is undefined.

What I tried is by including OR condition in this line which is inside Register.js:-

const {user, isLoading, isError, isSuccess, message} = useSelector(state => state.auth || {});

And then when I click on Submit button to register, then I get one more error that is this:-

proxy error: Could not proxy request /api/users from localhost:3000 to http://localhost:8000/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED)

I have also included proxy in the package.json file but still I am getting the above error:
My Package.json of the frontend folder:

{
  "name": "frontend",
  "version": "0.1.0",
  "proxy": "http://localhost:8000",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.7",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^14.5.2",
    "axios": "^1.7.2",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-icons": "^5.2.1",
    "react-redux": "^8.1.3",
    "react-router-dom": "^6.24.0",
    "react-scripts": "5.0.1",
    "react-toastify": "^10.0.5",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Can someone help me out with this ? What am I missing ? Or am I doing something wrong ?