in react redux state is not updating while loading user

// Problem Description:
//I am encountering an issue where the login value in my Redux store is updating for login logout register part but loadingUser its not getting updated.Even though the in LoadUser fnction is dispatching
LoadUserSuccess but login value is not updating.
// I’ve provided my code below and would like to understand why this issue is happening.

// App.js

import ‘./App.css’;

import Login from ‘./component/LoginRegis/login’;

import Navbar from ‘./component/Navbar/navbar’;

import Footer from ‘./component/Footer/footer’;

import Book from ‘./component/Book/book’;

import { useEffect} from ‘react’;

import { useDispatch,useSelector } from “react-redux”;

import { LoadUser} from “./Action/user”

function App() {

const dispatch = useDispatch();

const isLogged = useSelector((state) => state.user.login);

console.log(isLogged);

useEffect(()=>{

dispatch(LoadUser())

},[dispatch])

return (

<div className="app">

{isLogged && < Navbar/>}

{isLogged && < Book />}

{!isLogged && < Login/>}

{isLogged &&< Footer/>}

 </div>

);

}

export default App;

//Redux action file

import axios from “axios”;

export const LoginUser = (email, password) => async (dispatch) => {

try {

dispatch({

  type: "LoginRequest"

})

const data = await axios.post("api/v1/login/", {email, password}, {

  headers: {

    "content-type": "application/json",

  }

});

dispatch({

  type: "LoginSuccess",

  payload: data.user

})

} catch (error) {

dispatch({

  type: "LoginFailure",

  payload: error

})

}

};

export const RegisterUser = (userDetails) => async (dispatch) => {

try {

dispatch({

  type: "RegisterRequest"

})

const data = await axios.post("api/v1/register/", {userDetails}, {

  headers: {

    "content-type": "application/json",

  }

});

dispatch({

  type: "RegisterSuccess",

  payload: data.user

})

} catch (error) {

dispatch({

  type: "RegisterFailure",

  payload: error

})

}

};

export const LoadUser = () => async (dispatch) => {

try {

dispatch({

  type: "LoadUserRequest",

});



const { data } = await axios.get("api/v1/me/");

dispatch({

  type: "LoadUserSuccess",

  payload: data.user,

});

} catch (error) {

dispatch({

  type: "LoadUserFailure",

  payload: error.response.data.message,

});

}

};

export const LogoutUser = () => async (dispatch) => {

try {

dispatch({

  type: "LogoutUserRequest",

});



await axios.get("api/v1/logout/");

dispatch({

  type: "LogoutUserSuccess"

});

} catch (error) {

dispatch({

  type: "LogoutUserFailure",

  payload: error.response.data.message,

});

}

};

//Reducer userjs

import { createReducer } from “@reduxjs/toolkit”;

const initialState={login :false}

export const userReducer = createReducer(initialState,{

RegisterRequest:(state)=>{

    state.loading = true

},

RegisterSuccess:(state, action)=>{

    state.loading = false

    state.user = action.payload

},

RegisterFailure:(state, action)=>{

    state.loading = false

    state.error = action.payload

},



LoginRequest:(state)=>{

    state.loading = true

    state.login = false

},

LoginSuccess:(state, action)=>{

    state.loading = false

    state.login = true

    state.user = action.payload

},

LoginFailure:(state, action)=>{

    state.loading = false;

    state.login = false;

    state.error = action.payload

},



LoadRequest:(state)=>{

    state.loading = true

},

LoadSuccess:(state, action)=>{

    state.loading = false;

    state.login= true;

    state.user = action.payload

},

LoadFailure:(state, action)=>{

    state.loading = false

    state.login= false;

    state.error = action.payload 

}, 




LogoutUserRequest: (state) => {

    state.loading = true;

  },

LogoutUserSuccess: (state) => {

    state.loading = false;

    state.login = false;

    state.user = null;

  },

LogoutUserFailure: (state, action) => {

    state.loading = false;

    state.login = true;

    state.error = action.payload;

  },



clearErrors: (state) => {

    state.error = null;

  }

})

//store.js

import {configureStore}from “@reduxjs/toolkit”

import { userReducer } from “./Reducer/User”

const store =configureStore({

reducer:{ user : userReducer}

})

export default store;

i try to update in this manner
state = {
…state,
loading = false,
login = true,
user = action.payload
}

but stiil it didn’t work

AG-Grid displays blank page after reaching the last page

I’m using AG-Grid with Stimulus controllers in my Rails 7 app. All works well until the user reaches the last page, then returns to the first page using the << arrows, at which point it renders a blank page instead of displaying data. No errors are found in server logs or browser console. Is that a common issue? Below is my code:

order_items_controller.js

import { Controller } from 'stimulus';
import Rails from '@rails/ujs';
import * as AgGrid from 'ag-grid-community';
import {
  DEFAULT_GRID_OPTIONS,
  buildColumnDefs,
  GridDatasource,
  updateColumnPositionsInCookies,
} from 'core/utils/grid';

const columnOptions = {
  columnDefs: {
    order_reference: { cellClass: 'font-mono', cellRenderer: 'flexCellRenderer', sortable: false },
    order_date: { cellClass: 'font-mono', maxWidth: 300, sortable: false },
    description: { cellClass: 'font-mono', maxWidth: 300, sortable: false },
    quantity: { cellClass: 'font-mono', maxWidth: 100, sortable: false },
    amount: {
      cellClass: 'ag-right-aligned-cell font-mono', maxWidth: 200, sortable: false,
      headerClass: 'ag-header-cell ag-header-cell-sortable text-xs font-medium text-gray-500 uppercase bg-gray-100'
                   + ' ag-focus-managed ag-right-aligned-header' },
    currency_code: { cellClass: 'font-mono', maxWidth: 150, sortable: false },
    invoice_id: { cellClass: 'font-mono', sortable: false },
    vat: { cellClass: 'font-mono', maxWidth: 100, sortable: false },
    actions: { cellClass: 'ag-right-aligned-cell font-mono', maxWidth: 120, sortable: false, withoutHeader: true }
  },
  cookiesName: 'order_items_columns_positions',
  defaultSorting: [
    'order_reference',
    'order_date',
    'amount',
    'quantity',
    'currency_code',
    'invoice_id',
    'vat',
    'description',
    'actions'
  ],
};

function buildGrid(gridElement) {
  const {indexUrl, paginationPageSize, i18nJson} = gridElement.dataset
  const options = {
    ...DEFAULT_GRID_OPTIONS,
    cacheBlockSize: paginationPageSize,
    maxConcurrentDatasourceRequests: 2,
    columnDefs: buildColumnDefs(columnOptions, i18nJson),
    datasource: new GridDatasource({ indexUrl }),
    onColumnMoved(params) { updateColumnPositionsInCookies(columnOptions, params) }
  }
  return new AgGrid.Grid(gridElement, options);
}

export default class extends Controller {
  connect() {
    const gridElement = this.element.querySelector('#orderItemsGrid');

    if (gridElement) {
      this.gridObject = buildGrid(gridElement)
    }
  }


  disconnect() {
    if (this.gridObject) {
      this.gridObject.destroy();
    }
  }
}

order_items_controller.rb

  class OrderItemsController < ApplicationController
    def index # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
      respond_to do |format|
        format.json do
          render json: order_items
            .serialize(::DtfsOrders::OrderItemSerializer, scope: view_context, payment_ids:, pundit_user:)
            .as_json
        end
        format.html do
          @order_item_list = fetch_order_items(@order_items_params.merge(limit: 1).to_h)
        end
      end
    rescue ::DtfsOrders::Error => e
      redirect_to main_app.root_path, alert: api_error_message(e)
    end

How to edit shadow root popover-content in css

wanna ask how to edit the default css in shadow root? I wanna remove default border applied to popover content
The red rectangle is the properties that i wanna change. Notice that is (.popover-desktop) inside

Appreciated for your answer. Thanks!

I have tried few ways also not work. Below are the way I had tried.

:host(.popover-desktop) .popover-content {
  border: none;
}

::ng-deep .popover-wrapper {
  .popover-content {
    border: none;
  }
}

:popover-open {
  .popover-wrapper {
    .popover-content {
      border: none;
    }
  }
}

Custom Cursor scrolls away unless mouse is moved HTML CSS JS

I am working on a custom cursor design for my website. I found a design I liked and tweaked it to my liking. The only problem is, when I scroll, the design scroll away too. It returns when I move the mouse.

const cursor = document.querySelector('.cursor')
document.addEventListener('mousemove', (e) => {
  cursor.setAttribute("style", "top: " + (e.pageY - 60) + "px; left: " + (e.pageX - 60) + "px;")
})

document.addEventListener("click", (e) => {
  console.log(e.target)
  cursor.classList.add('click')

  setTimeout(() => {
    cursor.classList.remove('click')
  }, 500)
})
@import url("https://fonts.googleapis.com/css?family=Montserrat:400,400i,700");
body {
  font-family: Montserrat, sans-serif;
  font-size: 30px;
  background: #000;
  color: #fff;
  cursor: none;
  position: relative;
  min-height: 100vh;
  padding: 0px;
  margin: 0px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

div {
  display: inline-block;
  padding: 20px;
}

.cursor {
  pointer-events: none;
  position: absolute;
  width: 80px;
  height: 80px;
  background: #fff;
  border-radius: 50%;
  mix-blend-mode: exclusion;
  background: radial-gradient(circle, #000 0%, #000 3.99%, #fff 4%, #fff 100%);
}

.cursor.click {
  animation: click .3s ease-in-out;
}

@keyframes click {
  0% {
    transform: scale(1);
  }
  5% {
    transform: scale(1.3);
  }
  100% {
    transform: scale(1);
  }
}
<div class="cursor">
</div>
<h1>Hello world</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mi nisi, congue at mattis in, fermentum at purus. In venenatis diam eget facilisis pharetra. Nam eget metus gravida nibh consectetur auctor. Nunc dignissim eros nunc, at tempus dui tincidunt quis. 

Mauris augue dui, pretium vel nunc ac, lacinia condimentum est. Maecenas mattis ligula non mi rutrum sodales. Aenean porta augue eget ex convallis, eget pulvinar felis accumsan. Suspendisse lorem nunc, dignissim at sapien eget, condimentum varius enim. 

Duis bibendum sed justo non laoreet. Ut egestas nisi vel interdum viverra. Ut consectetur ex sed sem pretium, convallis egestas tellus elementum. Maecenas libero felis, efficitur nec dolor et, ultrices dignissim magna.</p>
<br>

I have tried changing pageX and pageY to clientX and clientY but all it did was make the cursor irrecoverable if scrolled too far.

How to post value into database based on function calculation using javascript [closed]

    <script>
    function calculateTotal() 
    {
var doContainers = document.querySelectorAll('[data-doquantity]');
    var grandTotal = 0; // Initialize grand total
    var affectedStock = 0; // Initialize affected stock
    var totalCompensation = 0; // Initialize total compensation
    

    for (var i = 0; i < doContainers.length; i++) {
        var container = doContainers[i];
        var doQuantity = parseFloat(container.getAttribute('data-doquantity'));
        var exceedValue = parseFloat(container.querySelector('input[name="exceed_value[]"]').value);
        var rate = parseFloat(container.querySelector('input[name="rate[]"]').value);
        var totalInput = container.querySelector('input[name="total[]"]');

        if (!isNaN(exceedValue) && !isNaN(rate) && !isNaN(doQuantity)) {
            var calculatedTotal = doQuantity * (exceedValue * rate);
            grandTotal += calculatedTotal; // Accumulate the total

            // Update the total input
            totalInput.value = calculatedTotal.toFixed(2);

        } else {
            totalInput.value = '0.00';
        }
        
    }
    
    // Update the grand total display and hidden field
     var grandTotalDisplay = document.getElementById('grandTotal');
    grandTotalDisplay.textContent = grandTotal.toFixed(2); // You can adjust the decimal places as needed
    grandTotalDisplay.value = grandTotal.toFixed(2); // Store the value in a hidden field


// Calculate and update the total compensation for all checkboxes
    var affectedStock = parseFloat(document.getElementById('affected_stock').value);
    var compensation = (grandTotal) / (affectedStock / 1000);

    // Update the compensation display and hidden field
    var compensationDisplay = document.getElementById('compensation');
    compensationDisplay.textContent = compensation.toFixed(2); // You can adjust the decimal places as needed
    compensationDisplay.value = compensation.toFixed(2); // Store the value in a hidden field
    
}
</script>

<table>
    <tr>
        <td colspan="3">
        <div align="right">
        <b>Grand Total (RM) : </b>
        <!-- Display the grand total here -->
        <span id="grandTotal">
        </span>
        <br>
        <b><i>Compensation per RM / MT : </i></b>
        <!-- Display the compensation here -->
        <span id="compensation"></span>
        </div>
        </td>
</tr>   
</table>

How can I store this Calculated value in DB?
from the function i calculated grand total and compensation based on exceedvalue, rate, affected stock and details.
now the problem is im not able to insert the value for grand total and compensation into database.

Shopify Processing Error On File Upload Through JS/GraphQL

I am implementing a simple solution that allows the user to select a file (any type of image). Once selected, the user clicks on “Upload Image,” and the API call is triggered. I am receiving a status 200 in response, but when I check the Shopify Files directory in the admin panel, it shows me a “Processing error.” As you can see in the screenshot, the resourceUrl is generated correctly. I am also facing an issue in fetching the image; this is because the image has not been uploaded to Shopify, which is why the **data.data.node.image** is null. Please review the JavaScript code below and let me know the possible reasons that could be causing this Processing error.

I have tried to upload different image types png,jpg with small size but still same issue.

Processing Error :

enter image description here

API Response :

enter image description here

CODE :

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>

const adminApiUrl = 'GRAPHQL_URL';

document.getElementById('upload-button').addEventListener('click', async () => {
    const fileInput = document.getElementById('file-input');
    const selectedFile = fileInput.files[0];
    
    if (selectedFile) {
        // const fileSize = selectedFile.size.toString();
        const file = selectedFile.name;
        try {
            console.error('selectedFile', selectedFile);

            const stagedUploadsQuery = `mutation stagedUploadsCreate($input: [StagedUploadInput!]!) {
              stagedUploadsCreate(input: $input) {
                stagedTargets {
                  resourceUrl
                  url
                  parameters {
                    name
                    value
                  }
                }
                userErrors {
                  field
                  message
                }
              }
            }`;

            // Variables
            const stagedUploadsVariables = {
                input: {
                    resource: 'FILE',
                    filename: selectedFile.name,
                    mimeType: selectedFile.type,
                    fileSize: selectedFile.size.toString(),
                    httpMethod: 'POST',
                },
            };

            const stagedUploadsQueryResult = await axios.post(
                adminApiUrl, {
                    query: stagedUploadsQuery,
                    variables: stagedUploadsVariables,
                }, {
                    headers: {
                        "X-Shopify-Access-Token": 'ACCESS_TOKEN',
                    },
                }
            );
            const target = stagedUploadsQueryResult.data.data.stagedUploadsCreate.stagedTargets[0];
            const url = target.url;
            const resourceUrl = target.resourceUrl;
            const params = target.parameters;
            await performFileCreateTest(target.resourceUrl);
            console.log("resourceUrl", resourceUrl);
          
            const formData = new FormData();
            params.forEach(({ name, value }) => {
              formData.append(name, value);
            });
            formData.append("file", selectedFile);
            await axios.post(url, formData);
          
            alert('Image uploaded successfully!');
        } catch (error) {
            console.error('Error uploading image:', error);
            alert('Error uploading image. Please try again.');
        }
    } else {
        alert('Please select an image to upload.');
    }
});

async function performFileCreateTest(resourceUrl) {

    // Query
    const createFileQuery = `mutation fileCreate($files: [FileCreateInput!]!) {
      fileCreate(files: $files) {
          files {
              fileStatus
              ... on MediaImage {
                  id
              }
          }
          userErrors {
              field
              message
          }
      }
    }`;

    // Variables
    const createFileVariables = {
        files: {
            alt: "alt-tag",
            contentType: "IMAGE",
            originalSource: resourceUrl, 
        },
    };

    // Finally post the file to shopify. It should appear in Settings > Files.
    const createFileQueryResult = await axios.post(
        adminApiUrl, {
            query: createFileQuery,
            variables: createFileVariables,
        }, {
            headers: {
                "X-Shopify-Access-Token": `ACCESS_TOKEN`,
            },
        }
    );
    console.log("createFileQueryResult",createFileQueryResult.data.data.fileCreate.files[0].id);    
    const imageId = createFileQueryResult.data.data.fileCreate.files[0].id;
    await fetchImage(imageId);
}

const fetchImage = async (imageId) => {
  const query = `
    query getFileByID($imageId: ID!) {
      node(id: $imageId) {
        ... on MediaImage {
          id
          image {
            url
          }
        }
      }
    }
  `;

  const variables = { imageId };

  try {
    const response = await axios({
      url: adminApiUrl,
      method: 'post',
      headers: {
        'X-Shopify-Access-Token': 'ACCESS_TOKEN', 
      },
      data: {
        query: query,
        variables: variables,
      },
    });

    const image = response;
    console.log('Image originalSrc:', image);
    //console.log('Image transformedSrc:', image.transformedSrc);
    // You can now use the image URL as needed in your application
  } catch (error) {
    console.error('Error fetching image:', error);
    // Handle errors appropriately in your application
  }
};  
</script>
<h1>Upload Image</h1>
<input type="file" id="file-input">
<button id="upload-button">Upload Image</button>

How to close a bootstrap modal using angular

I have a bootstrap 5 modal that I am trying to close from typescript. When I call the function to close it. I get an error that saying undfined when the dismiss function
is called.

import {NgbModal, ModalDismissReasons,NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { ModalSizes } from 'src/app/core/utilities/modal-sizes';
import { timer } from 'rxjs';
declare var window: any;

export class UploadComponent {
 
 @ViewChild("spinnerLoaderModal") content;
  loading = false;
  spinnerDuration = 2000;
  closeResult: string;
  //modalReference: NgbModalRef;
  modalReference: NgbModalRef;
 
 constructor(
   private cdRef: ChangeDetectorRef,
   private modalService: NgbModal,){}


   //this.modalService.open(this.content, ModalSizes.lg);
   
 open(content){
    this.modalReference = this.modalService.open(content);
    this.modalReference.result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed `;
    });
    //this.modalReference.close();
    }

 public closeSpinnerModal()
 {

  this.modalReference.dismiss(); 
 }
 
 public onSubmit(event : MouseEvent) {
 this.isLoading = true;
   this.open(this.content)
   timer(this.spinnerDuration).subscribe(this.closeSpinnerModal)
 }

}

HTML

<ng-template #spinnerLoaderModal let-c="close" let-d="dismiss">
<div class="modal-body">
      <div class="row">
        <input type="hidden" id="spinLoader" class="form-control">
       </div>
            <img src="../../../../assets/images/loaderBlue.gif" id="bg" alt="" style="width:30%; margin-left: 0; margin-right: 0;">
  </div>
</ng-template>

find repeated characters in two arrays?

I have a two arrays which contains repeated characters. I tried to achieve it by using for loop in JavaScript.
I am getting output with repeated and also non repeated. which is not expected. I want only repeated characters in two arrays.

Thanks in advance.

I have a two arrays which contains repeated characters. I tried to achieve it by using for loop in JavaScript. I am getting output with repeated and also non repeated. which is not expected. I want only repeated characters in two arrays.

// javascript

// output : 123

let arr1 = [1, 1, 2, 2, 3, 3, 4 ]; 
let arr2 = [1, 1, 2, 2, 7, 3, 3, 5, 6, 1]; 
function repeatedElements(inputArray1, inputArray2){
  let repeatedEle = [];
  for(let ele of inputArray1){
     if(inputArray1.indexOf(ele) !== inputArray2.lastIndexOf(ele)){
       repeatedEle.push(ele)
     }
  }
  return [...new Set(repeatedEle)]
}
console.log(repeatedElements(arr1, arr2));

How to check if a certain option is checked in my google form with apps script?

What I am attempting to do as a whole, is once someone has submitted a form, they will be sent an email (google doc) depending on which option they chose from “checkboxes” on my google form.

The response of that option is logged as follows: [a, c, d]

I got this far. I am not sure how I can take this response as a whole and check for 1 option independantly.

Here is my code so far:

var EMAIL_TEMPLATE_DOC_URL = 'x';

function sendEmail(e) {
  var responses = e.namedValues;

  var recipient_name = responses['What is your full name?']
  var recipient_email = responses['Email address'][0].trim()
  var recipient_classes = responses['Which classes are you interested in attending?']

  Logger.log(recipient_classes)

  // What do you want the subject of the email to be?
  var email_subject = `${recipient_name} here are your class details!` 
  
  MailApp.sendEmail({
    to: recipient_email,
    subject: email_subject,
    htmlBody: createEmailBody(),
  })

}

function createEmailBody() {
  // Make sure to update the emailTemplateDocId at the top.
  var docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
  var emailBody = docToHtml(docId);
  return emailBody;
}

function docToHtml(docId) {
  // Downloads a Google Doc as an HTML string.
  var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' +
            docId + '&exportFormat=html';
  var param = {
    method: 'get',
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true,
  };
  return UrlFetchApp.fetch(url, param).getContentText();
}

Form options
Loggler.log(recipient_classes) = [a, c, d]

I want to check if A is checked OR B is checked, OR C is checked, etc.

I can figure out a way to hard check if each combination of the options is selected… but I want it to be able to go through the list and check search for a certain term. It sounds like it would be something easy to code but I have been stuck for so long.

What is wrong with my JavaScript promise code

What is wrong with my code, can anybody tell me. i have just started learning about javascript and promises. i was practicing, can anybody tell me.. it is just a dummy code, i have been practicing promises and i think my code is wrong so can anybody correct my code , and suggests me the right way of doing this

type // createOrder();
// proceedToPayment();
// showOrderSummary();
// updateWallet();

const cart = [
  {
    pants: 1998,
    shoes: 2249,
    shirt: 1399,
    jacket: 4500,
  },
];

let walletBalance = 20000;

let OrderStatus = true;

createOrder(cart)
  .then(function (orderId) {
    console.log(orderId)
    return orderId;
  })
  .then(function (orderId) {
    return proceedToPayment(orderId);
  })
  .then(function (orderStatus) {
    console.log(orderStatus);
    return showOrderSummary(orderStatus);
  })
  .then(function (orderAmount) {
    return updateWallet(orderAmount);
  })
  .catch((err) => {
    console.log(err.message);
  })

function createOrder(cart) {
  const pr = new Promise(function (resolve, reject) {
    if (!validateCart(cart)) {
      const err = new Error("The cart is not valid");
      reject(err);
    }
    let orderId = "55289";
    if (orderId) {
      resolve(`the Order Id is = ${orderId}`);
    }
  });
  return pr;
}

function proceedToPayment(orderId) {
  return new Promise(function (resolve, reject) {
    if (orderId) {
      resolve(OrderStatus = true);
    } else {
      const err = new Error("Sorry! We could not process your order");
      reject(OrderStatus = false);
    }
  });
}

function showOrderSummary(orderStatus) {
    return new Promise((resolve, reject)=>{
        if(orderStatus){
            resolve("Here is the summary os your Order");
        }
        const err = new Error("The Order has Failed");
        reject(err);
    })
    
}

function updateWallet(orderAmount) {
    let keys = Object.keys(cart);
    orderAmount = 0;
    for(let i = 0; i< keys.length; i++){
        orderAmount = orderAmount + keys[i]; 
    }
    walletBalance - orderAmount;
    return walletBalance;
}

function validateCart(cart) {
  if (cart.length > 0) {
    return true;
  } else {
    return false;
  }
}

here

I want to know where i am going wrong, and what will the right way of doing this and , what will be the right resource to learn

Javascript page refresh when submit form

The default behaviour of a page when a form is submitted is to refresh, everybody knows that. I’m trying to at the same time validate my form with bootstrap and prevent my page from refreshing when the user clicks the submit button – INDEPENDENTLY of if the form was validated or not, I don’t want my page to refresh at all!

As you can see on the code snippet, I’m using checkValidity() alongisde event.preventDefault() and event.stopPropagation() to accomplish these things – and for 80% of the time, it works like a charm… except for those 20% in which occurs the exact 2 things I’m trying to prevent: the form doesn’t get validated and the page refreshes ‘-‘.

I wasn’t able to recreate this bug with the code snippet, and of course I’m not going to upload my entire project of 700+ lines of code here, so I know I’m not giving you guys the best tools to work here… even then, I’m open to you guys’s hunches, suggestions, theories, etc. Should I put and async or an await somewhere? Does the warning message “A form field element should have an id or name attribute” that appears on the console of dev tools when the form is submitted could have anything to do with this? I have no idea so any guidance is greatly appreciated!

function newFood (food) {
    const newFood = document.createElement("form");
    newFood.className = "new-food container-fluid needs-validation";
    newFood.setAttribute("novalidate", "");
    newFood.innerHTML = `
    <div class="row">
        <input class="col-6 col-md-3 form-control" required type="text" placeholder="Food name">
        <input class="col-6 col-md-3 form-control" required type="number" placeholder="Food calories">
        <select class="col-6 col-md-3 form-select" required>
            <option selected disabled>Select portion type</option>
            <option value="1 unit">1 unit</option>
            <option value="100 g">100 g</option>
        </select>
        <button class="col-6 col-md-3 btn btn-success confirm-new-food" type="submit">Create</button>
    </div>
    `;
    food.appendChild(newFood);
}

function sendFood (food) {
    const newElement = document.createElement("h1");
    newElement.textContent = "Done";
    food.appendChild(newElement);
}

document.addEventListener("DOMContentLoaded", () => {
    document.addEventListener("click", (event) => {
        if (event.target.classList.contains("new-food-form")) {
            const food = event.target.closest(".food");
            food.querySelector(".main").remove();
            newFood(food);
        }

        else if (event.target.classList.contains("confirm-new-food")) {
            const food = event.target.closest(".food");
            const newFoodForm = food.querySelector(".new-food");

            if (newFoodForm.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
                food.querySelector(".new-food").remove();
                sendFood(food);
            }

            else {
                event.preventDefault();
                event.stopPropagation();
                newFoodForm.classList.add('was-validated');
            }
        }
    });
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
        <script type="module" src="main.js"></script>
    </head>

    <body class="m-3">
        <div class="food p-4">
            <h1 class="main">Main Page
                <button class="btn btn-success new-food-form" type="button">New food form</button>
            </h1>
        </div>
    </body>
</html>

Bonus questions:

  1. Why is the pre-validated? How do I change that?
  2. Why does the input of type “number” also accepts the letter “e” AND ONLY the letter “e”?

How to get setInterval to continue running when on another screen?

Here is a simple counter https://codesandbox.io/s/jolly-sinoussi-rwkfrk?file=/src/App.js:0-684.

If you go to another screen, it stops counting. I want it to continue counting. How?

Code

import React, { useState, useEffect } from "react";

function App() {
  const [count, setCount] = useState(0);
  const [startCounting, setStartCounting] = useState(false);

  const handleCount = () => {
    setStartCounting(true);
  };

  useEffect(() => {
    let interval;
    if (startCounting) {
      interval = setInterval(() => {
        setCount((prevCount) => prevCount + 1);
      }, 10);
    }

    return () => {
      clearInterval(interval);
    };
  }, [startCounting]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => handleCount()} disabled={startCounting}>
        Start counting
      </button>
    </div>
  );
}

export default App;

I’m thinking local or session storage might be needed is there any other way?

Swiper component from react is not working, images appearing in rows

So i didnt found any information about how to solve this problem, i just npm installed swiper and everything is from default, i used npx create-react-app

import React from 'react';
import './App.css';
import { Swiper, SwiperSlide } from 'swiper/react'

import GodOfWar from './images/godofwarbanner.jpeg'
import ZeldaTotk from './images/zeldabotwbanneresticado.jpg'
import ZeldaBotw from './images/zeldabanner.jpg'
import Metro2033 from './images/metrobanneresticado.jpg'

const images = [
    GodOfWar,ZeldaTotk,ZeldaBotw,Metro2033
]

function App() {
  return (
    <div className="App">
      <div className="slider-container">
            <Swiper
              slidesPerView={1}
              pagination={{clickable: true}}
              navigation
              watchSlidesProgress
              
            >
                {images.map(image=>(
                    <SwiperSlide>
                        <img src={image} alt="" className="slide-item"/>
                    </SwiperSlide>
                ))}
            </Swiper>
        </div>
    </div>
  );
}

export default App;

enter image description here
enter image description here

i dont know what i did wrong if i did, the images should be like in a slider and hidden not appearing in bottom, also when i try to slide there isnt a next image, like the swiper isnt flex wrapping anything, i also tried to reinstall Swiper component but nothing changed